diff --git "a/1407.jsonl" "b/1407.jsonl" new file mode 100644--- /dev/null +++ "b/1407.jsonl" @@ -0,0 +1,377 @@ +{"seq_id": "483669905", "text": "from django.conf.urls import url\nfrom . import views\n\napp_name = 'account'\nurlpatterns = [\n url(r'^profile$', views.view, name='view'),\n url(r'^profile/view/(?P\\w+)$', views.view_user, name='view_user'),\n url(r'^profile/edit$', views.edit, name='edit'),\n url(r'^profile/edit/photo$', views.update_photo, name='update_photo'),\n url(r'^account$', views.preferences, name='preferences'),\n url(r'^account/payment$', views.preferences_payment, name='payment'),\n url(r'^account/close$', views.close, name='close'),\n # Usage example: $.post( \"/memo/about/2/\", \"lorem ipsum dolor sit amet\");\n url(r'^memo/about/(?P\\d+)/$', views.create_or_update_memo, name='memo')\n]\n", "sub_path": "account/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 711, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "194399612", "text": "from uuid import uuid4\n\nimport autofit as af\nfrom autofit.mock.mock import Gaussian\n\n\ndef test_float_inequality(session):\n aggregator = af.Aggregator(session)\n\n for sigma in [\n 0.9992237362814176,\n 4.9687212446221904,\n 9.967065800134504,\n ]:\n session.add(\n af.db.Fit(\n id=str(uuid4()),\n instance={\n \"gaussian\": Gaussian(\n sigma=sigma\n )\n }\n )\n )\n session.commit()\n\n assert len(aggregator) == 3\n\n assert len(aggregator.query(\n aggregator.gaussian.sigma < 3\n )) == 1\n", "sub_path": "test_autofit/database/query/test_regression.py", "file_name": "test_regression.py", "file_ext": "py", "file_size_in_byte": 660, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "autofit.Aggregator", "line_number": 8, "usage_type": "call"}, {"api_name": "autofit.db.Fit", "line_number": 16, "usage_type": "call"}, {"api_name": "autofit.db", "line_number": 16, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 17, "usage_type": "call"}, {"api_name": "autofit.mock.mock.Gaussian", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "26555873", "text": "#!/usr/bin/python3\nimport os\nimport zipfile\n\n\ndef extract_all(dir_with_zipfiles):\n os.chdir(dir_with_zipfiles)\n for zip_file in [file for file in os.listdir(os.curdir) if file.endswith(('.zip', '.ZIP'))]:\n with zipfile.ZipFile(zip_file) as zf_obj:\n for zitem in zf_obj.namelist():\n with open(str(zip_file).split('_ImageLibraryStrips')[0] + '_' + zitem, 'wb') as out_f:\n out_f.write(zf_obj.read(zitem))\n print('Файлы распакованы')\n", "sub_path": "file_extractor.py", "file_name": "file_extractor.py", "file_ext": "py", "file_size_in_byte": 507, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.chdir", "line_number": 7, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "os.curdir", "line_number": 8, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "404404451", "text": "# from parser import parse\nfrom utils import map_xyz\n\n\ndef gen_constraint_cell_d(game: list):\n \"\"\"Converts 2D list holding game in std format\n to CNF in DIMACS format for cell definedness constraint.\n\n Args:\n game (list): A 2D array of ints representing\n the start state of a sudoku game.\n\n Returns:\n str: A string representing the CNF of the constraint\n in DIMACS form.\n\n \"\"\"\n n = len(game)\n dimacs = []\n for r in range(1, n + 1):\n for c in range(1, n + 1):\n literals = []\n for v in range(1, n + 1):\n literals.append(map_xyz.map_ijk_to_num(r, c, v, n))\n clause = ' '.join(str(literal) for literal in literals)\n dimacs.append('{} 0'.format(clause))\n return '\\n'.join(dimacs)\n\n\nif __name__ == '__main__':\n \"\"\"Tests for contraint: cell definedness.\n \"\"\"\n path = '../data/p096_sudoku.txt'\n grids = parse(path)\n game = grids[1]\n print(gen_constraint_cell_d(game))", "sub_path": "ex_encode/constraint_cell_d.py", "file_name": "constraint_cell_d.py", "file_ext": "py", "file_size_in_byte": 999, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "utils.map_xyz.map_ijk_to_num", "line_number": 24, "usage_type": "call"}, {"api_name": "utils.map_xyz", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "532246707", "text": "import torch\nfrom torch.utils.data import Dataset, DataLoader\nimport logging\n\n\nclass JetDataset(Dataset):\n \"\"\"\n PyTorch dataset.\n \"\"\"\n\n def __init__(self, data, vec_dims=3, num_pts=-1, shuffle=True):\n\n self.data = data\n self.p4 = data['p4'] if vec_dims == 4 else data['p4'][..., 1:]\n\n if num_pts < 0:\n self.num_pts = len(data['Nobj'])\n else:\n if num_pts > len(data['Nobj']):\n logging.warn(f'Desired number of points ({num_pts}) is greater than '\n f'the number of data points ({len(data)}) available in the dataset!')\n self.num_pts = len(data['Nobj'])\n else:\n self.num_pts = num_pts\n\n if shuffle:\n self.perm = torch.randperm(len(data['Nobj']))[:self.num_pts]\n else:\n self.perm = None\n\n def __len__(self):\n return self.num_pts\n\n def __getitem__(self, idx):\n if self.perm is not None:\n idx = self.perm[idx]\n return self.p4[idx]\n\n\ndef initialize_data(path, batch_size, train_fraction, vec_dims=3, num_val=None):\n data = torch.load(path)\n\n jet_data = JetDataset(data, vec_dims=vec_dims, shuffle=True) # The original data is not shuffled yet\n\n if train_fraction > 1:\n num_train = int(train_fraction)\n if num_val is None:\n num_jets = len(data['Nobj'])\n num_val = num_jets - num_train\n else:\n num_others = len(data['Nobj']) - num_train - num_val\n train_set, val_set, _ = torch.utils.data.random_split(jet_data, [num_train, num_val, num_others])\n train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\n valid_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)\n return train_loader, valid_loader\n else:\n if train_fraction < 0:\n train_fraction = 0.8\n num_jets = len(data['Nobj'])\n num_train = int(num_jets * train_fraction)\n num_val = num_jets - num_train\n\n # split into training and validation set\n train_set, val_set = torch.utils.data.random_split(jet_data, [num_train, num_val])\n train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\n valid_loader = DataLoader(val_set, batch_size=batch_size, shuffle=True)\n\n logging.info('Data loaded')\n\n return train_loader, valid_loader\n\n\ndef initialize_test_data(path, batch_size, vec_dims=3):\n data = torch.load(path)\n jet_data = JetDataset(data, vec_dims=vec_dims, shuffle=False)\n return DataLoader(jet_data, batch_size=batch_size, shuffle=True)\n", "sub_path": "standard_autoencoder/utils/make_data.py", "file_name": "make_data.py", "file_ext": "py", "file_size_in_byte": 2629, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 6, "usage_type": "name"}, {"api_name": "logging.warn", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.utils.data.random_split", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 52, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.utils.data.random_split", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 66, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 76, "usage_type": "call"}]} +{"seq_id": "389000498", "text": "from PyQt5.QtCore import Qt, pyqtSignal, QObject\n\nimport math\n\nclass UnitProductionItem(QObject):\n on_value_changed = pyqtSignal()\n\n def __init__(self, unit_data, labels):\n super(UnitProductionItem, self).__init__()\n self.unit_data = unit_data\n self.labels = labels\n self.reset_labels()\n self.main_indicators_values = {\n \"MPM\": 0,\n \"GPM\": 0,\n \"SPM\": 0,\n \"supply_prov\": 0,\n }\n\n def reset_labels(self):\n for label in self.labels.values():\n label.setNum(0)\n label.setAlignment(Qt.AlignCenter)\n\n def quantity_changed(self, q_per_c):\n prod_cycles = 60 / self.unit_data[\"build_time\"]\n q_per_m = prod_cycles * q_per_c\n\n upm = 60 / self.unit_data[\"build_time\"]\n\n mpm = self.unit_data[\"minerals\"] * upm\n gpm = self.unit_data[\"vespene\"] * upm\n spm = upm * self.unit_data[\"supply\"]\n\n total_mpm = mpm * q_per_c\n total_gpm = gpm * q_per_c\n total_spm = spm * q_per_c\n\n if self.unit_data[\"race\"] == \"Terran\" and self.unit_data[\"multiplier\"]:\n prod_buildings = math.ceil(q_per_c / self.unit_data[\"multiplier\"])\n else:\n prod_buildings = q_per_c\n supply_providers = total_spm / 8\n\n self.labels[\"q_per_min\"].setNum(q_per_m)\n self.labels[\"MPM\"].setNum(total_mpm)\n self.labels[\"GPM\"].setNum(total_gpm)\n self.labels[\"SPM\"].setNum(total_spm)\n self.labels[\"Prod_buildings\"].setNum(prod_buildings)\n self.labels[\"Supply_providers\"].setNum(supply_providers)\n\n self.main_indicators_values[\"MPM\"] = total_mpm\n self.main_indicators_values[\"GPM\"] = total_gpm\n self.main_indicators_values[\"SPM\"] = total_spm\n self.main_indicators_values[\"supply_prov\"] = supply_providers\n\n self.on_value_changed.emit()", "sub_path": "unit_production_item.py", "file_name": "unit_production_item.py", "file_ext": "py", "file_size_in_byte": 1879, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "PyQt5.QtCore.QObject", "line_number": 5, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 6, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 23, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 23, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "318512968", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nQListWidget\n\"\"\"\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QListWidget,QWidget,QVBoxLayout\n\n\n\nclass mainWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.run()\n\n def run(self):\n items = []\n for i in range(1,50):\n items.append(\"Application %d\" % i)\n\n listBox = QListWidget()\n listBox.insertItems(0,items)\n listBox.insertItem(1,'insert %d' % listBox.__len__())\n listBox.resize(200,150)\n listBox.move(10,10)\n layout = QVBoxLayout()\n layout.addWidget(listBox)\n self.setLayout(layout)\n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Tooltips')\n self.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n mw = mainWindow()\n sys.exit(app.exec_())\n", "sub_path": "Python3/PyQt5/Qt6.py", "file_name": "Qt6.py", "file_ext": "py", "file_size_in_byte": 847, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 10, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QListWidget", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 33, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 33, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "586408022", "text": "import os\nimport time\nimport numpy as np\nimport nibabel as nib\nimport cv2\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.decomposition import PCA, KernelPCA\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn import linear_model\nfrom sklearn.svm import SVR\nfrom sklearn.metrics import mean_squared_error\n\nimport matplotlib\nmatplotlib.use('Agg') # for server w/o display\nimport matplotlib.pyplot as plt\n\ndef real_train_test(X, y, train_size, clf):\n clf.fit(X[:train_size], y[:train_size], get_weights(y[:train_size], n_bin = 10))\n return clf.predict(X[train_size:])\n\ndef write_submission(y):\n with open(\"final_sub.csv\", \"w\") as fw:\n #fw.write(\"ID,Prediction\\n\")\n fw.write('\"ID\",\"Prediction\"\\n')\n i = 1\n for yi in y:\n fw.write(\"{},{:.20f}\\n\".format(i, yi))\n i += 1\n\ndef plot_pca_data(pca, features_new, labels):\n for i in range(3):\n fig, ax = plt.subplots()\n ax.scatter(features_new[:,i], labels[:])\n ax.plot([features_new.min(), features_new.max()], [labels.min(), labels.max()], ls=\"--\", lw=4)\n ax.set_xlabel('pc{}'.format(i))\n ax.set_ylabel('label')\n plt.savefig(\"./pc{}_cv10.png\".format(i))\n fig, ax = plt.subplots()\n ax.plot(pca.explained_variance_, linewidth=2)\n plt.savefig(\"./explained_variance.png\".format(i))\n\ndef plot_cv_prediction(labels, predicted):\n fig, ax = plt.subplots()\n ax.scatter(labels, predicted)\n ax.plot([labels.min(), labels.max()], [predicted.min(), predicted.max()], ls=\"--\", lw=4)\n ax.set_xlabel('Measured')\n ax.set_ylabel('Predicted')\n plt.savefig(\"./regression_cv10.png\")\n\ndef get_weights(train_label, n_bin = 10):\n hist = np.histogram(train_label, bins=n_bin)\n counts = hist[0]\n bins = hist[1]\n n_label = sum(bins)\n weights = []\n for l in train_label:\n bin_id = next(b[0] for b in enumerate(bins) if b[1] >= l) - 1\n #print(l, bins[bin_id]/n_label)\n weights.append(bins[bin_id]/n_label)\n return weights\n", "sub_path": "mlp2/src/myutil.py", "file_name": "myutil.py", "file_ext": "py", "file_size_in_byte": 2075, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.use", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "numpy.histogram", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "419448757", "text": "import os\n\nfrom hatch.create import create_package\nfrom hatch.settings import copy_default_settings\nfrom hatch.utils import temp_chdir\nfrom hatch.files.coverage.codecov import TEMPLATE\nfrom ...utils import read_file\n\n\ndef test_no_coverage():\n with temp_chdir() as d:\n settings = copy_default_settings()\n settings['basic'] = False\n settings['coverage'] = ''\n create_package(d, 'ok', settings)\n\n assert not os.path.exists(os.path.join(d, '.codecov.yml'))\n\n\ndef test_basic():\n with temp_chdir() as d:\n settings = copy_default_settings()\n settings['basic'] = True\n settings['coverage'] = 'codecov'\n create_package(d, 'ok', settings)\n\n assert not os.path.exists(os.path.join(d, '.codecov.yml'))\n\n\ndef test_correct():\n with temp_chdir() as d:\n settings = copy_default_settings()\n settings['basic'] = False\n settings['coverage'] = 'codecov'\n create_package(d, 'ok', settings)\n\n assert read_file(os.path.join(d, '.codecov.yml')) == TEMPLATE\n", "sub_path": "tests/files/coverage/test_codecov.py", "file_name": "test_codecov.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "hatch.utils.temp_chdir", "line_number": 11, "usage_type": "call"}, {"api_name": "hatch.settings.copy_default_settings", "line_number": 12, "usage_type": "call"}, {"api_name": "hatch.create.create_package", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "hatch.utils.temp_chdir", "line_number": 21, "usage_type": "call"}, {"api_name": "hatch.settings.copy_default_settings", "line_number": 22, "usage_type": "call"}, {"api_name": "hatch.create.create_package", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "hatch.utils.temp_chdir", "line_number": 31, "usage_type": "call"}, {"api_name": "hatch.settings.copy_default_settings", "line_number": 32, "usage_type": "call"}, {"api_name": "hatch.create.create_package", "line_number": 35, "usage_type": "call"}, {"api_name": "utils.read_file", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "hatch.files.coverage.codecov.TEMPLATE", "line_number": 37, "usage_type": "name"}]} +{"seq_id": "599045642", "text": "import sys\nfrom cx_Freeze import setup, Executable\n\n# Dependencies are automatically detected, but it might need fine tuning.\nbuild_exe_options = {\"packages\": [\"matplotlib\"],\n \"excludes\": [\"tkinter\",\"collections.abc\"],\n \"includes\": [\"numpy\",\"PyQt4.QtCore\",\"PyQt4.QtGui\",\"matplotlib\",\"sip\",\"sys\"] }\n\n# GUI applications require a different base on Windows (the default is for a\n# console application).\nbase = None\nif sys.platform == \"win32\":\n base = \"Win32GUI\"\n\nsetup( name = \"TempMonitor\",\n version = \"0.1\",\n description = \"Temperature monitoring GUI application\",\n options = {\"build_exe\": build_exe_options},\n executables = [Executable(\"Temp_monitor.py\", base=base)])\n", "sub_path": "python/setup_cx_freeze.py", "file_name": "setup_cx_freeze.py", "file_ext": "py", "file_size_in_byte": 740, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.platform", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cx_Freeze.setup", "line_number": 15, "usage_type": "call"}, {"api_name": "cx_Freeze.Executable", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "468526053", "text": "#!/usr/bin/env python\n#\n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\nimport bleach\n\n\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=tournament\")\n\n\ndef deleteTournaments():\n \"\"\"Remove all the tournaments records from the database.\"\"\"\n conn = connect()\n query = \"\"\"delete from tournaments cascade;\"\"\"\n c = conn.cursor()\n c.execute(query)\n conn.commit()\n conn.close()\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n conn = connect()\n query = \"\"\"delete from matches cascade;\"\"\"\n c = conn.cursor()\n c.execute(query)\n conn.commit()\n conn.close()\n\n\ndef deletePlayersC():\n \"\"\"Remove all the player records from the database.\"\"\"\n conn = connect()\n query = \"\"\"delete from players_c cascade;\"\"\"\n c = conn.cursor()\n c.execute(query)\n conn.commit()\n conn.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the registrations of all players from the database.\"\"\"\n conn = connect()\n query = \"\"\"delete from players cascade;\"\"\"\n c = conn.cursor()\n c.execute(query)\n conn.commit()\n conn.close()\n\n\ndef countTournaments():\n \"\"\"Returns the number of tournaments in the database.\"\"\"\n conn = connect()\n query = \"\"\"select count(t_name) as nb from tournaments;\"\"\"\n c = conn.cursor()\n c.execute(query)\n result = c.fetchall()\n conn.close()\n return result[0][0]\n\n\ndef countRegisteredPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n conn = connect()\n query = \"\"\"select count(id_player) as nb from players;\"\"\"\n c = conn.cursor()\n c.execute(query)\n result = c.fetchall()\n conn.close()\n return result[0][0]\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n conn = connect()\n query = \"\"\"select count(p_sname) as nb from players_c;\"\"\"\n c = conn.cursor()\n c.execute(query)\n result = c.fetchall()\n conn.close()\n return result[0][0]\n\n\ndef countMatches():\n \"\"\"Returns the number of players currently registered.\"\"\"\n conn = connect()\n query = \"\"\"select count(id_match) as nb from matches;\"\"\"\n c = conn.cursor()\n c.execute(query)\n result = c.fetchall()\n conn.close()\n return result[0][0]\n\n\ndef registerTournament(t_name):\n \"\"\"Adds a tournament to the tournament table.\n\n The database assigns a unique serial id number for the tournament.\n\n Args:\n t_name(str): the tournament's name.\n \"\"\"\n conn = connect()\n t_name = bleach.clean(t_name)\n query = \"insert into tournaments (t_name) values (%s)\"\n c = conn.cursor()\n c.execute(query, (t_name,))\n conn.commit()\n conn.close()\n\n\ndef registerPlayer(f_name, name):\n \"\"\"Adds a player to the player_c table.\n\n The database assigns a unique serial id number for the player.\n\n Args:\n f_name(str): the player's first name.\n name(str): the player's name\n \"\"\"\n conn = connect()\n f_name = bleach.clean(f_name)\n name = bleach.clean(name)\n query = \"insert into players_c (p_sname, p_name) values (%s, %s)\"\n c = conn.cursor()\n c.execute(query, (f_name, name))\n conn.commit()\n conn.close()\n\n\ndef getTournamentId(tournament_name):\n \"\"\"Utility function to retrieve a tournament id using its name\n\n Args:\n tournament_name(str): the name of the tournament\n\n Returns:\n the unique id of a tournament (int).\n\n .. note::\n We take the first tournament we find in the db!!!\"\"\"\n\n # get the tournament's id\n conn = connect()\n c = conn.cursor()\n tournament_name = bleach.clean(tournament_name)\n query = \"select id_tournament from tournaments where t_name=%s\"\n c.execute(query, (tournament_name,))\n t_id = c.fetchall()\n conn.close()\n return t_id[0][0]\n\n\ndef getPlayerId(p_sname, p_name):\n \"\"\"Utility function to retrieve a player id using his first and last names\n\n Args:\n p_sname(str): the first name of the player\n p_name(str): the last name of the player\n\n Returns:\n the unique id of a player from the players_c table (int).\n\n .. note::\n We take the first player we find in the db!!!\"\"\"\n\n # get the player's id\n conn = connect()\n c = conn.cursor()\n p_sname = bleach.clean(p_sname)\n p_name = bleach.clean(p_name)\n condition = \"where p_sname=%s and p_name=%s\"\n query = \"select id_player_c from players_c \" + condition\n c.execute(query, (p_sname, p_name))\n p_id = c.fetchall()\n conn.close()\n return p_id[0][0]\n\n\ndef registerPlayerTournament(p_id, t_id):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player, tournament\n pair. We use the player id from the players_c table and the tournament\n id from the tournaments table.\n\n Args:\n p_id(int): the player's unique id from the players_c table.\n t_id(int): the tournament's unique id from the tournaments table\n \"\"\"\n # register a player in a tournament\n conn = connect()\n c = conn.cursor()\n # no need to clean because we get this data from the db\n query = \"\"\"insert into players (id_player_c, tournament) values (%s, %s)\"\"\"\n c.execute(query, (p_id, t_id))\n conn.commit()\n conn.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a\n player tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, p_sname, p_name, tournament\n wins, matches, tournament_id):\n id(int): the player's unique id (assigned by the database)\n p_sname(str): the player's first name (as registered)\n p_name(str): the player's last name (as registered)\n wins(int): the number of matches the player has won\n matches(int): the number of matches the player has played\n \"\"\"\n\n conn = connect()\n c = conn.cursor()\n query = \"select * from playstats;\"\n c.execute(query)\n players_reg = c.fetchall()\n conn.close()\n return players_reg\n\n\ndef reportMatch(score_p1, score_p2, tournament, p1, p2):\n \"\"\"\n Records the outcome of a single match between two players.\n\n Args:\n id_p1(int): the id number of the player 1\n id_p2(int): the id number of the player 2\n score_p1(int): the score of the player 1\n score_p2(int): the score of the player 2\n tournament(int): the id number of the tournament\n \"\"\"\n conn = connect()\n c = conn.cursor()\n # build the inserts for the match\n assert p1 != p2, \"You have to use two different player ids!\"\n match_val = \"(%s, %s, %s, %s, %s)\"\n # add a new match between those 2 players\n query = \"insert into matches \\\n (score_p1, score_p2, tournament, id_p1, id_p2) values \" + match_val\n\n c.execute(query, (score_p1, score_p2, tournament, p1, p2))\n conn.commit()\n\n # update matches variable in the players table\n\n condition = \"where id_player = {} or id_player = {};\".format(p1, p2)\n query = \"update players set matches = matches + 1 {}\"\n c.execute(query.format(condition))\n conn.commit()\n\n # update wins variable in the players table\n if score_p1 > score_p2:\n condition = \"where id_player = {};\".format(p1)\n query = \"update players set wins = wins + 1 {}\"\n c.execute(query.format(condition))\n conn.commit()\n elif score_p2 > score_p1:\n condition = \"where id_player = {};\".format(p2)\n query = \"update players set wins = wins + 1 {}\"\n c.execute(query.format(condition))\n conn.commit()\n conn.close()\n\n\ndef swissPairingsPython():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n USING PYTHON!\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1(int): the first player's unique id\n p_sname1(str): the first player's first name\n p_sname1(str): the first player's last name\n id2(int): the second player's unique id\n p_sname2(str): the second player's first name\n p_sname1(str): the second player's last name\n \"\"\"\n\n conn = connect()\n c = conn.cursor()\n standings = playerStandings()\n # because the view returns players ordered by wins\n l_of_tup = []\n for i in range(0, len(standings)-1, 2):\n p1 = standings[i]\n p2 = standings[i+1]\n l_of_tup.append((p1[0], p1[1], p1[2],\n p2[0], p2[1], p2[2]))\n return l_of_tup\n\n\ndef swissPairingsSQL():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n USING A VIEW IN THE DATABASE!\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1(int): the first player's unique id\n p_sname1(str): the first player's first name\n p_sname1(str): the first player's last name\n id2(int): the second player's unique id\n p_sname2(str): the second player's first name\n p_sname1(str): the second player's last name\n \"\"\"\n\n conn = connect()\n c = conn.cursor()\n query = \"select * from pairing\"\n c.execute(query)\n pairing = c.fetchall()\n conn.close\n return pairing\n", "sub_path": "vagrant/tournament/tournament.py", "file_name": "tournament.py", "file_ext": "py", "file_size_in_byte": 9895, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "psycopg2.connect", "line_number": 12, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 108, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 126, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 127, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 150, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 174, "usage_type": "call"}, {"api_name": "bleach.clean", "line_number": 175, "usage_type": "call"}]} +{"seq_id": "629456463", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 16 11:13:17 2018\r\n\r\n\r\n\"\"\"\r\n\r\n#merge sort is so called advance sort\r\n#basically its like a binary search\r\n#we keep dividing the list into two parts\r\n#until it reaches base case there are only two elements\r\n#we sort the two elements and combine two sublists together \r\n#we do a traversal on both sublists\r\n#we run through elements one by one\r\n#we compare two lists with each other and insert into the bigger list\r\n#its like shuffling poker\r\n#say u got 1 and 2 from two different sublists\r\n#1 is smaller than 2\r\n#we insert 1 back to the bigger list\r\n#the second element is 1.5\r\n#it is still smaller than 2\r\n#we keep inserting elements from a sorted sublist\r\n#until the element is larger than 2\r\n#now we insert 2 into the bigger list\r\n#we keep doing the same procedure until we come back to the whole list\r\n#we do a final sort, its all done\r\n\r\n#from my description, u can easily tell that we may need recursion\r\n#i assume that is why its slowing down the sorting\r\n#if we replace recursion with memory or iterations\r\n#it is supposed to be faster than insertion\r\ndef mer(list):\r\n \r\n #so this is to check the base case\r\n #we wanna make sure the base case is a sublist with two elements\r\n #otherwise we got nothing to sort\r\n if len(list)>1:\r\n \r\n #this is how we keep splitting the list into two halves\r\n ind=len(list)//2\r\n \r\n #we set each half as an individual list\r\n #then we run the same trick on each half recursively\r\n left=list[:ind]\r\n right=list[ind:]\r\n mer(left)\r\n mer(right)\r\n \r\n #let me denote i as the index in left list\r\n #j as the index in right list\r\n #k as the index in right and left combined list\r\n i=0\r\n j=0\r\n k=0\r\n \r\n #now we have three scenarios\r\n #the first case is both indexes are under list length\r\n #so we can compare two element in the list\r\n #we put the larger one into a bigger list\r\n #we increase the index by 1 \r\n #which we just moved the element to a bigger list\r\n #we come back to the loop to see which element is bigger\r\n while i=len(right):\r\n list[k]=left[i]\r\n i+=1\r\n k+=1\r\n \r\n #vice versa\r\n while i>=len(left) and j 0\\n緑 => 1\\n白 => 2\\n青 => 3\")\n max_i = input('>>> ')\n print(\"max_i: \",max_i)\n'''\n\nclass App:\n def __init__(self, window, window_title):\n self.window = window\n self.window.overrideredirect(True)\n self.window.attributes('-fullscreen', True)\n self.window.attributes('-topmost', True)\n self.window.overrideredirect(False)\n self.window.bind(\"\", lambda e: e.widget.quit())\n self.window.title(window_title)\n\n # Create a canvas that can fit the above video source size\n self.canvas = tkinter.Canvas(window, width = window_w, height = window_h)\n self.canvas.pack()\n self.panels = []\n self.seq = 0\n \n im = Image.open(img_paths[self.seq])\n self.photo = PIL.ImageTk.PhotoImage(image = im.resize((window_w, window_h)))\n \n self.delay = int(length_seconds / num_of_frames * 1000)\n print(self.delay, \"s\")\n\n # パネルの情報を読み込み\n for i in range(4):\n path = \"../datas/champ_panels\" + str(i) + \".txt\"\n self.data = open(path, \"r\")\n self.panels.append(self.data.readlines())\n\n num_panels = [self.panels[i].__len__() for i in range(4)]\n np_array = np.array(num_panels)\n max_index = [i for i, x in enumerate(np_array) if x == max(np_array)]\n if max_index.__len__() == 1:\n self.max_i = max_index[0]\n num = self.panels[self.max_i].__len__()\n else:\n for i in max_index:\n print(color_names[i], \",\") \n print(\"が同率首位です.どちらが優勝者か入力してください.\")\n print(\"赤 => 0\\n緑 => 1\\n白 => 2\\n青 => 3\")\n self.max_i = int(input(''))\n\n for k in reversed(range(self.panels[self.max_i].__len__())):\n self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)\n for i in range(k):\n n = int(self.panels[self.max_i][i])\n x = panel_w * (n%PANEL_NUM)\n y = panel_h * (n//PANEL_NUM)\n self.canvas.create_rectangle(x, y, x+panel_w, y+panel_h, fill=colors[self.max_i], tag='free', width=4)\n self.canvas.create_text(x+(panel_w/2),y+(panel_h/2),text=str(n+1),font=TEXT_FONT, tag='label')\n \n for i in range(4):\n if i != self.max_i:\n for n_str in self.panels[i]:\n n = int(n_str)\n x = panel_w * (n%PANEL_NUM)\n y = panel_h * (n//PANEL_NUM)\n self.canvas.create_rectangle(x, y, x+panel_w, y+panel_h, fill=colors[i], tag='free', width=4)\n self.canvas.create_text(x+(panel_w/2),y+(panel_h/2),text=str(n+1),font=TEXT_FONT, tag='label')\n \n sleep(0.5)\n self.window.update()\n\n th = threading.Thread(name=\"a\", target=sound.play)\n th.start()\n\n # After it is called once, the update method will be automatically called every delay milliseconds\n self.update()\n\n self.window.mainloop()\n\n \n def update(self):\n im = Image.open(img_paths[self.seq])\n im_resize = im.resize((window_w, window_h))\n self.photo = PIL.ImageTk.PhotoImage(image = im_resize)\n self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)\n \n for i in range(4):\n if i != self.max_i:\n for n_str in self.panels[i]:\n n = int(n_str)\n x = panel_w * (n%PANEL_NUM)\n y = panel_h * (n//PANEL_NUM)\n self.canvas.create_rectangle(x, y, x+panel_w, y+panel_h, fill=colors[i], tag='free', width=4)\n self.canvas.create_text(x+(panel_w/2),y+(panel_h/2),text=str(n+1),font=TEXT_FONT, tag='label')\n \n # Get a frame from the video source\n if self.seq < num_of_frames-1:\n self.seq += 1\n\n print(\"seq: \", self.seq, \"num: \", num_of_frames)\n\n self.window.after(self.delay, self.update)\n\n\nclass MyVideoCapture:\n def __init__(self):\n # Get video source width and height\n im = Image.open(img_paths[self.seq])\n im_resize = im.resize((window_w, window_h))\n self.photo = PIL.ImageTk.PhotoImage(image = im_resize)\n self.height, self.width, self.channels = im_resize.shape\n \n# Create a window and pass it to the Application object\nroot = tkinter.Tk()\nwindow_w, window_h = root.winfo_screenwidth(), root.winfo_screenheight()\npanel_w = int(window_w / PANEL_NUM)\npanel_h = int(window_h / PANEL_NUM)\n\nApp(root, \"最終問題\")\n", "sub_path": "src/film_quiz.py", "file_name": "film_quiz.py", "file_ext": "py", "file_size_in_byte": 6421, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pygame.mixer.pre_init", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.mixer.init", "line_number": 40, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 41, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 46, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 84, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 89, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 89, "usage_type": "name"}, {"api_name": "PIL.Image.ImageTk.PhotoImage", "line_number": 90, "usage_type": "call"}, {"api_name": "PIL.Image.ImageTk", "line_number": 90, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 90, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 102, "usage_type": "call"}, {"api_name": "tkinter.NW", "line_number": 115, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 132, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 135, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 145, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 145, "usage_type": "name"}, {"api_name": "PIL.Image.ImageTk.PhotoImage", "line_number": 147, "usage_type": "call"}, {"api_name": "PIL.Image.ImageTk", "line_number": 147, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 147, "usage_type": "name"}, {"api_name": "tkinter.NW", "line_number": 148, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 171, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 171, "usage_type": "name"}, {"api_name": "PIL.Image.ImageTk.PhotoImage", "line_number": 173, "usage_type": "call"}, {"api_name": "PIL.Image.ImageTk", "line_number": 173, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 173, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 177, "usage_type": "call"}]} +{"seq_id": "432535682", "text": "\n\nimport pymysql\n\n# 打开数据库连接\ndb = pymysql.connect(\"localhost\", \"root\", \"123456\", \"python\")\n\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\n\n# 使用 execute() 方法执行 SQL 查询\ncursor.execute(\"UPDATE xiaoliu SET name='jdSDds' WHERE id<5\")\ndb.commit()\n# 使用 fetchone() 方法获取单条数据.\ndata = cursor.fetchone()\n\nprint(\"Database version : %s \" % data)\n\n# 关闭数据库连接\ndb.close()", "sub_path": "test/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 447, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymysql.connect", "line_number": 6, "usage_type": "call"}]} +{"seq_id": "590455949", "text": "from django import forms\n\nfrom resturants.models import ResturantLocation\n\nfrom .models import Item\n\nclass ItemForm(forms.ModelForm):\n class Meta:\n model = Item\n fields = [\n 'resturant',\n 'name',\n 'contents',\n 'excludes',\n 'public'\n ]\n\n def __init__(self, user=None, *args, **kwargs):\n print(user)\n #print(kwargs.pop('instance'))\n super(ItemForm, self).__init__(*args, **kwargs)\n self.fields['resturant'].queryset = ResturantLocation.objects.filter(owner=user) #.exclude(item__isnull=False)", "sub_path": "menus/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 600, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.forms.ModelForm", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 7, "usage_type": "name"}, {"api_name": "models.Item", "line_number": 9, "usage_type": "name"}, {"api_name": "resturants.models.ResturantLocation.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "resturants.models.ResturantLocation.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "resturants.models.ResturantLocation", "line_number": 22, "usage_type": "name"}]} +{"seq_id": "532440822", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nX=np.array([1,3,5,7])\nprint(type(X))\nprint(X)\n\nY=np.arange(-np.pi,np.pi,0.1)\nprint(type(Y))\nprint(Y)\n\nZ=np.linspace(0,5,10)\nprint(type(Z))\nprint(np.size(Z))\n\nT=np.zeros(7)\nprint(T)\n\nX=np.linspace(-2,2,10)\nY=np.zeros(10)\nfor k in range(10):\n Y[k]=(X[k])**2\nprint(Y)\n\nX = np.arange(-np.pi,np.pi,0.1)\nY = np.sin(X)\nprint(Y)\n\nX = np.arange(1,10,1)\nprint(X)\ndef fact(n):\n p = 1\n for k in range(1,n):\n p = p*k\n return(p)\nvfact = np.vectorize(fact)\nY = vfact(X)\nprint(Y)\n\nl=[2,3,0]\nm=np.array(l)\nn=vfact(m)\n\nX = np.linspace(-2,2,10)\nY = X**2\nplt.axis(\"equal\")\nplt.plot(X,Y)\nplt.show()\n\nT = np.linspace(0,10,100)\nX = T*np.cos(T)\nY = T*np.sin(T)\nplt.axis(\"equal\")\nplt.plot(X,Y)\nplt.show()\n\nT = np.linspace(0,10,100)\nY = np.sin(T)\nplt.axis(\"equal\")\nplt.plot(T,Y)\nplt.show()\n\nT = [k*0.3 for k in range(100)]\nX = [0.01*t*np.cos(t) for t in T]\nY = [0.01*t*np.sin(t) for t in T]\nplt.axis(\"equal\")\nplt.plot(X,Y)\nplt.show()\n\nT = np.linspace(-10,10,10000)\nY=np.arctan(T**2+5*T)\nplt.axis([0,10,-5,30])\nplt.axis(\"equal\")\nplt.plot(T,Y,color=\"red\",linewidth=3,linestyle=\"--\")\nplt.title(\"Marmite\")\nplt.show()\n\nT = np.linspace(-10,10,10000)\nY=np.arcsin(T**2+5*T)\nZ=np.sin(T**2+5*T)\nW=T\nplt.plot(T,Y,color=\"red\",label='arcsin')\nplt.plot(T,Z,color=\"green\",label='sin')\nplt.plot(T,W,color=\"brown\",label='y=x')\nplt.axis(\"equal\")\nplt.title(\"Marmite\")\nplt.show()\n\nimport math\n\nX = [k*0.01 for k in range(157)]\nY = [math.sin(x) for x in X]\nplt.plot(X,Y,color='blue', label = 'sin')\nplt.plot(Y,X,color='red', label = 'arcsin')\nplt.plot(X,X,color='green', linestyle = ':', label = 'y=x')\nplt.axis(\"equal\")\nplt.legend()\nplt.show()\n\n", "sub_path": "TD/TD6.py", "file_name": "TD6.py", "file_ext": "py", "file_size_in_byte": 1658, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 4, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "numpy.cos", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.arctan", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.arcsin", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "math.sin", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}]} +{"seq_id": "129387177", "text": "#! /usr/local/bin/python\n\nimport sys\nimport platform\nfrom selenium import webdriver\n\nif len(sys.argv) != 3:\n\tprint(\"USAGE: \" + sys.argv[0] + \" \")\n\tquit()\n\nBrowser = sys.argv[1]\nWebpage = sys.argv[2]\n\nprint(\"Opening \" + Webpage + \" wtih \" + Browser)\nprint(\"Opening \" + Browser)\n\nif Browser == \"Chrome\":\n\n\toptions = webdriver.ChromeOptions()\n\toptions.add_experimental_option(\"excludeSwitches\", [\"ignore-certificate-errors\"])\n\tdriver = webdriver.Chrome(chrome_options=options)\n\nelif Browser == \"Firefox\":\n\n\tdriver = webdriver.Firefox()\n\nelif Browser == \"IE\":\n\n\tif platform.system() != \"Windows\":\n\t\tprint(\"IE is only available on Windows\")\n\t\tquit()\n\n\tdriver = webdriver.Ie()\n\nelse:\n\tprint(Browser + \" is not a supported browser\")\n\tquit()\n\nprint(\"Browsing to \" + Webpage)\ndriver.get(Webpage)\n\nprint(\"Getting webpage title\")\nprint(\"\\n\" + driver.title + \"\\n\")\n\nprint(\"Closing \" + Browser)\ndriver.close()\nquit()\n", "sub_path": "Python/Browse.py", "file_name": "Browse.py", "file_ext": "py", "file_size_in_byte": 957, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 19, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 19, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 21, "usage_type": "name"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 25, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 25, "usage_type": "name"}, {"api_name": "platform.system", "line_number": 29, "usage_type": "call"}, {"api_name": "selenium.webdriver.Ie", "line_number": 33, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 33, "usage_type": "name"}]} +{"seq_id": "612735817", "text": "# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport re, os, sys, random\nimport pandas as pd\nimport json\nimport time, datetime\nimport lxml\nfrom multiprocessing import Pool, Process\nfrom requests import adapters\n\n# 思考日期怎么用,要不要作为一个基础的参数\ndef to_min_bar(df):\n df['presentPrice'] = list(map(lambda x: float(x), df['presentPrice']))\n df['volume'] = list(map(lambda x: int(x), df['volume']))\n df['hand'] = list(map(lambda x: int(x), df['hand']))\n df['volume_money'] = df['presentPrice'] * df['volume'] * df['hand']\n grouped = df.groupby('time')\n bar = grouped.agg({'presentPrice': ['first', 'max', 'min', 'last'], 'volume': 'sum', 'volume_money': 'sum'}).rename(\n columns={\"first\": \"open\", \"max\": \"high\", \"min\": \"low\", \"last\": \"close\", \"sum\": \"volume\"}\n )\n col_name = ['open', 'high', 'low', 'close', 'volume', 'volume_money']\n bar.columns = col_name\n # bar.index.name = None\n bar = bar.rename_axis(None, axis=0) # 重命名index或者columns的name,与 bar.index.name = None 等价\n bar['time'] = bar.index\n new_col_name = ['time'] + col_name\n print(new_col_name)\n bar = bar.reindex(columns=new_col_name)\n print(bar.head())\n\n return bar\n\n\ndef time_transfer(t_ms):\n timeStamp = t_ms / 1000.0\n timeArray = datetime.datetime.fromtimestamp(timeStamp)\n t_format = timeArray.strftime(\"%H:%M\")\n return t_format\n\n\ndef full_fuction(code):\n #target_path = \"E:/Project/spider/zhongxin_min_bar/zhongxin_bar_data/\"\n #tick_data_path = \"E:\\\\Project\\\\spider\\\\zhongxin_spider\\\\stock_data_tick\\\\\"\n target_path = \"/home/hyc/Project/hanyuntest/spider/zhongxin_min_bar/zhongxin_bar_data/\"\n tick_data_path = \"/home/hyc/Project/hanyuntest/spider/zhongxin_spider/stock_data_tick/\"\n cur_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n csv_file = tick_data_path + cur_date + \"/\" + str(code) + \".csv\"\n if not os.path.exists(csv_file):\n print(\"%s股票源数据不存在\"%code)\n return\n df = pd.read_csv(csv_file, dtype='str', encoding='utf-8')\n if df is None:\n print(\"!!!!%s股票minute_bar数据保存失败!!!!\" % code)\n return\n try:\n bar = to_min_bar(df)\n except:\n print(\"!!!!%s股票minute_bar数据保存失败!!!!\" % code)\n return\n\n filename = target_path + cur_date +'/'+str(code) + '.csv'\n with open(filename, 'w+') as f:\n bar.to_csv(f, index=False)\n if os.path.exists(filename):\n print(\"%s股票minute_bar数据保存成功\"%code)\n else:\n print(\"!!!!%s股票minute_bar数据保存失败!!!!\"%code)\n\n\nif __name__ == \"__main__\":\n #target_path = \"E:/Project/spider/zhongxin_min_bar/zhongxin_bar_data/\"\n #stocklist_file = \"E:/Project/spider/zhongxin_spider/stock_data_tick/stocklist.csv\"\n cur_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n trading_calendar = pd.read_csv(\"/home/hyc/Project/hanyuntest/calendar/china_futures_calendar_2017_2018.csv\")\n if cur_date not in list(trading_calendar['days']):\n print(\"%s不是交易日\"%cur_date)\n sys.exit(0)\n else:\n print(\"%s是交易日\"%cur_date)\n target_path = \"/home/hyc/Project/hanyuntest/spider/zhongxin_min_bar/zhongxin_bar_data/\"\n stocklist_file = \"/home/hyc/Project/hanyuntest/spider/zhongxin_spider/stock_data_tick/stocklist.csv\"\n \n code_df = pd.read_csv(stocklist_file, dtype='str', encoding=\"utf-8\") # dtype='str',\n code_df['code'] = list(map(lambda x: str(x), code_df['code']))\n if os.path.exists(target_path + cur_date):\n print(\"%s目录已创建\" % cur_date)\n else:\n os.mkdir(target_path + cur_date)\n pool = Pool(processes=4)\n pool.map(full_fuction, code_df['code'])\n pool.close()\n pool.join()\n\n print(\"名单上的股票数量:%s只\" % len(code_df))\n print(\"实际保存数据的股票数量:%s只\" % len([name for name in os.listdir(target_path + cur_date)]))\n print(\"\\n%s--minute_bar数据处理完成\" % cur_date)\n", "sub_path": "spider/zhongxin_min_bar/zhongxin_bar_data_module.py", "file_name": "zhongxin_bar_data_module.py", "file_ext": "py", "file_size_in_byte": 4059, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.fromtimestamp", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 37, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 75, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 78, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path", "line_number": 86, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 89, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 90, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 96, "usage_type": "call"}]} +{"seq_id": "519409916", "text": "# interpreting results\n\nimport csv\nimport pandas as pd\nimport plotly.express as px\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\nrows = []\nwith open(\"main.csv\",\"r\") as f: \n csvreader = csv.reader(f) \n for row in csvreader:\n rows.append(row)\n\nheaders = row[0]\nplanet_data_rows = row[1:]\n\nplanet_masses = []\nplanet_radiuses = []\nplanet_names = []\nfor planet_data in planet_data_rows:\n planet_masses.append(planet_data[3]) \n planet_radiuses.append(planet_data[7])\n planet_names.append(planet_data[11]) \n\nplanet_gravity = []\nfor index, value in enumerate(planet_names):\n gravity = (float(planet_masses[index])*1.989e+30) / (float(planet_radiuses[index])*float(planet_radiuses[index])*.989e+30)\n planet_gravity.append(gravity)\n\nfig = px.scatter(x=planet_radiuses, y=planet_masses, size=planet_gravity, hover_data=[planet_names])\nfig.show()\n\nX = []\nfor index, planet_mass in enumerate(planet_masses): \n temp_list = [\n planet_radiuses[index],\n planet_mass\n ]\n X.append(temp_list)\n\nwcss = []\nfor i in range(1, 11): \n kmeans = KMeans(n_clusters=i, init='k-means++', random_state = 42) \n kmeans.fit(X) \n wcss.append(kmeans.inertia_)\n\nplt.figure(figsize=(10,5))\nsb.lineplot(range(1, 11), wcss, marker='o', color='red')\nplt.title('The Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show()\n\ngravity_planets_range = []\nfor index, gravity in enumerate(planet_gravity):\n if gravity<300 and gravity>150: \n gravity_planets_range.append(planet_data_rows[index])\n\nsuitable_planets = []\nfor planet_data in gravity_planets_range: \n if planet_data[2] <= 100:\n suitable_planets.append(planet_data)\n\nprint(len(suitable_planets))\n\nplanet_distance = []\nfor planet_data in planet_data_rows:\n planet_distance.append(planet_data[8]) \n\ngraph1 = px.bar(x = planet_names, y = planet_mass)\ngraph2 = px.bar(x = planet_names, y = planet_radiuses)\ngraph3 = px.bar(x = planet_names, y = planet_gravity)\ngraph4 = px.bar(x = planet_names, y = planet_distance)\n\ngraph1.show()\ngraph2.show()\ngraph3.show()\ngraph4.show()\n\n\n\n", "sub_path": "hw40.py", "file_name": "hw40.py", "file_ext": "py", "file_size_in_byte": 2136, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "csv.reader", "line_number": 12, "usage_type": "call"}, {"api_name": "plotly.express.scatter", "line_number": 32, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 32, "usage_type": "name"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "plotly.express.bar", "line_number": 72, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 72, "usage_type": "name"}, {"api_name": "plotly.express.bar", "line_number": 73, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 73, "usage_type": "name"}, {"api_name": "plotly.express.bar", "line_number": 74, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 74, "usage_type": "name"}, {"api_name": "plotly.express.bar", "line_number": 75, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "576990290", "text": "#!/usr/bin/python\nimport os\nimport re\nimport sys\nimport csv\nimport json\nimport pandas\nimport installLib\n\nrequiredConfigParameters = [\"dataFolder\"]\n\n# Load the configuration file.\nconfig = json.loads(installLib.readFile(\"config/config.json\"))\nfor requiredConfigParameter in requiredConfigParameters:\n if not requiredConfigParameter in config.keys():\n print(\"Error - required value \" + requiredConfigParameter + \" not set in config.json.\")\n sys.exit(1)\n \n# Read the existing basic staff details. Headings:\n# GUID,UserCode,Title,GivenName,FamilyName,DateOfBirth,Username,Identifier,Form,Role,JobTitle,TelephoneNumber\nstaff = pandas.read_csv(config[\"dataFolder\"] + os.sep + \"staff.csv\", header=0)\n# Tell Pandas that the (currently empty) JobTitle and TelephoneNumber columns are actually meant to be String, not Float.\nstaff[\"JobTitle\"] = staff[\"JobTitle\"].astype(str)\nstaff[\"TelephoneNumber\"] = staff[\"TelephoneNumber\"].astype(str)\n\n# Staff job titles: not recorded by iSAMS, but instead set manually in GSuite for each signature. Therefore, for each user,\n# retrive the existing signature and extract the \"job title\" value, updating the \"staff\" records read from CSV above. Use the job\n# Role if no other value is present, then write out the updated \"staff.csv\" again with the added values.\noutputString = \"\"\nfor staffIndex, staffMember in staff.iterrows():\n if staff.at[staffIndex, \"JobTitle\"] == \"nan\":\n staff.at[staffIndex, \"JobTitle\"] = \"\"\n if staff.at[staffIndex, \"TelephoneNumber\"] == \"nan\":\n staff.at[staffIndex, \"TelephoneNumber\"] = \"\"\n staffName = \"\"\n staffJobTitle = \"\"\n staffUsername = \"\"\n staffTelephone = \"\"\n for sigLine in installLib.runCommand(\"gam user \" + staffMember[\"Username\"] + \" show signature\"):\n sigLine = sigLine.replace(u'\\xc2\\xa0', u' ').strip()\n matchResult = re.match(\".*bold..(.*)..span. . (.*)..div..*?\", sigLine)\n if not matchResult == None:\n staffName = matchResult[1].strip()\n staffJobTitle = matchResult[2].split(\"<\")[0].strip().replace(\"&\", \"&\")\n matchResult = re.match(\".*blank..(.*)@knightsbridgeschool.com./a..*\", sigLine)\n if not matchResult == None:\n staffUsername = matchResult[1]\n matchResult = re.match(\"([ \\d]*)$\", sigLine)\n if not matchResult == None:\n if not matchResult[1] == \"\":\n staffTelephone = matchResult[1]\n if staffUsername == \"\":\n staffUsername = staffMember[\"Username\"]\n if staffTelephone == \"\":\n staffTelephone = \"020 7590 9000\"\n if staffJobTitle == \"\":\n staffJobTitle = staffMember[\"Role\"]\n if not staffMember[\"Username\"] == staffUsername:\n print(\"Username mismatch: \" + staffMember[\"Username\"] + \" not equal to \" + staffUsername)\n else:\n print(\"Adding details for staff member \" + staffMember[\"GivenName\"] + \" \" + staffMember[\"FamilyName\"] + \" - JobTitle: \" + str(staffJobTitle) + \", staffTelephone: \" + str(staffTelephone))\n staff.at[staffIndex, \"JobTitle\"] = staffJobTitle\n staff.at[staffIndex, \"TelephoneNumber\"] = staffTelephone\ninstallLib.writeFile(config[\"dataFolder\"] + os.sep + \"staff.csv\", staff.to_csv(index=False))\n", "sub_path": "addStaffDetails.py", "file_name": "addStaffDetails.py", "file_ext": "py", "file_size_in_byte": 3091, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.loads", "line_number": 13, "usage_type": "call"}, {"api_name": "installLib.readFile", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 21, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 21, "usage_type": "attribute"}, {"api_name": "installLib.runCommand", "line_number": 39, "usage_type": "call"}, {"api_name": "re.match", "line_number": 41, "usage_type": "call"}, {"api_name": "re.match", "line_number": 45, "usage_type": "call"}, {"api_name": "re.match", "line_number": 48, "usage_type": "call"}, {"api_name": "installLib.writeFile", "line_number": 64, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 64, "usage_type": "attribute"}]} +{"seq_id": "631280396", "text": "# Run a ghidra_bridge server for external python environments to interact with\n# @author justfoxing\n# @category Bridge\n\n# NOTE: any imports here may need to be excluded in ghidra_bridge\nimport logging\nimport subprocess\nimport ghidra_bridge\n\n\ndef run_server(server_host=ghidra_bridge.bridge.DEFAULT_HOST, server_port=ghidra_bridge.bridge.DEFAULT_SERVER_PORT):\n server = ghidra_bridge.GhidraBridge(\n server_host=server_host, server_port=server_port, connect_to_host=None, connect_to_port=None, start_in_background=False, loglevel=logging.INFO)\n server.bridge.start()\n\n\ndef run_script_across_ghidra_bridge(script_file, python=\"python\", argstring=\"\"):\n \"\"\" Spin up a ghidra_bridge_server and spawn the script in external python to connect back to it. Useful in scripts being triggered from\n inside ghidra that need to use python3 or packages that don't work in jython \n\n The called script needs to handle the --connect_to_host and --connect_to_port command-line arguments and use them to start\n a ghidra_bridge client to talk back to the server.\n\n Specify python to control what the script gets run with. Defaults to whatever python is in the shell - if changing, specify a path \n or name the shell can find.\n Specify argstring to pass further arguments to the script when it starts up.\n \"\"\"\n\n # spawn a ghidra bridge server - use server port 0 to pick a random port\n server = ghidra_bridge.GhidraBridge(\n server_host=\"127.0.0.1\", server_port=0, connect_to_host=None, connect_to_port=None, start_in_background=True, loglevel=logging.INFO)\n\n try:\n # work out where we're running the server\n server_host, server_port = server.bridge.get_server_info()\n\n print(\"Running \" + script_file)\n\n # spawn an external python process to run against it\n\n try:\n output = subprocess.check_output(\"{python} {script} --connect_to_host={host} --connect_to_port={port} {argstring}\".format(\n python=python, script=script_file, host=server_host, port=server_port, argstring=argstring), stderr=subprocess.STDOUT, shell=True)\n print(output)\n except subprocess.CalledProcessError as exc:\n print(\"Failed ({}):{}\".format(exc.returncode, exc.output))\n\n print(script_file + \" completed\")\n\n finally:\n # when we're done with the script, shut down the server\n server.bridge.shutdown()\n\n\nif __name__ == \"__main__\":\n run_server()\n", "sub_path": "ghidra_bridge_server.py", "file_name": "ghidra_bridge_server.py", "file_ext": "py", "file_size_in_byte": 2485, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "ghidra_bridge.bridge", "line_number": 11, "usage_type": "attribute"}, {"api_name": "ghidra_bridge.GhidraBridge", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 13, "usage_type": "attribute"}, {"api_name": "ghidra_bridge.GhidraBridge", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 31, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 42, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 43, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 45, "usage_type": "attribute"}]} +{"seq_id": "122730586", "text": "from ml_lib.dlmodel import DLModel\nfrom keras.applications import VGG16\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.models import Model, Sequential\nfrom keras import optimizers\n\n\nclass VGGModel(DLModel):\n\n def architecture(self):\n submodel_vgg = VGG16(\n include_top=False,\n input_shape=self.image_size,\n weights=\"imagenet\"\n )\n\n for layer in submodel_vgg.layers:\n layer.trainable = False\n\n submodel_classifier = Sequential()\n submodel_classifier.add(Flatten(input_shape=submodel_vgg.output_shape[1:]))\n submodel_classifier.add(Dense(128, activation=\"relu\"))\n submodel_classifier.add(Dropout(0.5))\n submodel_classifier.add(Dense(1, activation=\"sigmoid\"))\n\n self.model = Model(inputs=submodel_vgg.input, outputs=submodel_classifier(submodel_vgg.output))\n\n self.model.compile(loss='binary_crossentropy',\n optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),\n metrics=['accuracy'])\n\n\nif __name__ == '__main__':\n pass\n", "sub_path": "src/sandbox/ml_lib/vgg_model.py", "file_name": "vgg_model.py", "file_ext": "py", "file_size_in_byte": 1087, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "ml_lib.dlmodel.DLModel", "line_number": 8, "usage_type": "name"}, {"api_name": "keras.applications.VGG16", "line_number": 11, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 20, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 21, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 22, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 23, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 24, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 26, "usage_type": "call"}, {"api_name": "keras.optimizers.SGD", "line_number": 29, "usage_type": "call"}, {"api_name": "keras.optimizers", "line_number": 29, "usage_type": "name"}]} +{"seq_id": "161873339", "text": "# coding: utf-8\n\n\nimport pymysql\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom sqlalchemy import Column, String, create_engine, Integer\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom config.load_config import config\n\npymysql.install_as_MySQLdb()\nBaseModel = declarative_base()\n\n\nclass DataManager(object):\n __instance = None\n __init_flag = False\n\n def __new__(cls, *args, **kwargs):\n if cls.__instance == None:\n cls.__instance = object.__new__(cls)\n return cls.__instance\n else:\n return cls.__instance\n\n def __init__(self):\n if DataManager.__init_flag == False:\n DataManager.__init_flag = True\n url = config.MYSQL_DB_URL\n\n SQL_CONFIG = {\n 'pool_size': config.MYSQL_POOL_SIZE,\n 'echo': False,\n 'pool_recycle': config.MYSQL_POOL_RECYLE,\n 'convert_unicode': True\n }\n\n self.engine = create_engine(url, **SQL_CONFIG)\n\n def get_session(self):\n session = scoped_session(sessionmaker(bind=self.engine))\n return session\n\n\nif __name__ == '__main__':\n mysql = DataManager()\n", "sub_path": "server/db/mysql.py", "file_name": "mysql.py", "file_ext": "py", "file_size_in_byte": 1233, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymysql.install_as_MySQLdb", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 12, "usage_type": "call"}, {"api_name": "config.load_config.config.MYSQL_DB_URL", "line_number": 29, "usage_type": "attribute"}, {"api_name": "config.load_config.config", "line_number": 29, "usage_type": "name"}, {"api_name": "config.load_config.config.MYSQL_POOL_SIZE", "line_number": 32, "usage_type": "attribute"}, {"api_name": "config.load_config.config", "line_number": 32, "usage_type": "name"}, {"api_name": "config.load_config.config.MYSQL_POOL_RECYLE", "line_number": 34, "usage_type": "attribute"}, {"api_name": "config.load_config.config", "line_number": 34, "usage_type": "name"}, {"api_name": "sqlalchemy.create_engine", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.scoped_session", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "6791202", "text": "from rest_framework import serializers\nfrom .models import Client\nfrom django.contrib.auth.models import User\n\nfrom rest_framework import serializers\n\n\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'groups')\n\n\nclass ClientSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Client\n fields = ('id', 'first_name', 'last_name',\n 'personal_id', 'personal_id2', 'phone', 'birthdate',\n 'email', 'workplace', 'workplace_position', 'workplace_phone',\n 'salary', 'bank', 'bank_account', 'bank_account_confirmed',\n 'actual_address', 'legal_address', 'contact_person',\n 'contact_person_phone', 'labels', 'loyalty',\n 'registration_date', 'registration_ip',\n 'registration_ref', 'blocked', 'last_activity'\n )\n\n\n\n\n#\n# class GroupSerializer(serializers.HyperlinkedModelSerializer):\n# permissions = serializers.ManySlugRelatedField(\n# slug_field='codename',\n# queryset=Permission.objects.all()\n# )\n#\n# class Meta:\n# model = Group\n# fields = ('url', 'name', 'permissions')", "sub_path": "clients/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 1265, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rest_framework.serializers.HyperlinkedModelSerializer", "line_number": 10, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 10, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User", "line_number": 12, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 16, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 16, "usage_type": "name"}, {"api_name": "models.Client", "line_number": 19, "usage_type": "name"}]} +{"seq_id": "369326810", "text": "#!/usr/bin/python\n\nimport os\nimport json\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom oauth2client.tools import argparser\n\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom oauth2client.tools import argparser\n\n\n# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps\n# tab of\n# https://cloud.google.com/console\n# Please ensure that you have enabled the YouTube Data API for your project.\nDEVELOPER_KEY = os.environ[\"YOUTUBE_DEVELOPER_KEY\"]\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\n\ndef youtube_search(regioncode):\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)\n\n # Call the videos.list method to retrieve location details for each video.\n response = youtube.videos().list(part='snippet, statistics',\n regionCode=regioncode,\n hl=\"en\",\n maxResults=10,\n chart=\"mostPopular\"\n ).execute()\n\n video_objs = response[\"items\"]\n\n videos = []\n\n for video in video_objs:\n vid = {}\n\n vid[\"title\"] = video[\"snippet\"][\"title\"]\n vid[\"description\"] = video[\"snippet\"][\"description\"]\n vid[\"thumbnail_url\"] = video[\"snippet\"][\"thumbnails\"][\"default\"][\"url\"]\n vid[\"channel\"] = video[\"snippet\"][\"channelTitle\"]\n vid[\"viewcount\"] = video[\"statistics\"][\"viewCount\"]\n # vid[\"likecount\"] = video[\"statistics\"][\"likeCount\"]\n # vid[\"dislikecount\"] = video[\"statistics\"][\"dislikeCount\"]\n\n videos.append(vid)\n\n return videos\n\n\n\n\n", "sub_path": "youtube_api.py", "file_name": "youtube_api.py", "file_ext": "py", "file_size_in_byte": 1757, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "apiclient.discovery.build", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "617277024", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/10/8 23:15\n# @Author : SmallStrong\n# @Des : \n# @File : export_to_output.py\n# @Software: PyCharm\n\nimport sys\nimport json\n\n\ndef write(file_name, data_name, data):\n f = open(\"./pipeline/output/{}.py\".format(file_name), 'w+')\n print >> f, '# !/bin/python'\n print >> f, '# -*- coding: utf8 -*-'\n print >> f, '{} = {}'.format(data_name, sort_serialize(data))\n\n\ndef sort_serialize(data):\n try:\n raise Exception\n except:\n f = sys.exc_info()[2].tb_frame.f_back\n try:\n return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)\n except Exception as e:\n return None\n", "sub_path": "qinglong/pipeline/export_to_output.py", "file_name": "export_to_output.py", "file_ext": "py", "file_size_in_byte": 690, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.exc_info", "line_number": 24, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "519581576", "text": "from ..base.translator_base import TranslatorBase\nfrom ..core.object import Objects, Object\nfrom ..core.function import Function\nfrom .regex import RegexPatternCpp\n\n\nclass Translator(TranslatorBase):\n\n def __init__(self):\n TranslatorBase.__init__(self)\n\n def translate_function(self, cls, method, model):\n if not method.translated:\n body = '\\n'.join(method.operations)\n body = self.translate_function_body(cls, method, body, model, method.args)\n method.body = body\n else:\n if method.operations:\n method.body = '\\n'.join(method.operations)\n else:\n method.body = ''\n\n def translate_function_body(self, cls, func, body, model, args):\n if not body:\n body = ''\n body = self.replace_by_regex(func, body, model, args)\n return body\n\n def convert_to_enum(self, cls):\n cast = 'int'\n values = []\n\n def get_enum_value(cls_, index):\n return '(1 << {})'.format(index) if not cls_.is_numeric else str(index)\n\n def translate_members():\n shift = 0\n for member in cls.members:\n if member.name:\n continue\n member.name = member.type\n member.type = cast\n member.is_static = True\n member.is_const = True\n if member.initial_value is None:\n member.initial_value = get_enum_value(cls, shift)\n values.append(1 << shift)\n shift += 1\n\n def add_method(type_, name, const):\n method = Function()\n method.return_type = type_\n method.name = name\n method.is_const = const\n cls.functions.append(method)\n return method\n\n def create_const_ref():\n const_ref = Object()\n const_ref.type = cls.name\n const_ref.is_const = True\n const_ref.is_ref = True\n return const_ref\n\n def create_const_ref_base():\n const_ref = Object()\n const_ref.type = 'BaseEnum'\n const_ref.is_const = True\n const_ref.is_ref = True\n return const_ref\n\n def add_constructor_with_parameter():\n method = add_method(Object(), cls.name, False)\n method.args.append(['_value', Objects.INT])\n method.operations.append('value = _value;')\n\n def add_constructor_copy():\n method = add_method(Object(), cls.name, False)\n method.args.append(['rhs', create_const_ref()])\n method.operations.append('value = rhs.value;')\n\n def add_constructor_with_string():\n method = add_method(Object(), cls.name, False)\n method.args.append(['_value', Objects.STRING])\n for index, obj in enumerate(cls.members):\n if obj.name != 'value' and index <= len(values):\n method.operations.append('''if(_value == \"{0}\")\n {{\n value = {0};\n return;\n }}'''.format(obj.name))\n method.operations.append('value = 0;')\n\n def add_operator_copy():\n method = add_method(create_const_ref(), 'operator =', False)\n method.args.append(['rhs', create_const_ref()])\n method.operations.extend(['value = rhs.value;', 'return *this;'])\n\n def add_operator_copy_with_int():\n method = add_method(create_const_ref(), 'operator =', False)\n method.args.append(['rhs', Objects.INT])\n method.operations.extend(['value = rhs;', 'return *this;'])\n\n def add_operator_copy_with_string():\n method = add_method(create_const_ref(), 'operator =', False)\n method.args.append(['_value', Objects.STRING])\n for index, obj in enumerate(cls.members):\n if obj.name != 'value' and index <= len(values):\n method.operations.append('''if(_value == \"{0}\")\n {{\n value = {0};\n return *this;\n }}'''.format(obj.name))\n method.operations.append('return *this;')\n\n def add_operator_equals():\n method = add_method(Objects.BOOL, 'operator ==', True)\n method.args.append(['rhs', create_const_ref()])\n method.operations.append('return value == rhs.value;')\n\n method = add_method(Objects.BOOL, 'operator ==', True)\n method.args.append(['rhs', create_const_ref_base()])\n method.operations.append('return value == rhs.operator int();')\n\n def add_operator_equals_with_int():\n method = add_method(Objects.BOOL, 'operator ==', True)\n method.args.append(['rhs', Objects.INT])\n method.operations.append('return value == rhs;')\n\n def add_operator_equals_with_string():\n method = add_method(Objects.BOOL, 'operator ==', True)\n method.args.append(['rhs', Objects.STRING])\n method.operations.append('return *this == {}(rhs);'.format(cls.name))\n\n def add_friend_equals_with_string():\n method = add_method(Objects.BOOL, 'operator ==', False)\n method.is_friend = True\n method.args.append(['lhs', Objects.STRING])\n method.args.append(['rhs', create_const_ref()])\n method.operations.append('return {}(lhs) == rhs;'.format(cls.name))\n\n def add_operator_less():\n method = add_method(Objects.BOOL, 'operator <', True)\n method.args.append(['rhs', create_const_ref()])\n method.operations.append('return value < rhs.value;')\n\n def add_cast_to_int():\n method = add_method(Object(), 'operator int', True)\n method.operations.append('return value;')\n\n def add_operator_cast_string():\n method = add_method(Object(), 'operator std::string', True)\n for index, obj in enumerate(cls.members):\n if obj.name != 'value' and index <= len(values):\n method.operations.append('''if(value == {0})\n {{\n return \"{0}\";\n }}'''.format(obj.name))\n method.operations.append('return std::string();')\n\n def add_method_str():\n method = add_method(Objects.STRING, 'str', True)\n for index, obj in enumerate(cls.members):\n if obj.name != 'value' and index <= len(values):\n method.operations.append('''if(value == {0})\n {{\n return \"{0}\";\n }}'''.format(obj.name))\n method.operations.append('return std::string();')\n\n translate_members()\n add_constructor_with_parameter()\n add_constructor_copy()\n add_constructor_with_string()\n add_operator_copy()\n add_operator_copy_with_int()\n add_operator_copy_with_string()\n add_operator_equals()\n add_operator_equals_with_int()\n add_operator_equals_with_string()\n add_friend_equals_with_string()\n add_operator_less()\n add_cast_to_int()\n add_operator_cast_string()\n add_method_str()\n\n return values\n\n def replace_by_regex(self, func, body, model, args):\n for reg in RegexPatternCpp.FUNCTION:\n body = self.replace(body, reg)\n for reg in RegexPatternCpp.REPLACES:\n body = body.replace(reg[0], reg[1])\n for reg in RegexPatternCpp.convert_c17_to_c14:\n body = self.replace(body, reg)\n return body\n", "sub_path": "mlc_tools/module_cpp/translator.py", "file_name": "translator.py", "file_ext": "py", "file_size_in_byte": 7782, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "base.translator_base.TranslatorBase", "line_number": 7, "usage_type": "name"}, {"api_name": "base.translator_base.TranslatorBase.__init__", "line_number": 10, "usage_type": "call"}, {"api_name": "base.translator_base.TranslatorBase", "line_number": 10, "usage_type": "name"}, {"api_name": "core.function.Function", "line_number": 51, "usage_type": "call"}, {"api_name": "core.object.Object", "line_number": 59, "usage_type": "call"}, {"api_name": "core.object.Object", "line_number": 66, "usage_type": "call"}, {"api_name": "core.object.Object", "line_number": 73, "usage_type": "call"}, {"api_name": "core.object.Objects.INT", "line_number": 74, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 74, "usage_type": "name"}, {"api_name": "core.object.Object", "line_number": 78, "usage_type": "call"}, {"api_name": "core.object.Object", "line_number": 83, "usage_type": "call"}, {"api_name": "core.object.Objects.STRING", "line_number": 84, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 84, "usage_type": "name"}, {"api_name": "core.object.Objects.INT", "line_number": 101, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 101, "usage_type": "name"}, {"api_name": "core.object.Objects.STRING", "line_number": 106, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 106, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 117, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 117, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 121, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 121, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 126, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 126, "usage_type": "name"}, {"api_name": "core.object.Objects.INT", "line_number": 127, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 127, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 131, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 131, "usage_type": "name"}, {"api_name": "core.object.Objects.STRING", "line_number": 132, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 132, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 136, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 136, "usage_type": "name"}, {"api_name": "core.object.Objects.STRING", "line_number": 138, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 138, "usage_type": "name"}, {"api_name": "core.object.Objects.BOOL", "line_number": 143, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 143, "usage_type": "name"}, {"api_name": "core.object.Object", "line_number": 148, "usage_type": "call"}, {"api_name": "core.object.Object", "line_number": 152, "usage_type": "call"}, {"api_name": "core.object.Objects.STRING", "line_number": 162, "usage_type": "attribute"}, {"api_name": "core.object.Objects", "line_number": 162, "usage_type": "name"}, {"api_name": "regex.RegexPatternCpp.FUNCTION", "line_number": 190, "usage_type": "attribute"}, {"api_name": "regex.RegexPatternCpp", "line_number": 190, "usage_type": "name"}, {"api_name": "regex.RegexPatternCpp.REPLACES", "line_number": 192, "usage_type": "attribute"}, {"api_name": "regex.RegexPatternCpp", "line_number": 192, "usage_type": "name"}, {"api_name": "regex.RegexPatternCpp.convert_c17_to_c14", "line_number": 194, "usage_type": "attribute"}, {"api_name": "regex.RegexPatternCpp", "line_number": 194, "usage_type": "name"}]} +{"seq_id": "26408846", "text": "from django.contrib import admin\nfrom .models import Stock, StockFinancialData, AssetStatus\nfrom .models import StockValueData, Order, Entry, ReasonWinLoss\n\n\n# Register your models here.\nclass StockAdmin(admin.ModelAdmin):\n list_display = ['pk', 'is_trust', 'code', 'name', 'market', 'industry', \"fkmanage_id\"]\n list_filter = ['market', 'industry', ]\n search_fields = ['is_trust', 'code', 'name', ]\n\n\nclass AssetStatusAdmin(admin.ModelAdmin):\n list_display = [\n 'pk', \"user\", \"date\",\n \"buying_power\", \"sum_stock\", \"sum_other\", \"sum_trust\",\n \"investment\", \"get_total\",\n ]\n list_filter = [\"user\", \"date\", ]\n\n\nclass OrderAdmin(admin.ModelAdmin):\n list_display = [\n \"pk\", \"is_simulated\", \"is_buy\", \"is_nisa\",\n \"user\", \"datetime\", \"entry\", \"stock\",\n \"num\", \"val\", \"commission\",\n \"chart\", \"chart_image\", \"fkmanage_id\",\n ]\n list_filter = [\n \"user\", \"datetime\", \"is_simulated\", \"is_buy\", \"stock__is_trust\",\n \"stock__name\", \"stock__code\", \"stock__industry\", \"stock__market\",\n ]\n search_fields = ['stock__name']\n\n def chart_image(self, row):\n if row.chart:\n return ''.format(row.chart)\n else:\n return None\n\n chart_image.allow_tags = True\n\n\nclass StockValueDataAdmin(admin.ModelAdmin):\n list_display = ['pk', \"stock\", \"date\", \"val_open\", \"val_high\", \"val_low\", \"val_close\", \"turnover\"]\n list_filter = [\"stock__code\", \"stock__name\", \"stock__industry\", \"stock__market\", \"date\", ]\n search_fields = ['stock__name']\n\n\nclass EntryAdmin(admin.ModelAdmin):\n list_display = [\n 'pk', 'stock',\n # 'border_loss_cut', 'border_profit_determination',\n 'is_closed', 'is_simulated',\n \"remaining\", \"profit\",\n 'reason_win_loss', 'memo', \"num_linked_orders\",\n ]\n list_filter = [\n \"is_closed\", \"is_simulated\",\n \"stock__name\",\n \"stock__code\",\n \"stock__industry\", \"stock__market\",\n ]\n search_fields = ['stock__name']\n\n\nclass StockFinancialDataAdmin(admin.ModelAdmin):\n list_display = [\n 'pk', 'stock', 'date',\n 'assets',\n 'eps', 'roe', 'roa', 'roa_2', 'bps',\n 'pbr_f', 'per_f', 'eps_f', 'bps_f',\n 'capital', 'sales',\n 'equity', 'equity_ratio',\n 'net_income',\n 'recurring_profit',\n 'operating_income',\n 'dividend_yield', 'market_value',\n 'interest_bearing_debt',\n ]\n list_filter = ['date', \"stock__name\", \"stock__code\", \"stock__industry\", \"stock__market\", ]\n search_fields = ['stock__name']\n\n\nclass ReasonWinLossAdmin(admin.ModelAdmin):\n list_display = [\"pk\", \"reason\", \"is_win\", ]\n\n\nadmin.site.register(Stock, StockAdmin)\nadmin.site.register(AssetStatus, AssetStatusAdmin)\nadmin.site.register(Order, OrderAdmin)\nadmin.site.register(StockValueData, StockValueDataAdmin)\nadmin.site.register(Entry, EntryAdmin)\nadmin.site.register(StockFinancialData, StockFinancialDataAdmin)\nadmin.site.register(ReasonWinLoss, ReasonWinLossAdmin)", "sub_path": "web/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 3067, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 22, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 44, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 44, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 50, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 50, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 67, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 67, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 85, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 85, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 89, "usage_type": "call"}, {"api_name": "models.Stock", "line_number": 89, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 89, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 89, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 90, "usage_type": "call"}, {"api_name": "models.AssetStatus", "line_number": 90, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 90, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 90, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 91, "usage_type": "call"}, {"api_name": "models.Order", "line_number": 91, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 91, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 91, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 92, "usage_type": "call"}, {"api_name": "models.StockValueData", "line_number": 92, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 92, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 92, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 93, "usage_type": "call"}, {"api_name": "models.Entry", "line_number": 93, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 93, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 93, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 94, "usage_type": "call"}, {"api_name": "models.StockFinancialData", "line_number": 94, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 94, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 94, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 95, "usage_type": "call"}, {"api_name": "models.ReasonWinLoss", "line_number": 95, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 95, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 95, "usage_type": "name"}]} +{"seq_id": "120159201", "text": "import collections\r\nimport string\r\n\r\nwordlist = [line.strip().lower() for line in open('gg2015-coding/wordlist')]\r\ncypher = [line.strip().lower() for line in open('gg2015-coding/cypher')][0].split(' ')\r\n\r\nwordlistFreqs = collections.Counter()\r\ncypherFreqs = collections.Counter()\r\n\r\nfor word in wordlist:\r\n for c in word:\r\n wordlistFreqs[c] += 1\r\n\r\nfor word in cypher:\r\n for c in word:\r\n cypherFreqs[c] += 1\r\n\r\nwordlistCommon = list(map(lambda x: x[0], wordlistFreqs.most_common()))\r\ncypherCommon = list(map(lambda x: x[0], cypherFreqs.most_common()))\r\n\r\nprint(wordlistCommon)\r\n\r\nfor word in cypher:\r\n plaintext = ''\r\n for c in word:\r\n plaintext += cypherCommon[wordlistCommon.index(c)][0]\r\n print(plaintext)", "sub_path": "p07.py", "file_name": "p07.py", "file_ext": "py", "file_size_in_byte": 744, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "collections.Counter", "line_number": 7, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "433004074", "text": "from urllib.error import HTTPError\n\nimport pytest\n\nfrom appconfig.__main__ import main\n\n\ndef test_ls(capsys):\n main(['ls'])\n out, err = capsys.readouterr()\n assert 'wals3' in out\n\n main(['ls', '-p'])\n out, err = capsys.readouterr()\n assert 'wals3' in out\n\n\ndef test_error(mocker):\n mocker.patch('appconfig.commands.test_error.urlopen')\n\n with pytest.raises(RuntimeError):\n main(['test_error', 'wals3'])\n\n mocker.patch(\n 'appconfig.commands.test_error.urlopen',\n mocker.Mock(side_effect=HTTPError('', 500, '', {}, None)))\n main(['test_error', 'wals3'])\n", "sub_path": "tests/test_cli.py", "file_name": "test_cli.py", "file_ext": "py", "file_size_in_byte": 603, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "appconfig.__main__.main", "line_number": 9, "usage_type": "call"}, {"api_name": "appconfig.__main__.main", "line_number": 13, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 21, "usage_type": "call"}, {"api_name": "appconfig.__main__.main", "line_number": 22, "usage_type": "call"}, {"api_name": "urllib.error.HTTPError", "line_number": 26, "usage_type": "call"}, {"api_name": "appconfig.__main__.main", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "63270473", "text": "# https://github.com/Pithikos/python-websocket-server\n# import logging\nfrom websocket_server import WebsocketServer\nimport json\nimport threading\nimport RPi.GPIO as GPIO\nimport time\nfrom time import sleep\n\nMotor1A = 3\nMotor1B = 5\nglobal prevAngle\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(Motor1A, GPIO.OUT)\nGPIO.setup(Motor1B, GPIO.OUT)\n\nGPIO.setup(12, GPIO.OUT)\nglobal pwm\npwm = GPIO.PWM(12, 50)\npwm.start(0)\n\nglobal pwmAngle\n\n\ndef doPWM():\n global pwm\n global pwmAngle\n\n duty = pwmAngle / 18 + 2\n GPIO.output(12, True)\n pwm.ChangeDutyCycle(duty)\n sleep(0.5)\n GPIO.output(12, False)\n pwm.ChangeDutyCycle(0)\n\ndef setAngle(angle, pwm):\n print(\"Rudder \" + str(angle))\n duty = angle / 18 + 2\n GPIO.output(12, True)\n pwm.ChangeDutyCycle(duty)\n sleep(0.5)\n GPIO.output(12, False)\n pwm.ChangeDutyCycle(0)\n\ndef new_client(client, server):\n print('connected!')\n server.send_message_to_all(\"Hey all, a new client has joined us\")\n\n\ndef message_received(client, server, message):\n global prevAngle\n print(message)\n if message[0] == '{':\n parsed_json = json.loads(message)\n direction = parsed_json['direction']\n throttle = parsed_json['throttle']\n rudder = parsed_json['rudder']\n maxRudder = parsed_json['maxRudder']\n minRudder = parsed_json['minRudder']\n rudderTrim = parsed_json['rudderTrim']\n print(\"Throttle \" + str(throttle))\n print(\"Direction \" + direction)\n percentageRudder = 0\n if (rudderTrim + rudder) > 0:\n percentageRudder = (rudderTrim + rudder) / maxRudder\n\n print(\"PercentageRudder : \" + str(percentageRudder))\n print(\"Rudder Trim : \" + str(rudderTrim))\n\n adjustedRudder = rudder\n\n if (rudder) < 0:\n rudder = 150#90 + (percentageRudder * 60)\n adjustedRudder = 150\n elif (rudder) > 0:\n rudder = 30 #90 - (-1 * percentageRudder * 60)\n adjustedRudder = 30\n else:\n adjustedRudder = 90 + rudderTrim\n rudder = 90\n\n if prevAngle != rudder:\n prevAngle = rudder\n setAngle(adjustedRudder, pwm)\n\n print(\"Rudder : \" + str(rudder))\n\n if throttle == 0:\n GPIO.output(Motor1A, GPIO.LOW)\n GPIO.output(Motor1B, GPIO.LOW)\n elif direction == 'Forward':\n # Forwards\n GPIO.output(Motor1A, GPIO.LOW)\n GPIO.output(Motor1B, GPIO.HIGH)\n elif direction == 'Reverse':\n GPIO.output(Motor1A, GPIO.HIGH)\n GPIO.output(Motor1B, GPIO.LOW)\n else:\n print(\"\\n\\nNo Json!\")\n\n\n# message_received(\"\", \"\", '{\"throttle\": 0,\"rudder\": 0,\"rudderTrim\": 0,\"throttleMultiply\": 1,\"direction\": \"Forward\",\"maxThrottle\": 10,\"minThrottle\": 0,\"maxRudder\": 10,\"minRudder\": -10,\"maxMultiplier\": 10,\"minMultiplier\": 1,\"maxRudderTrim\": 10,\"minRudderTrim\": -10}')\nGPIO.output(Motor1A, GPIO.LOW)\nGPIO.output(Motor1B, GPIO.LOW)\nprevAngle = 90\npwmAngle = 90\n#threading.Thread(target=doPWM).start()\n# setAngle(prevAngle, pwm)\nserver = WebsocketServer(5005, host='0.0.0.0')\nserver.set_fn_new_client(new_client)\nserver.set_fn_message_received(message_received)\nserver.run_forever()\n", "sub_path": "dasboot/dasbootWebsocketServerV1.py", "file_name": "dasbootWebsocketServerV1.py", "file_ext": "py", "file_size_in_byte": 3213, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "RPi.GPIO.setmode", "line_number": 13, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 13, "usage_type": "name"}, {"api_name": "RPi.GPIO.BOARD", "line_number": 13, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 14, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 14, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 14, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 15, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 15, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 15, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 17, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 17, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 17, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PWM", "line_number": 19, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 19, "usage_type": "name"}, {"api_name": "RPi.GPIO.output", "line_number": 30, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 30, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 32, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 33, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 33, "usage_type": "name"}, {"api_name": "RPi.GPIO.output", "line_number": 39, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 39, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 42, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 42, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 54, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 89, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 89, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 89, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 90, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 90, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 90, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 93, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 93, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 93, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 94, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 94, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 94, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 96, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 96, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 96, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 97, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 97, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 97, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 103, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 103, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 103, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 104, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 104, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 104, "usage_type": "attribute"}, {"api_name": "websocket_server.WebsocketServer", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "477993183", "text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC Azure ML & Azure Databricks notebooks by Parashar Shah.\n# MAGIC \n# MAGIC Copyright (c) Microsoft Corporation. All rights reserved.\n# MAGIC \n# MAGIC Licensed under the MIT License. \n\n# COMMAND ----------\n\n# MAGIC %md Please ensure you have run this notebook before proceeding.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Now we support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package (during private preview). You can select the option to attach the library to all clusters or just one cluster.\n# MAGIC \n# MAGIC Provide this full string to install the SDK:\n# MAGIC \n# MAGIC azureml-sdk[databricks]\n\n# COMMAND ----------\n\nimport azureml.core\n\n# Check core SDK version number - based on build number of preview/master.\nprint(\"SDK version:\", azureml.core.VERSION)\n\n# COMMAND ----------\n\nsubscription_id = \"09a97f32-5ee4-4391-a40b-f8de68e958c5\"\nresource_group = \"BigData\"\nworkspace_name = \"encmlworkspace\"\nworkspace_region = \"westeurope\"\n\n# COMMAND ----------\n\n# import the Workspace class and check the azureml SDK version\n# exist_ok checks if workspace exists or not.\n\nfrom azureml.core import Workspace\n\nws = Workspace.create(name = workspace_name,\n subscription_id = subscription_id,\n resource_group = resource_group, \n location = workspace_region,\n exist_ok=True)\n\nws.get_details()\n\n# COMMAND ----------\n\nws = Workspace(workspace_name = workspace_name,\n subscription_id = subscription_id,\n resource_group = resource_group)\n\n# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\nws.write_config()\n\n# COMMAND ----------\n\n# MAGIC %sh\n# MAGIC cat /databricks/driver/aml_config/config.json\n\n# COMMAND ----------\n\n# import the Workspace class and check the azureml SDK version\nfrom azureml.core import Workspace\n\nws = Workspace.from_config()\nprint('Workspace name: ' + ws.name, \n 'Azure region: ' + ws.location, \n 'Subscription id: ' + ws.subscription_id, \n 'Resource group: ' + ws.resource_group, sep = '\\n')\n\n# COMMAND ----------\n\ndbutils.notebook.exit(\"success\")\n\n# COMMAND ----------\n\n", "sub_path": "notebooks/Users/adiazcan@hotmail.com/FlightDelays/00.Installation_and_Configuration.py", "file_name": "00.Installation_and_Configuration.py", "file_ext": "py", "file_size_in_byte": 2331, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "azureml.core.core", "line_number": 27, "usage_type": "attribute"}, {"api_name": "azureml.core", "line_number": 27, "usage_type": "name"}, {"api_name": "azureml.core.Workspace.create", "line_number": 43, "usage_type": "call"}, {"api_name": "azureml.core.Workspace", "line_number": 43, "usage_type": "name"}, {"api_name": "azureml.core.Workspace", "line_number": 53, "usage_type": "call"}, {"api_name": "azureml.core.Workspace.from_config", "line_number": 70, "usage_type": "call"}, {"api_name": "azureml.core.Workspace", "line_number": 70, "usage_type": "name"}]} +{"seq_id": "448714857", "text": "import json \nfrom collections import OrderedDict\n\ndef jsonDefault(OrderedDict):\n return OrderedDict.__dict__\n\nclass PreAttckObject(object):\n '''\n Parent class of all other MITRE PRE-ATT&CK based classes\n\n This is a private class and should not be accessed directly\n '''\n\n _RELATIONSHIPS = None\n \n def __init__(self, **kwargs):\n \"\"\"\n Sets standard properties that are found in all child classes as well as provides standard methods used by inherited classes\n \n Arguments:\n kwargs (dict) -- Takes the MITRE PRE-ATT&CK Json object as a kwargs values\n \"\"\"\n self.id = self._set_id(kwargs)\n self.name = self._set_attribute(kwargs, 'name')\n self.description = self._set_attribute(kwargs, 'description')\n self.reference = self._set_reference(kwargs)\n self.created = self._set_attribute(kwargs, 'created')\n self.modified = self._set_attribute(kwargs, 'modified')\n self.type = self._set_attribute(kwargs, 'type')\n \n\n def __str__(self):\n return json.dumps(self, default=jsonDefault, indent=4)\n\n def set_relationships(self, attck_obj):\n if not PreAttckObject._RELATIONSHIPS:\n relationship_obj = {}\n for item in attck_obj['objects']:\n if 'type' in item:\n if item['type'] == 'relationship':\n source_id = item['source_ref']\n target_id = item['target_ref']\n if source_id not in relationship_obj:\n relationship_obj[source_id] = []\n relationship_obj[source_id].append(target_id)\n\n if target_id not in relationship_obj:\n relationship_obj[target_id] = []\n relationship_obj[target_id].append(source_id)\n PreAttckObject._RELATIONSHIPS = relationship_obj\n\n def set_relationship(self, obj, id, name):\n \"\"\"Sets relationships on two objects based on a defined relationship from MITRE PRE-ATT&CK\n \n Args:\n obj (dict): MITRE PRE-ATT&CK Json object\n id (str): A MITRE PRE-ATT&CK source reference ID\n name (str): A MITRE PRE-ATT&CK object type\n \n Returns:\n list: A list of related MITRE PRE-ATT&CK related objects based on provided inputs\n \"\"\" \n return_list = []\n for item in obj['objects']:\n if 'source_ref' in item:\n if id in item['source_ref']:\n for o in obj['objects']:\n if o['type'] == name:\n if item['target_ref'] in o['id']:\n return_list.append(o)\n return return_list\n\n def _set_attribute(self, obj, name):\n \"\"\"Parent class method to set attribute based on passed in object\n and the name of the property\n \n Arguments:\n obj (dict) -- Provided json objects are passed to this method\n name (str) -- The json property name to set attribute in child classes\n \n Returns:\n (str) -- Returns either the value of the attribute requested or returns 'null'\n \"\"\"\n try:\n value = obj.get(name)\n return None if not value else value\n except:\n return None\n\n\n def _set_list_items(self, obj, list_name):\n \"\"\"Private method used by child classes and normalizes list items\n \n Args:\n obj (dict) -- Provided json objects are passed to this method\n list_name (str) -- The json property name to set list items attribute in child classes\n \n Returns:\n list: returns a list of values from the provided list_name property\n \"\"\" \n item_value = []\n if list_name in obj:\n for item in obj[list_name]:\n item_value.append(item)\n \n return item_value\n\n def _set_id(self, obj):\n \"\"\"Returns the MITRE PRE-ATT&CK Framework external ID \n \n Arguments:\n obj (dict) -- A MITRE PRE-ATT&CK Framework json object\n \n Returns:\n (str) -- Returns the MITRE PRE-ATT&CK Framework external ID\n \"\"\"\n if \"external_references\" in obj:\n for p in obj['external_references']:\n for s in p:\n if p[s] == 'mitre-pre-attack':\n return p['external_id']\n return 'S0000'\n \n def _set_wiki(self, obj):\n \"\"\"Returns the MITRE ATT&CK Framework Wiki URL\n \n Arguments:\n obj (dict) -- A MITRE PRE-ATT&CK Framework json object\n \n Returns:\n (str) -- Returns the MITRE PRE-ATT&CK Framework Wiki URL\n \"\"\"\n if \"external_references\" in obj:\n for p in obj['external_references']:\n for s in p:\n if p[s] == 'mitre-attack':\n return p['url']\n\n\n def _set_reference(self, obj):\n \"\"\"Returns a list of external references from the provided MITRE PRE-ATT&CK Framework json object\n \n Arguments:\n obj (dict) -- A MITRE PRE-ATT&CK Framework json object\n \n Returns:\n (dict) -- Returns a dict containing the following key/value pairs\n external_id (str) -- The MITRE PRE-ATT&CK Framework external ID\n url (str) -- The MITRE PRE-ATT&CK Framework URL\n source_name (str) -- The MITRE PRE-ATT&CK Framework source name\n description (str) -- The MITRE PRE-ATT&CK Framework description or None if it does not exist\n \"\"\"\n return_list = []\n if \"external_references\" in obj:\n for p in obj['external_references']:\n return_list.append(p)\n return return_list\n ", "sub_path": "pyattck/preattck/preattckobject.py", "file_name": "preattckobject.py", "file_ext": "py", "file_size_in_byte": 5959, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "collections.OrderedDict.__dict__", "line_number": 5, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 5, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "398051418", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Python version: 3.6\n\nfrom torch import nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nimport zlib\nimport random\nimport math\nimport json\nimport math\n\nclass VGG19(nn.Module):\n def __init__(self, args):\n super(VGG19, self).__init__()\n self.args = args\n self.gama = args.gama\n self.alpha = args.alpha\n self.u = args.u\n self.beta = args.beta\n self.epsilon = args.epsilon\n self.l = 0 \n self.keep_rate = args.keep_rate\n\n self.clientlayers = nn.Sequential(\n # Conv 1-1\n nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n\n self.serverlayers = nn.Sequential(\n # Conv 1-2\n\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.ReLU(True),\n\n nn.MaxPool2d(kernel_size=2, stride=2),\n \n # Conv 2-1\n nn.Conv2d(64, 128, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 2-2\n nn.Conv2d(128, 128, kernel_size=3, padding=1),\n nn.ReLU(True),\n\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Conv 3-1\n nn.Conv2d(128, 256, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 3-2\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 3-3\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 3-4\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(True),\n\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Conv 4-1\n nn.Conv2d(256, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 4-2\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 4-3\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 4-4\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n\n nn.MaxPool2d(kernel_size=2, stride=2),\n\n # Conv 5-1\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 5-2\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 5-3\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n # Conv 5-4\n nn.Conv2d(512, 512, kernel_size=3, padding=1),\n nn.ReLU(True),\n\n # # nn.MaxPool2d(kernel_size=2, stride=2),\n \n )\n\n self.classifier = nn.Sequential(\n # FC1\n nn.Linear(2048, 512), \n nn.ReLU(True),\n nn.Dropout(),\n # FC2\n nn.Linear(512, 512),\n nn.ReLU(True),\n nn.Dropout(), \n # FC3\n nn.Linear(512, args.num_classes), \n )\n self._initialize_weights()\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n # m.weight.data.normal_(1, 5)\n m.bias.data.zero_()\n\n def forward(self, x):\n # client-side model\n x = self.clientlayers(x)\n\n # reduce communication cost \n if self.args.reduced:\n x = self.reduce_activations(x)\n x.register_hook(self.hook_fn) \n\n # Differential Privacy \n if self.args.dp: \n x = self.add_noise(x)\n\n # server-side model\n x = self.serverlayers(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n\n return x\n\n \n def add_noise(self, acts):\n n, m, w, h = list(acts.size()) # m = # kernels\n acts = [self.add_noise_channel(channel) for sample in acts for channel in sample ]\n acts = torch.stack(acts, dim=0)\n acts = acts.view(n, m, w, h)\n return acts\n \n \n def add_noise_channel(self, channel):\n w, h = list(channel.size())\n max_value = torch.max(channel)\n lap_param = max_value / self.epsilon # sensitivity (scale)\n tmp = np.random.laplace(0, lap_param.item(), w*h)\n noise = torch.from_numpy(tmp).to(device='cuda', dtype=torch.float)\n noise = torch.reshape(noise, (w, h))\n return channel+noise\n\n def reduce_activations(self, x):\n # randomly discard some activations\n tmp = x.view(1, -1)\n activation_size = tmp.shape[1]\n discard_size = int(activation_size * (1 - self.keep_rate))\n keep_size = activation_size - discard_size\n \n ones = torch.ones([1, keep_size])\n zeros = torch.zeros([1, discard_size])\n random_vector = torch.cat((ones, zeros), dim=1).to(device='cuda')\n ind = torch.randperm(activation_size)\n random_vector = random_vector[0, ind]\n\n result_vector = tmp.mul(random_vector)\n result_vector = result_vector.view(x.shape)\n \n return result_vector\n\n\n def hook_fn(self, grad):\n # discard gradients that have small absolute values\n # print('--------hook function----------')\n\n tmp = grad.view(1, -1).to(device='cuda', dtype=torch.float)\n tmp = torch.abs(tmp)\n tmp, _ = torch.sort(tmp, descending=True)\n\n position = int(tmp.shape[1]*(self.keep_rate))\n split_value = tmp[0, position] \n\n absresult = torch.abs(grad) < split_value\n grad = absresult.mul(grad)\n\n # print(grad)\n\n return grad\n\n", "sub_path": "src/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 6039, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.nn.Module", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 69, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 82, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 88, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 97, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 99, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 100, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 101, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 103, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 105, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 107, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 113, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 118, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 118, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 121, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 121, "usage_type": "name"}, {"api_name": "torch.stack", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.random.laplace", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 159, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 160, "usage_type": "attribute"}, {"api_name": "torch.reshape", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 187, "usage_type": "attribute"}, {"api_name": "torch.abs", "line_number": 188, "usage_type": "call"}, {"api_name": "torch.sort", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 194, "usage_type": "call"}]} +{"seq_id": "395877411", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 3 21:41:44 2018\n\n@author: danpal\n\"\"\"\n\nimport bs4\nfrom check_file import checkFile\nfrom revcomp import reverseComplement\n\n\ndef getPrimers(in_file, out_file):\n with open(in_file) as file:\n soup = bs4.BeautifulSoup(file, \"lxml\")\n pairs = soup.select('.prPairInfo')\n with open(out_file, 'w') as file:\n i = 0\n for pair in pairs:\n i += 1\n params = pair.select('td')\n fw, rv = params[0].text, reverseComplement(params[9].text)\n file.write(f'>primers_{i}\\n{fw}-{rv}\\n')\n\n\nif __name__ == '__main__':\n try:\n __IPYTHON__\n except NameError:\n import argparse\n\n desc = 'Extract from a PrimerBlast html the sequences.'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('input_file')\n parser.add_argument('output_file')\n args = parser.parse_args()\n in_file = args.input_file\n out_file = args.output_file\n else:\n path = '/home/danpal/Unidad/05_virus/norovirus/nv_GV/primer/'\n in_file = path + 'nv_GV_Primer-Blast.html'\n out_file = path + 'primer3.fasta'\n checkFile(in_file, True)\n checkFile(out_file, False)\n getPrimers(in_file, out_file)\n", "sub_path": "python/primers/get_primers.py", "file_name": "get_primers.py", "file_ext": "py", "file_size_in_byte": 1292, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "bs4.BeautifulSoup", "line_number": 16, "usage_type": "call"}, {"api_name": "revcomp.reverseComplement", "line_number": 23, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 34, "usage_type": "call"}, {"api_name": "check_file.checkFile", "line_number": 44, "usage_type": "call"}, {"api_name": "check_file.checkFile", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "640343859", "text": "import unittest\nfrom datetime import datetime\nfrom unittest.mock import MagicMock\n\nfrom jsonschema import ValidationError\nfrom parameterized import parameterized\n\nfrom application.data_validator import DataValidator\nfrom tests.test_utils import read_data\n\n\nclass OrdersValidatorTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.data_validator = DataValidator()\n\n def test_correct_orders_should_be_valid(self):\n orders_data = read_data('orders.json')\n self.data_validator.validate_orders(orders_data)\n\n def assert_exception(self, orders_data: dict, expected_exception_message: str):\n with self.assertRaises(ValidationError) as context:\n self.data_validator.validate_orders(orders_data)\n self.assertIn(expected_exception_message, str(context.exception.message))\n\n @parameterized.expand([({}, 'data')])\n def test_orders_should_be_incorrect_when_missing_data_field(self, orders_data: dict, field_name: str):\n self.assert_exception(orders_data, f'\\'{field_name}\\' is a required property')\n\n @parameterized.expand([\n [{'data': [{'order_id': 1, 'region': 4, 'delivery_hours': []}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'delivery_hours': []}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'region': 4}]}]\n ])\n def test_orders_should_be_incorrect_when_missing_field(self, orders_data: dict):\n self.assert_exception(orders_data, \"{'orders': [{'id': 1}]}\")\n\n @parameterized.expand([\n ({'data': None}, 'array'),\n ({'data': ['']}, 'object'),\n ])\n def test_orders_should_be_incorrect_when_wrong_type_of_field(self, orders_data: dict, data_type: str):\n self.assert_exception(orders_data, f'is not of type \\'{data_type}\\'')\n\n @parameterized.expand([\n [{'data': [{'order_id': 1, 'weight': None, 'region': 4, 'delivery_hours': []}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'region': None, 'delivery_hours': []}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': None}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'region': [''], 'delivery_hours': []}]}]\n ])\n def test_orders_should_be_incorrect_when_wrong_type_of_field(self, orders_data: dict):\n self.assert_exception(orders_data, \"{'orders': [{'id': 1}]}\")\n\n def test_orders_data_should_be_correct_with_different_field_order(self):\n orders_data = {'data': [{'delivery_hours': [], 'weight': 3, 'region': 4, 'order_id': 1}]}\n self.data_validator.validate_orders(orders_data)\n\n @parameterized.expand([\n ({'EXTRA': 0, 'data': [{'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': [\"00:59-23:59\"]}]}, ''),\n ({'data': [{'EXTRA': 0, 'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': [\"00:59-23:59\"]}]},\n \"{'orders': [{'id': 1}]}\"),\n ])\n def test_orders_should_be_incorrect_when_containing_extra_fields(self, orders_data: dict, field_name: str):\n self.assert_exception(orders_data, field_name)\n\n @unittest.mock.patch('jsonschema.validate')\n def test_orders_should_be_incorrect_when_order_ids_not_unique(self, _):\n orders_data = {'data': [{'order_id': 1}, {'order_id': 1}]}\n self.assert_exception(orders_data, 'Orders ids are not unique')\n\n @unittest.mock.patch('jsonschema.validate')\n def test_correct_delivery_hours_should_be_parsed(self, _):\n orders_data = {\n 'data': [{'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': [\"00:59-23:59\"]}]}\n self.data_validator.validate_orders(orders_data)\n delivery_hours = orders_data['data'][0]['delivery_hours']\n self.assertIsInstance(delivery_hours, list)\n self.assertEqual(len(delivery_hours), 1)\n self.assertIsInstance(delivery_hours[0], tuple)\n begin_time, end_time = delivery_hours[0]\n self.assertEqual(begin_time, datetime.strptime(\"00:59\", \"%H:%M\"))\n self.assertEqual(end_time, datetime.strptime(\"23:59\", \"%H:%M\"))\n\n @parameterized.expand([\n [{'data': [{'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': [\"09:59-33:33\"]}]}],\n [{'data': [{'order_id': 1, 'weight': 3, 'region': 4, 'delivery_hours': [\"9:9-22:33\"]}]}]\n\n ])\n def test_orders_should_be_incorrect_when_delivery_hours_in_wrong_format(self, orders_data: dict):\n self.assert_exception(orders_data, \"{'orders': [{'id': 1}]}\")\n\n @parameterized.expand([\n [{'data': [{'order_id': 1, 'weight': 0, 'region': 4, 'delivery_hours': [\"00:59-23:59\"]}]}],\n [{'data': [{'order_id': 1, 'weight': 51, 'region': 4, 'delivery_hours': [\"00:59-23:59\"]}]}]\n ])\n def test_orders_weight_should_have_in_correct_interval(self, orders_data: dict):\n self.assert_exception(orders_data, \"{'orders': [{'id': 1}]}\")\n\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "tests/orders_validator_tests.py", "file_name": "orders_validator_tests.py", "file_ext": "py", "file_size_in_byte": 4843, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "application.data_validator.DataValidator", "line_number": 15, "usage_type": "call"}, {"api_name": "tests.test_utils.read_data", "line_number": 18, "usage_type": "call"}, {"api_name": "jsonschema.ValidationError", "line_number": 22, "usage_type": "argument"}, {"api_name": "parameterized.parameterized.expand", "line_number": 26, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 26, "usage_type": "name"}, {"api_name": "parameterized.parameterized.expand", "line_number": 30, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 30, "usage_type": "name"}, {"api_name": "parameterized.parameterized.expand", "line_number": 38, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 38, "usage_type": "name"}, {"api_name": "parameterized.parameterized.expand", "line_number": 45, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 45, "usage_type": "name"}, {"api_name": "parameterized.parameterized.expand", "line_number": 58, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 58, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 66, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 66, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 81, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 81, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 71, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 71, "usage_type": "attribute"}, {"api_name": "parameterized.parameterized.expand", "line_number": 84, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 84, "usage_type": "name"}, {"api_name": "parameterized.parameterized.expand", "line_number": 92, "usage_type": "call"}, {"api_name": "parameterized.parameterized", "line_number": 92, "usage_type": "name"}, {"api_name": "unittest.main", "line_number": 101, "usage_type": "call"}]} +{"seq_id": "111259695", "text": "#!/usr/bin/evn python\n# -*- coding: utf-8 -*-\n# @Time    : 2020-09-03 1:38\n# @Author  : qinzhifeng\n# @FileName: shoushijiesuo.py\n# @Software: PyCharm\n\n''' 手机图案解锁案例 '''\n\nfrom appium import webdriver\nfrom appium.webdriver.common.touch_action import TouchAction\n\n# 配置项\ndesired_cap = dict()\ndesired_cap[\"platformName\"] = \"Android\"\ndesired_cap[\"platformVersion\"] = \"5.1.1\"\ndesired_cap[\"deviceName\"] = \"10.0.0.1:5555\"\ndesired_cap['appPackage'] = 'com.android.settings' # 夜神模拟器的包名\ndesired_cap['appActivity'] = '.Settings' # 夜神模拟器的设置页面\ndesired_cap[\"noSign\"] = True # 不重新签名\ndesired_cap['unicodeKeyboard'] = True # 使用 Unicode input 输入法,支持中文输入并隐藏键盘,默认是 false\ndesired_cap['resetKeyboard'] = True # 在运行了 unicodeKeyboard 完成测试后将输入法重置为原有状态,如果单独使用该参数将被忽略,默认值是 false\ndesired_cap['autoGrantPermisions'] = True # 自动同意 app 所需要的各项权限,默认是 false\n\n# 构造 driver webdriver\n# http://localhost:4723/wd/hub appium 的地址\ndriver = webdriver.Remote('http://localhost:4723/wd/hub',desired_cap)\n\n'''\nTouchAction 可以实现⼀些针对⼿势的操作,⽐如滑动、⻓按、拖动等。我们 可以将这些基本⼿势组合 成⼀个相对复杂的⼿势。\n⽐如,我们解锁⼿机或者⼀些应⽤软件都有⼿势解 锁的这种⽅式。 \n使⽤步骤 \n1. 创建 TouchAction 对象 \n2. 通过对象调⽤想执⾏的⼿势 \n3. 通过 perform() 执⾏动作 \n方法:TouchAction(driver).press(x=120,y=420).wait(10).move_to(x=120, y=660).release().perform()\n'''\n\nTouchAction(driver).press(x=319,y=1282).wait(10).move_to(x=319,y=1497).\\\n move_to(x=319,y=1713).move_to(x=532,y=1713).move_to(x=760,y=1713).release().perform()", "sub_path": "shoushijiesuo.py", "file_name": "shoushijiesuo.py", "file_ext": "py", "file_size_in_byte": 1881, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "appium.webdriver.Remote", "line_number": 27, "usage_type": "call"}, {"api_name": "appium.webdriver", "line_number": 27, "usage_type": "name"}, {"api_name": "appium.webdriver.common.touch_action.TouchAction", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "72932163", "text": "\"\"\"\nThis test is launched as part of the existing tox command\n\nIt tests general workflow with multiple classes from the promoter involved\n\n Uses standard pytest fixture as a setup/teardown method\n\"\"\"\nimport logging\nimport os\n\nimport promoter_integration_checks\nimport pytest\nimport yaml\nfrom common import close_logging\nfrom config import PromoterConfigFactory\nfrom dlrn_hash import DlrnAggregateHash, DlrnCommitDistroExtendedHash, DlrnHash\nfrom logic import Promoter\nfrom stage import main as stage_main\n\n\n@pytest.fixture(scope='function')\ndef staged_env(request):\n \"\"\"\n Fixture that runs the staging environment provisioner with parameters,\n yield the stage_info file produced and a promoter configured to use it\n and cleans up after\n It has two parameters by default, to test the interaction for single\n pipeline and for integration pipeline\n :param request: the parameter for the fixture, passed by the\n pytest.mark.parametrize decorator above each test\n :return: yields the stage_info dict and a promoter object\n \"\"\"\n\n # With a series of test ir rapid sequence but in the same test instance,\n # logging configuration is passed from env to env, but log file won't be\n # there anymore, so we need to close the logging handlers\n close_logging(\"promoter-staging\")\n close_logging(\"promoter\")\n log = logging.getLogger('promoter-staging')\n\n # We are going to call the main in the staging passing a composed command\n # line, so we are testing also that the argument parsing is working\n # correctly instead of passing configuration directly\n\n # TODO (akahat) Need to enable legacy non integration pipeline coverage.\n\n release_config = \"CentOS-8/master.yaml\"\n test_case = \"all_integration\"\n\n try:\n test_case = request.param\n except AttributeError:\n pass\n except KeyError:\n log.error(\"Invalid test case '{}'\".format(request.param))\n raise\n\n # Select scenes to run in the staging env depending on the parameter passed\n # to the fixture\n extra_file = \"\"\n scenes = None\n if \"all_\" in test_case:\n extra_file = \"--extra-settings stage-config.yaml\"\n if \"qcow_\" in test_case:\n scenes = 'dlrn,overcloud_images'\n if \"registries_\" in test_case:\n scenes = 'registries'\n if \"containers_\" in test_case:\n scenes = 'dlrn,registries,containers'\n extra_file = \"--extra-settings stage-config.yaml\"\n\n setup_cmd_line = \" {}\".format(extra_file)\n teardown_cmd_line = \"{}\".format(extra_file)\n\n if scenes is not None:\n setup_cmd_line += \" --scenes {}\".format(scenes)\n\n setup_cmd_line += \" setup --release-config {}\".format(release_config)\n teardown_cmd_line += \" teardown \"\n experimental = 'false'\n if \"_experimental\" in test_case:\n experimental = 'true'\n # for the tests of the integration pipeline we need to pass a different\n # file for component db data, and emulate CentOS8/master at least\n log.info(\"Running cmd line: {}\".format(setup_cmd_line))\n\n config = stage_main(setup_cmd_line)\n\n stage_info_path = config['stage_info_path']\n with open(stage_info_path, \"r\") as stage_info_file:\n stage_info = yaml.safe_load(stage_info_file)\n\n overrides = {\n 'log_file': stage_info['main']['log_file'],\n 'repo_url': stage_info['dlrn']['server']['repo_url'],\n 'log_level': 'DEBUG',\n 'experimental': experimental,\n 'default_qcow_server': 'local',\n 'config_file': release_config,\n }\n if \"containers_\" in test_case:\n overrides['containers_list_base_url'] = \\\n stage_info['containers']['containers_list_base_url']\n\n overrides_obj = type(\"FakeArgs\", (), overrides)\n os.environ[\"DLRNAPI_PASSWORD\"] = stage_info['dlrn']['server']['password']\n\n config_builder = PromoterConfigFactory()\n config = config_builder(\"staging\", release_config,\n cli_args=overrides_obj)\n\n promoter = Promoter(config)\n\n # Reflect config changes in to the stage server\n # This might cause some test failures\n target_label = [i.strip() for i in promoter.config.promotions.keys()][0]\n stage_updates = {\n 'target_label': target_label,\n 'candidate_label': promoter.config.promotions[\n target_label]['candidate_label'],\n 'criteria': promoter.config.promotions[target_label]['criteria'],\n }\n\n # TODO (akahat): Refresh stage info dict with config update\n\n stage_info['dlrn']['promotions'][\n 'promotions_candidate'] = stage_updates['candidate_label']\n stage_info['dlrn']['promotions_target'] = target_label\n\n yield (stage_info, promoter)\n\n log.info(\"Running cmd line: {}\".format(teardown_cmd_line))\n stage_main(teardown_cmd_line)\n\n\n@pytest.mark.parametrize(\"staged_env\", (\"containers_single\",\n \"containers_integration\"),\n indirect=True)\ndef test_promote_containers(staged_env):\n \"\"\"\n Tests promotion of containers\n :param staged_env: The stage env fixture\n :return: None\n \"\"\"\n stage_info, promoter = staged_env\n candidate_dict = stage_info['dlrn']['promotions']['promotion_candidate']\n candidate_hash = DlrnHash(source=candidate_dict)\n candidate_label = candidate_dict['name']\n target_label = stage_info['dlrn']['promotion_target']\n promoter.dlrn_client.fetch_current_named_hashes(store=True)\n promoter.promote(candidate_hash, candidate_label, target_label,\n allowed_clients=[\"registries_client\"])\n\n promoter_integration_checks.query_container_registry_promotion(\n stage_info=stage_info)\n\n\n@pytest.mark.parametrize(\"staged_env\", (\"qcow_single\",\n \"qcow_integration\"),\n indirect=True)\ndef test_promote_qcows(staged_env):\n \"\"\"\n Tests promotion of overcloud images\n :param staged_env: The stage env fixture\n :return: None\n \"\"\"\n stage_info, promoter = staged_env\n candidate_dict = stage_info['dlrn']['promotions']['promotion_candidate']\n candidate_hash = DlrnHash(source=candidate_dict)\n\n if stage_info['main']['pipeline_type'] == \"single\":\n error_msg = \"Single pipeline should promote a commit/distro hash\"\n assert type(candidate_hash) == DlrnCommitDistroExtendedHash, error_msg\n else:\n error_msg = \"Integration pipeline should promote an aggregate hash\"\n assert type(candidate_hash) == DlrnAggregateHash, error_msg\n\n target_label = stage_info['dlrn']['promotion_target']\n\n promoter.dlrn_client.fetch_current_named_hashes(store=True)\n promoter.qcow_client.promote(candidate_hash, target_label)\n\n promoter_integration_checks.compare_tagged_image_hash(stage_info=stage_info)\n\n\n# These are the closest test to integration jobs\ndef test_single_promote(staged_env):\n stage_info, promoter = staged_env\n\n candidate_dict = stage_info['dlrn']['promotions']['promotion_candidate']\n candidate_hash = DlrnHash(source=candidate_dict)\n\n promoter.promote(candidate_hash, \"tripleo-ci-staging\",\n \"tripleo-ci-staging-promoted\")\n\n\n@pytest.mark.parametrize(\"staged_env\", (\"all_single\",\n \"all_integration\"),\n indirect=True)\ndef test_promote_all(staged_env):\n \"\"\"\n Tests promotion of candidate hash in all its part: dlrn, images, containers\n :param staged_env: The stage env fixture\n :return: None\n \"\"\"\n stage_info, promoter = staged_env\n\n promoted_pairs = promoter.promote_all()\n\n promoter_integration_checks.compare_tagged_image_hash(\n stage_info=stage_info)\n promoter_integration_checks.query_container_registry_promotion(\n stage_info=stage_info)\n promoter_integration_checks.check_dlrn_promoted_hash(\n stage_info=stage_info)\n promoter_integration_checks.parse_promotion_logs(stage_info=stage_info)\n\n error_msg = \"Nothing promoted, and checks did not complain\"\n assert len(promoted_pairs) != 0, error_msg\n\n\n@pytest.mark.parametrize(\"staged_env\", (\"all_single\",\n \"all_integration\"),\n indirect=True)\n@pytest.mark.xfail(reason=\"Not Implemented\", run=False)\ndef test_promote_all_no_promotions(staged_env):\n \"\"\"\n This test should add a second promotion step with criteria, to verify\n taht we can actually perform two promotions in a row.\n It's not easy, as the staging environment needs to support a second\n promotion candidate\n :param staged_env:\n :return:\n \"\"\"\n assert False\n\n\n@pytest.mark.parametrize(\"staged_env\", (\"all_single\",\n \"all_integration\"),\n indirect=True)\n@pytest.mark.xfail(reason=\"Not Implemented\", run=False)\ndef test_promote_all_two_promotions_in_a_row(staged_env):\n \"\"\"\n This test should add a second promotion step with criteria, to verify\n taht we can actually perform two promotions in a row.\n It's not easy, as the staging environment needs to support a second\n promotion candidate\n :param staged_env:\n :return:\n \"\"\"\n assert False\n", "sub_path": "ci-scripts/dlrnapi_promoter/test_promoter_functional.py", "file_name": "test_promoter_functional.py", "file_ext": "py", "file_size_in_byte": 9149, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "common.close_logging", "line_number": 37, "usage_type": "call"}, {"api_name": "common.close_logging", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 39, "usage_type": "call"}, {"api_name": "stage.main", "line_number": 87, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 91, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 106, "usage_type": "attribute"}, {"api_name": "config.PromoterConfigFactory", "line_number": 108, "usage_type": "call"}, {"api_name": "logic.Promoter", "line_number": 112, "usage_type": "call"}, {"api_name": "stage.main", "line_number": 133, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 21, "usage_type": "call"}, {"api_name": "dlrn_hash.DlrnHash", "line_number": 147, "usage_type": "call"}, {"api_name": "promoter_integration_checks.query_container_registry_promotion", "line_number": 154, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 136, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 136, "usage_type": "attribute"}, {"api_name": "dlrn_hash.DlrnHash", "line_number": 169, "usage_type": "call"}, {"api_name": "dlrn_hash.DlrnCommitDistroExtendedHash", "line_number": 173, "usage_type": "name"}, {"api_name": "dlrn_hash.DlrnAggregateHash", "line_number": 176, "usage_type": "name"}, {"api_name": "promoter_integration_checks.compare_tagged_image_hash", "line_number": 183, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 158, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 158, "usage_type": "attribute"}, {"api_name": "dlrn_hash.DlrnHash", "line_number": 191, "usage_type": "call"}, {"api_name": "promoter_integration_checks.compare_tagged_image_hash", "line_number": 210, "usage_type": "call"}, {"api_name": "promoter_integration_checks.query_container_registry_promotion", "line_number": 212, "usage_type": "call"}, {"api_name": "promoter_integration_checks.check_dlrn_promoted_hash", "line_number": 214, "usage_type": "call"}, {"api_name": "promoter_integration_checks.parse_promotion_logs", "line_number": 216, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 197, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 197, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 222, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 222, "usage_type": "attribute"}, {"api_name": "pytest.mark.xfail", "line_number": 225, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 225, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 238, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 238, "usage_type": "attribute"}, {"api_name": "pytest.mark.xfail", "line_number": 241, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 241, "usage_type": "attribute"}]} +{"seq_id": "476514302", "text": "#!/usr/bin/python\nimport socket\nimport cv2\nimport numpy\nimport base64\n\n## getting the hostname by socket.gethostname() method\nhostname = socket.gethostname()\n\n## getting the IP address using socket.gethostbyname() method\nip_address = socket.gethostbyname(hostname)\n\n## printing the hostname and ip_address\nprint(f\"Hostname: {hostname}\")\nprint(f\"IP Address: {ip_address}\")\n\n# settings for TCP server\nTCP_IP = ip_address\nTCP_PORT = 5001\n\n#encode parameters for image conversion\nencode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]\n\nprint(\"videoTCPServer9_first_send\")\nprint(\"open TCP server socket\")\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nsock.bind((TCP_IP, TCP_PORT))\nprint(\"Waiting for TCP client ...\")\nsock.listen(True)\nconn, addr = sock.accept()\nprint(\"Connected: \" + addr[0]);\n\n# Connect camera\ncapture = cv2.VideoCapture(0)\n\n# Read first frame from Camera\nret, frame = capture.read()\n# optional resizing of frame\n#frame_sm = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)\n# encode image as base64 String\nresult, imgencode = cv2.imencode('.jpg', frame, encode_param)\nstringData = base64.b64encode(imgencode)\n\nwhile(True):\n try:\n input = conn.recv(11)\n except socket.error:\n input = \"error\"\n print(\"Lost connection...\")\n if input == b'getNewFrame':\n # send previous captured frame to server \n # (can also be done in different order: first capture then send -> depends on application)\n conn.send( bytes(str(len(stringData)).ljust(16), encoding = 'utf-8'));\n conn.send( stringData );\n\n # Read next frame from Camera\n ret, frame = capture.read()\n\n # encode image as base64 String\n result, imgencode = cv2.imencode('.jpg', frame, encode_param)\n stringData = base64.b64encode(imgencode)\n elif input == b'closeDriver':\n break\n else: \n print(\"Waiting for TCP client ...\")\n sock.listen(True)\n conn, addr = sock.accept()\n print(\"Connected: \" + addr[0]); \n \nsock.close()\ncv2.destroyAllWindows() \n", "sub_path": "Camera/old/videoTCPServer9_first_send.py", "file_name": "videoTCPServer9_first_send.py", "file_ext": "py", "file_size_in_byte": 2127, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "socket.gethostname", "line_number": 8, "usage_type": "call"}, {"api_name": "socket.gethostbyname", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.IMWRITE_JPEG_QUALITY", "line_number": 22, "usage_type": "attribute"}, {"api_name": "socket.socket", "line_number": 26, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 26, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 26, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 27, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.imencode", "line_number": 42, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 43, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.imencode", "line_number": 61, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "22771261", "text": "import cv2\nimport numpy as np\n\ndef imageCopy(src):\n return np.copy(src)\n\ndef makeBlackImage(image, color=False):\n height, width = image.shape[0], image.shape[1]\n if color is True:\n return np.zeros((height, width, 3), np.uint8)\n else:\n if len(image.shape) == 2:\n return np.zeros((height, width), np.uint8)\n else:\n return np.zeros((height, width, 3), np.uint8)\n\ndef convertColor(image, flag=cv2.COLOR_BGR2GRAY):\n return cv2.cvtColor(image, flag)\n \ndef rangeColor(image, lower, upper):\n result = imageCopy(image)\n return cv2.inRange(result, lower, upper)\n \ndef addImage(image1, image2):\n return cv2.add(image1, image2)\n \ndef imageMorphologyKernel(flag=cv2.MORPH_RECT, size=5):\n return cv2.getStructuringElement(flag, (size, size))\n \ndef imageMorphologyEx(image, op, kernel, iterations=1):\n return cv2.morphologyEx(image, op=op, kernel=kernel, iterations=iterations)\n\ndef fillPolyROI(image, points):\n if len(image.shape) == 2:\n channels = 1\n else:\n channels = image.shape[2]\n mask = makeBlackImage(image)\n ignore_mask_color = (255,) * channels\n cv2.fillPoly(mask, points, ignore_mask_color)\n return mask\n\ndef polyROI(image, points):\n mask = fillPolyROI(image, points)\n return cv2.bitwise_and(image, mask)\n\ndef houghLinesP(image, rho=1.0, theta=np.pi/180, threshold=100, minLineLength=10, maxLineGap=100):\n return cv2.HoughLinesP(image, rho, theta, threshold, minLineLength=minLineLength, maxLineGap=maxLineGap)\n\ndef splitTwoSideLines(lines, slope_threshold = (5. * np.pi / 180.)):\n lefts = []\n rights = []\n for line in lines:\n x1 = line[0,0]\n y1 = line[0,1]\n x2 = line[0,2]\n y2 = line[0,3]\n if (x2-x1) == 0:\n continue\n slope = (float)(y2-y1)/(float)(x2-x1)\n if abs(slope) < slope_threshold:\n continue\n if slope <= 0:\n lefts.append([slope, x1, y1, x2, y2])\n else:\n rights.append([slope, x1, y1, x2, y2])\n return lefts, rights\n\ndef medianPoint(x):\n if len(x) == 0:\n return None\n else:\n xx = sorted(x)\n return xx[(int)(len(xx)/2)]\n\ndef interpolate(x1, y1, x2, y2, y):\n return int(float(y - y1) * float(x2-x1) / float(y2-y1) + x1)\n\ndef lineFitting(image, lines, color = (0,0,255), thickness = 3, slope_threshold = (5. * np.pi / 180.)):\n result = imageCopy(image)\n height = image.shape[0]\n lefts, rights = splitTwoSideLines(lines, slope_threshold)\n left = medianPoint(lefts)\n right = medianPoint(rights)\n min_y = int(height*0.6)\n max_y = height\n min_x_left = interpolate(left[1], left[2], left[3], left[4], min_y)\n max_x_left = interpolate(left[1], left[2], left[3], left[4], max_y)\n min_x_right = interpolate(right[1], right[2], right[3], right[4], min_y)\n max_x_right = interpolate(right[1], right[2], right[3], right[4], max_y)\n cv2.line(result, (min_x_left, min_y), (max_x_left, max_y), color, thickness)\n cv2.line(result, (min_x_right, min_y), (max_x_right, max_y), color, thickness)\n return result\n\ndef lane_detection_and_draw(image):\n result = imageCopy(image)\n HLS = convertColor(result, cv2.COLOR_BGR2HLS)\n Y_lower = np.array([15, 52, 75])\n Y_upper = np.array([30, 190, 255])\n Y_BIN = rangeColor(HLS, Y_lower, Y_upper)\n W_lower = np.array([0, 200, 0])\n W_upper = np.array([180, 255, 255])\n W_BIN = rangeColor(HLS, W_lower, W_upper)\n result = addImage(Y_BIN, W_BIN)\n MORPH_ELLIPSE = imageMorphologyKernel(cv2.MORPH_ELLIPSE, 7)\n result = imageMorphologyEx(result, cv2.MORPH_CLOSE , MORPH_ELLIPSE) \n MORPH_CROSS = imageMorphologyKernel(cv2.MORPH_CROSS, 3)\n result = imageMorphologyEx(result, cv2.MORPH_OPEN , MORPH_CROSS)\n result_line = imageMorphologyEx(result, cv2.MORPH_GRADIENT , MORPH_CROSS)\n height, width = image.shape[:2]\n src_pt1 = [int(width*0.4), int(height*0.65)]\n src_pt2 = [int(width*0.6), int(height*0.65)]\n src_pt3 = [int(width*0.9), int(height*0.9)]\n src_pt4 = [int(width*0.1), int(height*0.9)]\n roi_poly_02 = np.array([[tuple(src_pt1), tuple(src_pt2), tuple(src_pt3), tuple(src_pt4)]], dtype=np.int32)\n line_roi = polyROI(result_line, roi_poly_02)\n lines = houghLinesP(line_roi, 1, np.pi/180, 10, 5, 10)\n result = lineFitting(image, lines, (0, 0, 255), 5, 5. * np.pi / 180.)\n return result\n", "sub_path": "lane_detection.py", "file_name": "lane_detection.py", "file_ext": "py", "file_size_in_byte": 4397, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.copy", "line_number": 5, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.add", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.MORPH_RECT", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.getStructuringElement", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.morphologyEx", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.fillPoly", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 47, "usage_type": "attribute"}, {"api_name": "cv2.HoughLinesP", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 79, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 91, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 92, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HLS", "line_number": 97, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 102, "usage_type": "call"}, {"api_name": "cv2.MORPH_ELLIPSE", "line_number": 105, "usage_type": "attribute"}, {"api_name": "cv2.MORPH_CLOSE", "line_number": 106, "usage_type": "attribute"}, {"api_name": "cv2.MORPH_CROSS", "line_number": 107, "usage_type": "attribute"}, {"api_name": "cv2.MORPH_OPEN", "line_number": 108, "usage_type": "attribute"}, {"api_name": "cv2.MORPH_GRADIENT", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 117, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 118, "usage_type": "attribute"}]} +{"seq_id": "82660226", "text": "import csv\nimport json\n\n\ndef float_or_nan(x):\n if x == \".\":\n return x\n else:\n return float(x)\n\n\n_regions_value_type_map = {\n \"#Region\": str,\n \"Chromosome\": lambda x: str(x).replace(\"chr\", \"\").replace(\"CHR\", \"\"),\n \"Start_position\": int,\n \"End_position\": int,\n \"Start_transcript\": str,\n \"End_transcript\": str,\n \"Pass_or_fail\": str,\n \"RC\": int,\n \"RC+\": int,\n \"RC-\": int,\n \"MEDCOV\": float_or_nan,\n \"MINCOV\": float_or_nan,\n \"MEDQCOV\": float_or_nan,\n \"MINQCOV\": float_or_nan,\n \"MAXFLMQ\": float_or_nan,\n \"MAXFLBQ\": float_or_nan\n}\n\n\n_summary_value_type_map = {\n \"#CHROM\": lambda x: x,\n \"RC\": int,\n \"RCIN\": lambda x: x if x == \"-\" else int(x),\n \"RCOUT\": lambda x: x if x == \"-\" else int(x)\n}\n\n\n_profile_value_type_map = {\n \"#Chromosome\": lambda x: x,\n \"Position\": int,\n \"Transcript_coordinate\": str,\n \"COV\": int,\n \"QCOV\": int,\n \"MEDBQ\": float_or_nan,\n \"FLBQ\": float_or_nan,\n \"MEDMQ\": float_or_nan,\n \"FLMQ\": float_or_nan\n}\n\n\ndef load_gui_json_output(file_name):\n with open(file_name, 'r') as json_file:\n return json.load(json_file)\n\n\ndef load_coverview_profile_output(file_name):\n\n data = {}\n header_names = []\n current_region_name = None\n\n with open(file_name, 'r') as profile_file:\n for line in profile_file:\n if line.startswith(\"#\"):\n header_names = line.strip().split(\"\\t\")\n elif line.startswith(\"[\"):\n region_name = line.strip().strip(\"[\").strip(\"]\")\n data[region_name] = {}\n current_region_name = region_name\n else:\n\n if line.strip() == \"\":\n continue\n\n cols = line.strip().split(\"\\t\")\n chrom_pos = \":\".join([cols[0], cols[1]])\n data[current_region_name][chrom_pos] = {}\n\n for col_index, col_data in enumerate(cols):\n typed_data = _profile_value_type_map[header_names[col_index]](col_data)\n data[current_region_name][chrom_pos][header_names[col_index]] = typed_data\n return data\n\n\ndef load_coverview_summary_output(file_name):\n with open(file_name, 'r') as summary_file:\n summary_file_reader = csv.DictReader(summary_file, delimiter='\\t')\n data = {}\n\n for record in summary_file_reader:\n chrom = record['#CHROM']\n data[chrom] = {}\n\n for key, value in record.items():\n if key == \"#CHROM\":\n continue\n else:\n typed_value = _summary_value_type_map[key](value)\n data[chrom][key] = typed_value\n\n return data\n\n\ndef load_coverview_regions_output(file_name):\n with open(file_name, 'r') as regions_file:\n data = {}\n regions_file_reader = csv.DictReader(regions_file, delimiter='\\t')\n\n for record in regions_file_reader:\n region_name = record['#Region']\n data[region_name] = {}\n\n for key, converter_function in _regions_value_type_map.items():\n\n if key in record:\n typed_value = converter_function(record[key])\n data[region_name][key] = typed_value\n\n return data\n", "sub_path": "testutils/output_checkers.py", "file_name": "output_checkers.py", "file_ext": "py", "file_size_in_byte": 3279, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 55, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 89, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "325381302", "text": "\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.views.generic import TemplateView\n\nfrom voting.models import Bill\nfrom voting.models import Member\n\n\nclass HomeView(TemplateView):\n template_name = \"website/index.html\"\n context_object_name = \"homepage\"\n\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n return context\n\n\nclass BillsView(TemplateView):\n template_name = \"website/bills.html\"\n context_object_name = \"bills\"\n\n def get_context_data(self, **kwargs):\n context = super(BillsView, self).get_context_data(**kwargs)\n\n bills = Bill.objects.all()\n for bill in bills:\n bill.votes = bill.get_votes()\n context['bills'] = bills\n return context\n\n\nclass MembersView(TemplateView):\n template_name = \"website/members.html\"\n context_object_name = \"members\"\n\n def get_context_data(self, **kwargs):\n context = super(MembersView, self).get_context_data(**kwargs)\n\n members = Member.objects.all()\n context['members'] = members\n return context", "sub_path": "website/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1114, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 3, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView", "line_number": 11, "usage_type": "name"}, {"api_name": "django.views.generic.TemplateView", "line_number": 20, "usage_type": "name"}, {"api_name": "voting.models.Bill.objects.all", "line_number": 27, "usage_type": "call"}, {"api_name": "voting.models.Bill.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "voting.models.Bill", "line_number": 27, "usage_type": "name"}, {"api_name": "django.views.generic.TemplateView", "line_number": 34, "usage_type": "name"}, {"api_name": "voting.models.Member.objects.all", "line_number": 41, "usage_type": "call"}, {"api_name": "voting.models.Member.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "voting.models.Member", "line_number": 41, "usage_type": "name"}]} +{"seq_id": "435042103", "text": "import break_out_scores as score\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.constants as const\npi = const.pi\ndef read_sav_files(sav_file):\n pkl_file = open(sav_file, 'rb')\n data = pickle.load(pkl_file)\n return data\ndef read_sav_files_with_scores(sav_file):\n pkl_file = open(sav_file, 'rb')\n [data,scores] = pickle.load(pkl_file)\n return [data,scores]\ndef get_stats_method(x):\n stats = {}\n x.sort()\n n = len(x)\n x_pert = np.arange(5,100,5)\n for pert in x_pert:\n \n stats[pert] = x[int(n*pert/100.0 + 0.5)]\n mad_array = []\n for i in x:\n mad_array.append(abs(i-stats[50]))\n mad_array.sort()\n MAD = mad_array[int(len(mad_array)*0.5+0.5)]\n return stats,MAD\n\ndef get_expert_weights():\n weights = {}\n weights['pace'] = 0.2#1.0/6.0\n weights['cornering'] = 0.15#1.0/6.0 \n weights['junctionacceleration'] = 0.1#1.0/6.0\n weights['junctionbrake'] = 0.2#1.0/6.0\n weights['roadbrake'] = 0.1#1.0/6.0\n weights['roadacceleration'] = 0.25#1.0/6.0\n return weights\n \ndef get_correct_format(data):\n output = {}\n for subid in data:\n for metric in data[subid]:\n if metric not in output:\n output[metric] = {}\n for road_type in data[subid][metric]:\n if road_type not in output[metric]:\n output[metric][road_type] = []\n output[metric][road_type].append(data[subid][metric][road_type]) \n return output \ndef get_stats():\n #rospa_data = read_sav_files(\"../sav_files/rospa-driver-reports-2014-01-07.sav\") \n #print rospa_data\n rospa_data,scores_subids =read_sav_files_with_scores(\"../sav_files/rospa-driver-reports-2013-09-05_subids_distance_with_scores.sav\")\n rospa_data = get_correct_format(rospa_data)\n #import pdb;pdb.set_trace()\n stats = {} \n MAD = {}\n road_types = rospa_data['pace'].keys() \n for metric in rospa_data:\n if metric!=\"distance\":\n if metric not in stats:\n stats[metric] = {}\n MAD[metric] = {}\n for i,road_type in enumerate(road_types):\n stats[metric][road_type],MAD[metric][road_type] = get_stats_method(rospa_data[metric][road_type])\n return [stats,MAD,road_types]\n\ndef get_stats_1():\n rospa_data = read_sav_files(\"../sav_files/rospa-driver-reports-2014-01-07.sav\") \n #print rospa_data\n #rospa_data,scores_subids =read_sav_files_with_scores(\"../sav_files/rospa-driver-reports-2013-09-05_subids_distance_with_scores.sav\")\n #rospa_data = get_correct_format(rospa_data)\n #import pdb;pdb.set_trace()\n stats = {} \n MAD = {}\n road_types = rospa_data['pace'].keys() \n for metric in rospa_data:\n if metric!=\"distance\":\n if metric not in stats:\n stats[metric] = {}\n MAD[metric] = {}\n for i,road_type in enumerate(road_types):\n stats[metric][road_type],MAD[metric][road_type] = get_stats_method(rospa_data[metric][road_type])\n return [stats,MAD,road_types]\n\n\ndef get_class(stats,var,type_of_filter):\n if type_of_filter == \"advanced\":\n low_thres_upper = 10\n ideal_thres_upper = 85\n average_thres_upper = 95\n else:\n low_thres_upper = 10\n ideal_thres_upper = 85\n average_thres_upper = 95\n #low_thres_upper = 5\n #ideal_thres_upper = 80\n #average_thres_upper = 95 \n \n if var <=stats[low_thres_upper]:\n score_class = \"low\"\n if stats[low_thres_upper] < var <= stats[ideal_thres_upper]:\n score_class = \"ideal\"\n if stats[ideal_thres_upper] < var <= stats[average_thres_upper]:\n score_class = \"average\"\n if stats[average_thres_upper]med:\n gauss_score = gauss_score*(1.0-high)/gauss_max\n gauss_score = gauss_score + high\n else:\n gauss_score = gauss_score*(1.0-low)/gauss_max\n gauss_score = gauss_score + low\n return gauss_score\ndef get_scores_from_dict(data,expert_weights,stats,MAD,road_types,type_of_filter):\n experts = get_expert_weights()\n score = {}\n for subid in data: \n temp_score_dict = {}\n distances = {}\n\n for metric in data[subid]:\n if metric !=\"distance\":\n if metric not in temp_score_dict:\n temp_score_dict[metric] = 0.0\n for i,road_type in enumerate(road_types):\n \n if float(data[subid][metric][road_type])!=0.0:\n if stats[metric][road_type][40]!=0.0:\n if road_type not in distances: \n distances[road_type] = 0.0\n score_class = get_class(stats[metric][road_type],data[subid][metric][road_type],type_of_filter)\n mad = MAD[metric][road_type]#stats[metric][road_type][75]- stats[metric][road_type][50]\n #score_weight = expert_weights[metric][score_class]\n score_weight = get_gauss(data[subid][metric][road_type],mad,stats[metric][road_type][50],expert_weights[metric]['high'],expert_weights[metric]['low'])\n temp_score_dict[metric]+=score_weight*data[subid]['distance'][road_type]\n distances[road_type] = data[subid]['distance'][road_type]\n \n total_distance = 0.0\n for road_type in distances:\n total_distance+=distances[road_type]\n if total_distance!=0.0:\n if subid not in score:\n score[subid] = {}\n for metric in temp_score_dict:\n if 'expert' not in score[subid]:\n score[subid]['expert'] = 0.0\n \n \n if metric not in score[subid]:\n #import pdb;pdb.set_trace()\n score[subid][metric] = 100.0*temp_score_dict[metric]/total_distance\n score[subid]['expert']+=score[subid][metric]*experts[metric]\n \n return score\n\ndef convert_subids():\n \n x_convert = {}\n filename = \"03_subscription_mapping.csv\"\n with open(filename, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n x_convert[row[0]] = row[1]\n\n return x_convert\n \ndef get_scores_per_metric(computed_scores):\n scores_per_metric = {}\n for subid in computed_scores:\n for metric in computed_scores[subid]:\n if metric not in scores_per_metric:\n scores_per_metric[metric] = []\n scores_per_metric[metric].append(computed_scores[subid][metric])\n return scores_per_metric\nweights = score.score_weights()\nstats,MAD,road_types = get_stats()\n#data,scores_subids =read_sav_files_with_scores(\"../sav_files/ares-reprocessed-xml-profiles-2014-01-14_subids_distance_with_scores.sav\")\ndata,scores_subids =read_sav_files_with_scores(\"../sav_files/axaie-driver-reports-2014-01-10_subids_distance_with_scores.sav\")\ncomputed_scores = get_scores_from_dict(data,weights,stats,MAD,road_types,\"old\")\nscores_per_metric = get_scores_per_metric(computed_scores)\n\nweights = score.score_weights_1()\nstats_1,MAD_1,road_types = get_stats_1()\ndata_1,scores_subids_1 =read_sav_files_with_scores(\"../sav_files/ares-reprocessed-xml-profiles-2014-01-14_subids_distance_with_scores.sav\")\ncomputed_scores_1 = get_scores_from_dict(data_1,weights,stats_1,MAD_1,road_types,\"advanced\")\nscores_per_metric_1 = get_scores_per_metric(computed_scores_1)\n\n\nnumbins = np.arange(0,101,1) \nfor i,metric in enumerate(scores_per_metric.keys()):\n plt.subplot(4,2,i+1)\n plt.hist(scores_per_metric[metric],alpha=0.5,bins=numbins,color=\"c\",label=metric)\n plt.hist(scores_per_metric_1[metric],alpha=0.5,bins=numbins,color=\"r\",label=metric)\n plt.legend(loc=0)\nplt.show()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n", "sub_path": "mydrive_python/check_axa_distributions/code/test_axaie_individual_scoring.py", "file_name": "test_axaie_individual_scoring.py", "file_ext": "py", "file_size_in_byte": 8349, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "scipy.constants.pi", "line_number": 6, "usage_type": "attribute"}, {"api_name": "scipy.constants", "line_number": 6, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 112, "usage_type": "call"}, {"api_name": "break_out_scores.score_weights", "line_number": 184, "usage_type": "call"}, {"api_name": "break_out_scores.score_weights_1", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}]} +{"seq_id": "606453310", "text": "import logging\nimport re\n\nlogger = logging.getLogger('log01')\n\n\nclass BatchCheckBase:\n def __init__(self, pattern_id, urls):\n self.usr_dict = {}\n self.usr_list = []\n self.pattern_id = pattern_id\n for url in urls:\n self.get_id(url)\n\n def get_id(self, url):\n m = re.match(self.pattern_id, url)\n if m:\n usr_id = m.group('id')\n self.usr_dict[usr_id.lower()] = url\n self.usr_list.append(usr_id)\n\n def check(self):\n pass\n\n\ndef match1(text, *patterns):\n if len(patterns) == 1:\n pattern = patterns[0]\n match = re.search(pattern, text)\n if match:\n return match.group(1)\n else:\n return None\n else:\n ret = []\n for pattern in patterns:\n match = re.search(pattern, text)\n if match:\n ret.append(match.group(1))\n return ret\n\n\nfake_headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.1'\n}\n", "sub_path": "biliup/plugins/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1235, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 4, "usage_type": "call"}, {"api_name": "re.match", "line_number": 16, "usage_type": "call"}, {"api_name": "re.search", "line_number": 29, "usage_type": "call"}, {"api_name": "re.search", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "223732454", "text": "import cv2\n\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\nrecognizer.read('C:\\\\Users\\Marvin\\Desktop\\Opencv-face-detection-python-master\\\\trainner\\\\trainner.yml')\ncascadePath = \"C:\\\\Users\\Marvin\\Desktop\\Opencv-face-detection-python-master\\haarcascade_frontalface_default.xml\"\nfaceCascade = cv2.CascadeClassifier(cascadePath);\n\ncam = cv2.VideoCapture(0)\nfont = cv2.FONT_HERSHEY_SIMPLEX\nname = \"\"\nwhile True:\n ret, im =cam.read()\n gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n faces=faceCascade.detectMultiScale(gray, 1.2,5)\n for(x,y,w,h) in faces:\n cv2.rectangle(im,(x,y),(x+w,y+h+10),(225,0,0),2)\n Id, conf = recognizer.predict(gray[y:y+h,x:x+w])\n if(int(conf)<70):\n if(int(Id) == 1):\n name=\"Mohammad\"\n elif(int(Id) == 2):\n name=\"Rahmani\"\n else:\n name=\"Unknown\"\n\n cv2.putText(im, str(name), (x, y-10), font, 1, (255,255,255))\n cv2.imshow('im',im)\n if cv2.waitKey(30) & 0xFF == 27:\n break\ncam.release()\ncv2.destroyAllWindows()", "sub_path": "Master/recognizer.py", "file_name": "recognizer.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "cv2.face.LBPHFaceRecognizer_create", "line_number": 3, "usage_type": "call"}, {"api_name": "cv2.face", "line_number": 3, "usage_type": "attribute"}, {"api_name": "cv2.CascadeClassifier", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 9, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 13, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "469353708", "text": "from typing import List\n\nimport redis\n\nfrom .image_model import ImageModel\n\ncache = redis.Redis(host=\"redis\", port=6379)\n\n\"\"\" Cache Structure\n key | Type | Data Format | Example (key: value)\n------------------+----------------+-----------------+---------------------------------------------------\n images:file_list | Set | filename | images:file_list: 8f9478cbf3182768.jpg\n images:working | Set | filename_style | images:working: 8f9478cbf3182768.jpg_cartoongan_hayao\n style | Array(String) | [filename] | cartoongan_hayao: [8f9478cbf3182768.jpg, 8f9478cbf3182768.jpg, ...]\n\n\"\"\"\n\nclass Cache:\n file_list_key = \"images:file_list\"\n working_key = \"images:working\"\n\n @classmethod\n def add(cls, filename: str, style: str):\n cache.sadd(cls.file_list_key, filename)\n cache.sadd(style, filename)\n\n @classmethod\n def add_all_db_data(cls, all_data_in_db: List[ImageModel]):\n all_filename = [x.filename for x in all_data_in_db]\n cache.sadd(cls.file_list_key, *all_filename)\n for image_model in all_data_in_db:\n filename = image_model.filename\n for style in image_model.styles:\n cache.sadd(style, filename)\n\n @classmethod\n def exist_image(cls, filename: str):\n return bool(cache.sismember(cls.file_list_key, filename))\n\n @classmethod\n def exist_output_image(cls, filename: str, style: str):\n return bool(cache.sismember(style, filename))\n\n @classmethod\n def remove_working(cls, filename: str, style: str):\n cache.srem(cls.working_key, cls.working_job_name(filename, style))\n\n @classmethod\n def working_job_name(cls, filename: str, style: str):\n return \"_\".join([filename, style])\n", "sub_path": "modelserver/database/cache.py", "file_name": "cache.py", "file_ext": "py", "file_size_in_byte": 1787, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "redis.Redis", "line_number": 7, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 28, "usage_type": "name"}, {"api_name": "image_model.ImageModel", "line_number": 28, "usage_type": "name"}, {"api_name": "image_model.filename", "line_number": 32, "usage_type": "attribute"}, {"api_name": "image_model.styles", "line_number": 33, "usage_type": "attribute"}]} +{"seq_id": "292586961", "text": "#Python project for student grades\n\nimport statistics as s\n\nprint('Login with admin credentials to access Grade Central:....')\nusername = input('Username: ')\n\nstudentsGrade = {'Vishal':[45,87,98],\n 'Prodipto': [65,76,87],\n 'Pallav': [87,76,76]}\n\ndef firstMenu():\n print('1. Enter Grades.')\n print('2. Remove student.')\n print('3. Student Average Grades.')\n print('4. Exit')\n choice=int(input('Enter your choice : '))\n #var_choice = int(choice)\n if choice >= 4 :\n print('Invalid Selection...')\n else:\n return choice\n\n\ndef gradeOperations(choice):\n if choice == 1: \n addStudent()\n elif choice == 2:\n removeStudent()\n elif choice == 3:\n studentAverage()\n else:\n exit()\n\n\ndef addStudent():\n print('Enter the below details:')\n sName = input('Student Name : ')\n Grade = input('Grade : ')\n\n if sName in studentsGrade:\n studentsGrade[sName].append(float(Grade))\n print('Student grade added successfully. Updated details as below:')\n print(studentsGrade)\n else:\n print('Student not found. Please give an existing user')\n\ndef removeStudent():\n sNametoDelete = input('Enter the name of the student to be deleted: ')\n print('Are you sure to delete?')\n user_Choice = int(input('enter 1 for yes or 2 for no :'))\n if user_Choice == 1:\n del studentsGrade[sNametoDelete]\n print('Student deleted successfully. Updated details as below:')\n print(studentsGrade)\n \ndef studentAverage():\n for eachStudent in studentsGrade:\n gradeList = studentsGrade[eachStudent]\n print(gradeList)\n avgGrade = s.mean(gradeList)\n\n print(eachStudent,'has an average grade of:',avgGrade)\n \n \n\nif username == 'admin':\n password = input('Password: ')\n if password == '1234':\n print('Welcome to Grade Central !')\n user_choice = firstMenu()\n gradeOperations(user_choice)\nelse:\n print('User not found..')\n print('Please login with admin credentials')\n\n\n\n\n", "sub_path": "PythonAssignment.py", "file_name": "PythonAssignment.py", "file_ext": "py", "file_size_in_byte": 2074, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "statistics.mean", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "394285992", "text": "\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef PlotSlumping():\n print('hi you there, im plotting')\n data2 = np.loadtxt('time_data.dat')\n #data3 = np.loadtxt('geometric_data.dat')\n #data = np.loadtxt('density_data.dat')\n #print(data)\n #print(data3)\n #for i in range(0,len(data),):\n multiple_data = ['10','100','500','1000']\n \n for i in multiple_data:\n data3 = np.loadtxt('geometric_data_'+i+'.dat')\n data = np.loadtxt('density_data_'+i+'.dat')\n plt.plot(data3,data[-1],label=i)\n \n plt.legend(title='Spatial Nodes')\n plt.title('Grid Independance at t=500s for Slumping process')\n plt.xlabel('Relative height up cylinder from bottom (x/a)')\n plt.ylabel(r'Relative density change ($\\rho/\\rho_{0}$)')\n #plt.show()\n plt.savefig('slumping_plot.png')\n\ndef PlotSlump():\n print('hi you there, im plotting')\n data2 = np.loadtxt('time_data_odepack.dat')\n data3 = np.loadtxt('geometric_data_odepack.dat')\n data = np.loadtxt('density_data_odepack.dat')\n print(len(data),len(data2),len(data3))\n for i in range(0,len(data),100):\n plt.plot(data3,data[i],label=data2[i])\n \n plt.legend(title='Time')\n plt.title('Progression of slump through time')\n plt.xlabel('Relative height up cylinder from bottom (x/a)')\n plt.ylabel(r'Relative density change ($\\rho/\\rho_{0}$)')\n plt.show()\n #plt.savefig('slumping_plot_progression.png')\n\n\nPlotSlump()\n\n", "sub_path": "PackSlumpingPlot.py", "file_name": "PackSlumpingPlot.py", "file_ext": "py", "file_size_in_byte": 1450, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.loadtxt", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}]} +{"seq_id": "382918296", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom time import time\r\nimport pandas as pd \r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n# Load dataset\r\nTrain_data = pd.read_csv('Train_Data.csv', header=None)\r\nTrain_label = pd.read_csv('Train_Labels.csv', header=None, dtype=int)\r\n\r\nTest_data = pd.read_csv('Test_Data.csv', header=None)\r\nTest_label = pd.read_csv('Test_Labels.csv', header=None, dtype=int)\r\n\r\nt1 = time()\r\nC_range = np.logspace(-2, 10, 13)\r\ngamma_range = np.logspace(-9, 3, 13)\r\nparam_grid = dict(gamma=gamma_range, C=C_range)\r\nsvr = svm.SVC(kernel='rbf',decision_function_shape='ovo')\r\nclf = GridSearchCV(svr, param_grid=param_grid)\r\nclf.fit(Train_data, Train_label)\r\ntest_result = clf.predict(Test_data)\r\nprint(\"training time: \", time()-t1,\" s\")\r\n\r\n\r\n\r\n\r\ndef plot_confusion_matrix(y_true, y_pred, \r\n normalize=False,\r\n title=None,\r\n cmap=plt.cm.Blues):\r\n \"\"\"\r\n This function prints and plots the confusion matrix.\r\n Normalization can be applied by setting `normalize=True`.\r\n \"\"\"\r\n if not title:\r\n if normalize:\r\n title = 'Normalized confusion matrix'\r\n else:\r\n title = 'Confusion matrix, without normalization'\r\n\r\n # Compute confusion matrix\r\n cm = confusion_matrix(y_true, y_pred)\r\n # Only use the labels that appear in the data\r\n\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n print(cm)\r\n\r\n fig, ax = plt.subplots()\r\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\r\n ax.figure.colorbar(im, ax=ax)\r\n # We want to show all ticks...\r\n ax.set(xticks=np.arange(cm.shape[1]),\r\n yticks=np.arange(cm.shape[0]),\r\n # ... and label them with the respective list entries\r\n title=title,\r\n ylabel='True label',\r\n xlabel='Predicted label')\r\n\r\n # Rotate the tick labels and set their alignment.\r\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\r\n rotation_mode=\"anchor\")\r\n\r\n # Loop over data dimensions and create text annotations.\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i in range(cm.shape[0]):\r\n for j in range(cm.shape[1]):\r\n ax.text(j, i, format(cm[i, j], fmt),\r\n ha=\"center\", va=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n fig.tight_layout()\r\n return ax\r\n\r\n\r\nplot_confusion_matrix(Test_label, test_result, normalize=True)\r\nplt.show()\r\n\r\nprint(accuracy_score(Test_label, test_result, normalize=True))", "sub_path": "A5/Q5/Q5_2.py", "file_name": "Q5_2.py", "file_ext": "py", "file_size_in_byte": 2900, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 24, "usage_type": "name"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 25, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 36, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 52, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "567809017", "text": "import datetime\r\nimport json\r\nimport re\r\n\r\n# Directory where we write our geojson-data\r\ndataDir = '/home//mysite/static/gps/'\r\n\r\n# Number of points in curves with recent history.\r\n# The number of points should match the update frequency of your GPS logger.\r\n# In my case, I use an app that logs approximately every 30 seconds, so this\r\n# would be about 20 minutes\r\nhistoryPoints = 40\r\n\r\ndef findIndex(lst, key, value):\r\n \"\"\" Finds the dictionary item in list where dict['properties']['key'] match the\r\n provided value. Used to find the geojson object with matching ID\r\n\r\n Cortesy of\r\n http://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value\r\n \"\"\"\r\n\r\n for i, dic in enumerate(lst):\r\n if dic['properties'][key] == value:\r\n return i\r\n return -1\r\n\r\ndef readGeoJson( filename, id):\r\n \"\"\" Reads GeoJson with featureCollection from file, finds the matching ID within\r\n that collection and returns both the (geo)JSON object and the index to said ID\r\n \"\"\"\r\n\r\n with open(filename) as data_file:\r\n gjdata = json.load(data_file)\r\n\r\n idx = -1\r\n # Find index of feature matching ID\r\n idx = findIndex( gjdata['features'], 'id', id)\r\n\r\n return (gjdata, idx)\r\n\r\ndef emptyGeoJson( filename):\r\n \"\"\"Removes data from GeoJSON file; writes an empty featureCollection\r\n \"\"\"\r\n\r\n filename = dataDir + filename\r\n with open(filename) as data_file:\r\n gjdata = json.load(data_file)\r\n\r\n gjdata['features'] = []\r\n\r\n with open(filename, \"w\") as outfile:\r\n json.dump(gjdata, outfile)\r\n\r\n\r\ndef loggGps(lat, lon, name):\r\n \"\"\"Main function. Basic sanity check of lat, lon (numeric, within\r\n geophysical possible range) and name (alphanumeric characters only)\r\n\r\n Valid lat,lon values are logged to appropriate GeoJSON\r\n files, with file names and ID determined by name parameter. We keep separate\r\n files for the last valid data point and the track of newest 'historyPoints'\r\n coordinates.\r\n\r\n Also loggs any requests, including invalid lat-lon pairs, to file\r\n \"\"\"\r\n\r\n loggfil = dataDir + 'gpslogg.txt' # Log file\r\n\r\n # File names of FeatureCollections containing ALL valid data\r\n gpspunkt = dataDir + 'gpspunkt.geojson' # last valid data point\r\n gpskurve = dataDir + 'gpskurve.geojson' # curve with newest data points\r\n\r\n # This is javascript-friendly formatted date string\r\n tid = datetime.datetime.now().strftime(\"%a %b %d %Y %H:%M:%S\") + ' GMT+0000'\r\n\r\n # Logg all incoming requests to file\r\n with open(loggfil ,'a') as outfile:\r\n outfile.write(tid + \"\\t\" + str(lon)+ \"\\t\" + str(lat)+ \"\\t\" + name + \"\\n\")\r\n\r\n # Sanity check\r\n if not name or not lat or not lon:\r\n return \"NOT OK - one or more parameters missing!\"\r\n try:\r\n lon = float(str(lon))\r\n lat = float(str(lat))\r\n except ValueError:\r\n return \"lon, lat not recognized as numeric values\"\r\n\r\n # Sanity check of lat, lon values\r\n if not -90 < lat < 90:\r\n return \"latitude outside accepted range\"\r\n if not -180 < lon < 180:\r\n return \"longitude outside accepted range\"\r\n\r\n # Stripping \"name\" for anything not alphanumeric!\r\n name2 = re.sub( '\\W+', '', name)\r\n if name2 != name:\r\n return \"Non alphanumeric characters not accepted in name!\"\r\n\r\n # Template for GeoJson feature\r\n pointdata = {\r\n \"type\": \"Feature\",\r\n \"geometry\": {\r\n \"type\": \"Point\",\r\n \"coordinates\": [float(str(lon)), float(str(lat))]\r\n },\r\n \"properties\": {\r\n \"id\": str(name),\r\n \"time\" : tid\r\n }\r\n }\r\n\r\n # (over)writing single feature to file determined by name parameter\r\n with open(dataDir + name + '.geojson' ,'w') as outfile:\r\n json.dump(pointdata, outfile)\r\n\r\n # Adding point to featureCollection of points\r\n # If there exist a feature with correct ID in this collection we replace it\r\n # If not we append to it.\r\n gjdata, idx = readGeoJson( gpspunkt, name )\r\n if idx >= 0:\r\n gjdata['features'][idx] = pointdata\r\n\r\n else:\r\n gjdata['features'].append( pointdata)\r\n\r\n with open(gpspunkt, \"w\") as outfile:\r\n json.dump(gjdata, outfile)\r\n\r\n # Appending new point to the LineString-feature found in featureCollection\r\n # of LineString's If no matching ID is found in collection we will append\r\n # a new LineString-feature to it.\r\n gjdata, idx = readGeoJson( gpskurve, name)\r\n if idx >= 0:\r\n gjdata['features'][idx]['geometry']['coordinates'].append(\r\n [float(str(lon)), float(str(lat))]\r\n )\r\n\r\n # Removing ancient history\r\n gjdata['features'][idx]['geometry']['coordinates'] = \\\r\n gjdata['features'][idx]['geometry']['coordinates'][-historyPoints:]\r\n\r\n # Updating timestamp\r\n gjdata['features'][idx]['properties']['time'] = tid\r\n\r\n newCurve = gjdata['features'][idx]\r\n\r\n else:\r\n # Creating a new lineString feature.\r\n newCurve = pointdata\r\n newCurve['geometry']['type'] = \"LineString\"\r\n pos = newCurve['geometry']['coordinates']\r\n # To have a valid lineString we repeat coordinates\r\n newCurve['geometry']['coordinates'] = [ pos, pos]\r\n gjdata['features'].append( newCurve)\r\n\r\n with open(gpskurve, \"w\") as outfile:\r\n json.dump(gjdata, outfile)\r\n\r\n # (over)writes track with recent history to file whose name is derived\r\n # from name parameter\r\n newCurve['geometry']['coordinates'] = \\\r\n newCurve['geometry']['coordinates'][-historyPoints:]\r\n with open( dataDir + name + '_kurve.geojson' ,'w') as outfile:\r\n json.dump(newCurve, outfile)\r\n\r\n # Return to caller.\r\n return( 'ok' )\r\n\r\n\r\nif __name__==\"__main__\":\r\n loggGps('63.5', '11.0', 'konsoll2')\r\n # loggGps('19.9', '5.5', 'test')\r\n\r\n# dataDir = 'Directory where we write our geojson-data'\r\n# emptyGeoJson( dataDir + 'gpspunkt.geojson' )\r\n# emptyGeoJson( dataDir + 'gpskurve.geojson' )\r\n", "sub_path": "loggGps.py", "file_name": "loggGps.py", "file_ext": "py", "file_size_in_byte": 6103, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 33, "usage_type": "call"}, {"api_name": "json.load", "line_number": 47, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 96, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 115, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 128, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 158, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 165, "usage_type": "call"}]} +{"seq_id": "541278571", "text": "\"\"\"Model predict.\"\"\"# coding=utf-8\n#\n# /************************************************************************************\n# ***\n# *** Copyright Dell 2021, All Rights Reserved.\n# ***\n# *** File Author: Dell, 2021年 02月 27日 星期六 17:25:55 CST\n# ***\n# ************************************************************************************/\n#\nimport argparse\nimport glob\nimport os\nimport pdb\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom data import get_transform\nfrom model import get_model, model_device\n\ndef normal_predict(d):\n ma = torch.max(d)\n mi = torch.min(d)\n\n dn = (d-mi)/(ma - mi + 1e-12)\n\n return dn\n\nif __name__ == \"__main__\":\n \"\"\"Predict.\"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--checkpoint', type=str, default=\"models/ImageMatting.pth\", help=\"checkpint file\")\n parser.add_argument('--input', type=str, default=\"dataset/predict/*.png\", help=\"input image\")\n parser.add_argument('--output', type=str, default=\"output\", help=\"output folder\")\n\n args = parser.parse_args()\n\n # Create directory to store weights\n if not os.path.exists(args.output):\n os.makedirs(args.output)\n\n model = get_model(args.checkpoint)\n device = model_device()\n model.eval()\n\n totensor = get_transform(train=False)\n toimage = transforms.ToPILImage()\n\n image_filenames = sorted(glob.glob(args.input))\n progress_bar = tqdm(total = len(image_filenames))\n\n for index, filename in enumerate(image_filenames):\n progress_bar.update(1)\n\n image = Image.open(filename).convert(\"RGB\")\n input_image = image.resize((320, 320))\n input_tensor = totensor(input_image).unsqueeze(0).to(device)\n\n with torch.no_grad():\n output_tensor = model(input_tensor)\n\n output_tensor = output_tensor[:,0,:,:]\n output_tensor = normal_predict(output_tensor)\n\n output_image = toimage(output_tensor.cpu())\n output_image = output_image.resize((image.width, image.height))\n\n output_image.save(\"{}/{}\".format(args.output, os.path.basename(filename)))\n", "sub_path": "project/predict.py", "file_name": "predict.py", "file_ext": "py", "file_size_in_byte": 2140, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.max", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.min", "line_number": 24, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 42, "usage_type": "call"}, {"api_name": "model.get_model", "line_number": 44, "usage_type": "call"}, {"api_name": "model.model_device", "line_number": 45, "usage_type": "call"}, {"api_name": "model.eval", "line_number": 46, "usage_type": "call"}, {"api_name": "data.get_transform", "line_number": 48, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToPILImage", "line_number": 49, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 49, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 51, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 52, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 57, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}]} +{"seq_id": "32962345", "text": "import logging\nimport numpy as np\nimport pickle\nfrom pathlib import Path\nfrom classes.enums.SmoothingType import SmoothingType\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.svm import SVC\nfrom os import makedirs\nfrom os.path import dirname\nimport settings as s\n\nlogger = logging.getLogger(__name__)\n\n\nclass SVMClassifier():\n model = None\n\n def __init__(self, modelName, experimentBase, modelClasses, numInstances):\n self.modelName = modelName\n self.experimentBase = experimentBase\n self.modelClasses = modelClasses\n self.numInstances = numInstances\n self.modelClassesReverted = {value: key for key, value in self.modelClasses.items()}\n\n def train(self, features, featureData, targets, targetData):\n logger.info(f\"Beggining training {self.modelName} model\")\n self.model = SVC(C=100,\n kernel='rbf',\n degree=3,\n gamma=5,\n coef0=1,\n shrinking=True,\n tol=0.001,\n probability=True,\n cache_size=2000,\n class_weight=None,\n verbose=False,\n max_iter=-1,\n decision_function_shape='ovo',\n random_state=None)\n X_train, X_test, y_train, y_test = train_test_split(featureData, targetData, test_size=0.20)\n self.model.fit(X_train, y_train)\n y_pred = self.model.predict(X_test)\n logger.info(confusion_matrix(y_test, y_pred))\n logger.info(classification_report(y_test, y_pred))\n self.saveModel()\n logger.info(f\"End training {self.modelName} model\")\n\n def predict(self, vector):\n return self.model.predict(vector)\n\n def predictProbability(self, vector, smoothingType):\n probabilities = self.model.predict_proba(vector)[0]\n logger.debug(self.model.classes_)\n logger.debug(self.modelClasses)\n logger.debug(self.modelClassesReverted)\n assert len(self.modelClasses) == len(probabilities), \"Error in class definition, its doesnt fit the trained model\"\n logger.debug(f\"my proba {probabilities}\")\n smoothedProbability = 0\n classification = {}\n for i, probability in enumerate(list(probabilities), 0):\n if SmoothingType.PROBABILITY.value:\n smoothedProbability = probability\n elif SmoothingType.APRIORY_PROBABILITY.value:\n if(self.modelName != \"Thing\"):\n smoothedProbability = probability * (self.numInstancesAllModels / self.numInstances)\n elif SmoothingType.TARGET_TYPES_NUMBER.value:\n smoothedProbability = (probability - (1 / len(self.modelClasses))) / (1 - (1 / len(self.modelClasses)))\n classification[self.modelClassesReverted[i]] = smoothedProbability\n return classification\n\n def saveModel(self):\n \"\"\"\n saves the trained model serialisation for later usage\n \"\"\"\n modelDataFile = Path(str(s.modelsDir) + \"/\" + self.experimentBase.name, self.modelName).with_suffix(\".pickle\")\n makedirs(dirname(modelDataFile), exist_ok=True)\n with open(modelDataFile, \"wb+\") as f:\n pickle.dump(self.model, f)\n\n def loadModel(self):\n \"\"\"\n loads the model from pickle file\n \"\"\"\n modelDataFile = Path(str(s.modelsDir) + \"/\" + self.experimentBase.name, self.modelName).with_suffix(\".pickle\")\n with open(modelDataFile, \"rb+\") as f:\n self.model = pickle.load(f)\n logger.info(f\"Model {self.modelName} - {self.experimentBase.name} has been loaded\")\n", "sub_path": "classes/SVMClassifier.py", "file_name": "SVMClassifier.py", "file_ext": "py", "file_size_in_byte": 3817, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 46, "usage_type": "call"}, {"api_name": "classes.enums.SmoothingType.SmoothingType.PROBABILITY", "line_number": 63, "usage_type": "attribute"}, {"api_name": "classes.enums.SmoothingType.SmoothingType", "line_number": 63, "usage_type": "name"}, {"api_name": "classes.enums.SmoothingType.SmoothingType.APRIORY_PROBABILITY", "line_number": 65, "usage_type": "attribute"}, {"api_name": "classes.enums.SmoothingType.SmoothingType", "line_number": 65, "usage_type": "name"}, {"api_name": "classes.enums.SmoothingType.SmoothingType.TARGET_TYPES_NUMBER", "line_number": 68, "usage_type": "attribute"}, {"api_name": "classes.enums.SmoothingType.SmoothingType", "line_number": 68, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 77, "usage_type": "call"}, {"api_name": "settings.modelsDir", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 78, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 80, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 86, "usage_type": "call"}, {"api_name": "settings.modelsDir", "line_number": 86, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 88, "usage_type": "call"}]} +{"seq_id": "441318688", "text": "import pandas as pd\nimport gzip\nfrom flatten_json import flatten\nimport json\nimport re\nimport sys\nfrom monitoring.time_it import timing\n\n\ndef flatton_json_data(filename):\n \n def unzip_and_fix_json(filename):\n with gzip.GzipFile(filename, \"r\") as f:\n data = f.read()\n data = data.decode('UTF-8')\n data = fix_json(data)\n data = json.loads(data)\n return data\n\n \n def flatten_json_file_into_df(data):\n dict_flattened = (flatten(record, '.') for record in data)\n df = pd.DataFrame(dict_flattened)\n return df\n\n \n def timestamp_converter(df):\n timestamp_cols = [col for col in df.columns if 'timestamp' in col]\n while len(timestamp_cols) != 0:\n element = timestamp_cols.pop()\n df[element] = pd.to_datetime(df[element], unit='ms')\n df[element] = df[element].astype('datetime64[s]')\n return df\n\n \n def fix_json(broken):\n parts = []\n start = 0\n try:\n idx = broken.index('}{', start)\n while idx != -1:\n parts.append(broken[start:idx + 1])\n start = idx + 1\n idx = broken.index('}{', start)\n except ValueError:\n pass\n parts.append(broken[start:])\n return ''.join(['[',','.join(map(lambda s: re.sub(r\"(? '\n if len(sys.argv) < 3 or len(sys.argv) > 4:\n print(usage, file=sys.stderr)\n sys.exit(1)\n validate = False\n off = 1\n if sys.argv[1].startswith('--'):\n off += 1\n if sys.argv[1] == '--validate':\n validate = True\n else:\n print(usage, file=sys.stderr)\n sys.exit(2)\n print('Loading...')\n with open(sys.argv[off], mode='r', encoding='utf-8') as inf:\n data = inf.read()\n print('Processing...')\n fixed = fix_json(data)\n\n with open(sys.argv[off + 1], mode='w', encoding='utf-8') as outf:\n outf.write(fixed)\n if validate:\n print('Validating...')\n with open(sys.argv[off + 1], mode='r', encoding='utf-8') as valf:\n json.load(valf)\n print('Validation successful')\n\n data = unzip_and_fix_json(filename)\n df = flatten_json_file_into_df(data)\n df = timestamp_converter(df)\n return df\n", "sub_path": "code/data_extraction/flatten_json_data.py", "file_name": "flatten_json_data.py", "file_ext": "py", "file_size_in_byte": 2552, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "gzip.GzipFile", "line_number": 13, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "flatten_json.flatten", "line_number": 22, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 31, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 48, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 52, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 53, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 54, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 57, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 59, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 62, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 63, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 65, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 74, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "541563390", "text": "from __future__ import absolute_import, unicode_literals\n\nimport os\nimport json\nimport cgi\n\nfrom six.moves.urllib_parse import urlparse\n\n\ndef load_test_data(filename):\n path = os.path.dirname(os.path.abspath(__file__))\n full_path = os.path.join(path, 'test_data', filename)\n with open(full_path) as f:\n return json.load(f)\n\n\ndef assert_urls_match(url_a, url_b):\n url_a = urlparse(url_a)\n url_b = urlparse(url_b)\n\n assert url_a.scheme == url_b.scheme\n assert url_a.netloc == url_b.netloc\n assert url_a.path == url_b.path\n assert cgi.parse_qs(url_a.query) == cgi.parse_qs(url_b.query)\n", "sub_path": "src/tests/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 617, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 14, "usage_type": "call"}, {"api_name": "six.moves.urllib_parse.urlparse", "line_number": 18, "usage_type": "call"}, {"api_name": "six.moves.urllib_parse.urlparse", "line_number": 19, "usage_type": "call"}, {"api_name": "cgi.parse_qs", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "445928445", "text": "import json\nimport requests\nfrom celery.result import AsyncResult\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom data_construction.for_views.StartInstall.function_start_install import request_to_start_install\nfrom data_construction.for_views.pure_functions_history import updateDict, to_start_end_day\nfrom services_main_server.ldap import find_computer_in_ad, create_ps1_script_for_client\nfrom data_construction.models import LogsInstallationSoft, Soft\nfrom django.utils import timezone\nfrom django.shortcuts import render\n\n\ndef index(request):\n return render(request, 'index.html', {})\n\n\n# {data: \"2020-04-18\"}\n# Выводим список задач запущеных в определенную дату\nclass History(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n all_data = LogsInstallationSoft.objects.filter(date_time__range=(to_start_end_day(request.data['data'])))\n list_startnumber = all_data.values('startnumber').distinct()\n\n list_a = []\n for num in range(len(list_startnumber)):\n obj = all_data.filter(startnumber=list_startnumber[num]['startnumber']).values(\n 'startnumber', 'computer_name', 'events_id', 'date_time')\n list_a.append(obj[0])\n\n return Response(dict(data=[updateDict(list_a[i]) for i in range(len(list_a))]))\n\n\n# Детальная информация об одной установке\n# {\n# \"data\": 255853\n# }\nclass HistoryDetail(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n all_data = LogsInstallationSoft.objects.filter(startnumber=request.data['data']).values(\n 'date_time',\n 'computer_name', \n 'program_id_id',\n 'events_id',\n 'result_work'\n )\n return Response(dict(data=[updateDict(obj) for obj in all_data]))\n\n\n\n\nclass ShowProgrammList(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request):\n\n import json\n all_worked_data = Soft.objects.all()\n data_from_db = json.loads(json.dumps(dict(data=list(all_worked_data.values('id', 'short_program_name', 'soft_display_name')))))\n\n return Response(data_from_db)\n\n\n\n\n# Example request to StartInstall\n# {\n# \"program_name\": [\"notepad\"],\n# \"program_id\": [1],\n# \"DistinguishedName\": [\n# \"CN=COMP3,OU=comps,DC=npr,DC=nornick,DC=ru\"\n# ],\n# \"methodInputnamePc\": false,\n# \"computer_name\": [\"COMP3\"]\n# }\nclass StartInstall(APIView):\n \"\"\"отправляем запрос со списком ПК и софта на functional_server\"\"\"\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n # записываем событие в таблицу LogsInstallationSoft\n id_install_array = []\n for comp_name in request.data[\"computer_name\"]:\n id_install = LogsInstallationSoft.objects.last().startnumber + 1\n id_install_array.append(id_install)\n for prog_id in request.data[\"program_id\"]:\n LogsInstallationSoft.objects.create(date_time=timezone.now(),\n startnumber=id_install,\n computer_name=comp_name,\n program_id=Soft.objects.get(pk=prog_id),\n events_id=6,\n result_work=False)\n if request.data[\"methodInputnamePc\"]:\n request.data[\"computer_name\"] = check_computer_name_list_in_ad(request.data[\"computer_name\"])\n request.data[\"idInstall\"] = id_install_array\n\n create_ps1_script_for_client(request.data)\n\n object_for_start_install = create_object_to_insert_functional_server(request.data)\n\n return Response(request_to_start_install(object_for_start_install))\n\n\n# Example request to create_object_to_insert_functional_server\n# {\n# \"program_name\": [\"notepad\"],\n# \"program_id\": [1],\n# \"DistinguishedName\": [\n# \"CN=COMP3,OU=comps,DC=npr,DC=nornick,DC=ru\", \"CN=COMP2,OU=comps,DC=npr,DC=nornick,DC=ru\"\n# ],\n# \"methodInputnamePc\": false,\n# \"computer_name\": [\"COMP3\", \"COMP2\"],\n# \"idInstall\": 1\n# }\ndef create_object_to_insert_functional_server(data):\n \"\"\"Формируем словарь для запроса на сервер functional-server\"\"\"\n\n data_list = [dict(data=[dict(\n program_name=data[\"program_name\"][i],\n events_id=1,\n program_id=data[\"program_id\"][i]\n ) for i in range(len(data[\"program_id\"]))],\n id_install=data[\"idInstall\"][index],\n result_work=False,\n computer_name=data[\"computer_name\"][index],\n DistinguishedName=data[\"distinguishedName\"][index]\n ) for index in range(len(data[\"computer_name\"]))]\n return dict(data=data_list,\n DistinguishedName=data[\"distinguishedName\"])\n \n\ndef check_computer_name_list_in_ad(computr_name_list):\n array = []\n for computer_name in computr_name_list:\n if find_computer_in_ad(computer_name):\n array.append(computer_name)\n return array\n", "sub_path": "pm_main_server/data_construction/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5189, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.shortcuts.render", "line_number": 16, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 21, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 22, "usage_type": "name"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "data_construction.models.LogsInstallationSoft", "line_number": 25, "usage_type": "name"}, {"api_name": "data_construction.for_views.pure_functions_history.to_start_end_day", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 34, "usage_type": "call"}, {"api_name": "data_construction.for_views.pure_functions_history.updateDict", "line_number": 34, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 41, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 42, "usage_type": "name"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects.filter", "line_number": 45, "usage_type": "call"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects", "line_number": 45, "usage_type": "attribute"}, {"api_name": "data_construction.models.LogsInstallationSoft", "line_number": 45, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "data_construction.for_views.pure_functions_history.updateDict", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 57, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 58, "usage_type": "name"}, {"api_name": "data_construction.models.Soft.objects.all", "line_number": 63, "usage_type": "call"}, {"api_name": "data_construction.models.Soft.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "data_construction.models.Soft", "line_number": 63, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 64, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 64, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 81, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 83, "usage_type": "name"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects.last", "line_number": 89, "usage_type": "call"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects", "line_number": 89, "usage_type": "attribute"}, {"api_name": "data_construction.models.LogsInstallationSoft", "line_number": 89, "usage_type": "name"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects.create", "line_number": 92, "usage_type": "call"}, {"api_name": "data_construction.models.LogsInstallationSoft.objects", "line_number": 92, "usage_type": "attribute"}, {"api_name": "data_construction.models.LogsInstallationSoft", "line_number": 92, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 92, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 92, "usage_type": "name"}, {"api_name": "data_construction.models.Soft.objects.get", "line_number": 95, "usage_type": "call"}, {"api_name": "data_construction.models.Soft.objects", "line_number": 95, "usage_type": "attribute"}, {"api_name": "data_construction.models.Soft", "line_number": 95, "usage_type": "name"}, {"api_name": "services_main_server.ldap.create_ps1_script_for_client", "line_number": 102, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 106, "usage_type": "call"}, {"api_name": "data_construction.for_views.StartInstall.function_start_install.request_to_start_install", "line_number": 106, "usage_type": "call"}, {"api_name": "services_main_server.ldap.find_computer_in_ad", "line_number": 140, "usage_type": "call"}]} +{"seq_id": "644765064", "text": "from pdf2image import convert_from_path\nfrom docx import Document\nfrom docx.shared import Inches\nfrom services import parte, parteAte\nimport os\nimport comtypes.client\n\nfrom pdf2image.exceptions import (\n PDFInfoNotInstalledError,\n PDFPageCountError,\n PDFSyntaxError\n)\n\ndef pdf_to_images(path, file):\n\tabs_path = os.path.join(path, file)\n\tpoppler_abs_path = os.path.abspath(os.path.join('poppler-0.68.0', 'bin'))\n\timages = convert_from_path(abs_path, poppler_path = poppler_abs_path)\n\tname = parteAte(file, -1, '.')\n\tfor i, image in enumerate(images):\n\t\ti+=1\n\t\tfname = name + str(i) + \".png\"\n\t\tfpath = os.path.join(path, fname)\n\t\timage.save(fpath, \"PNG\")\n\ndef arquivosParaImagem(path_to_files):\n\tfor root, dir_names, file_names in os.walk(path_to_files):\n\t\tif len(file_names) == 0:\n\t\t\tcontinue\n\n\t\tprint(root)\n\t\tfor file in file_names:\n\t\t\tif \"pdf\" in file:\n\t\t\t\tprint(file)\n\t\t\t\tpdf_to_images(root, file)\n\n\t\tprint('==================')\n\ndef gerar_documento(path_to_files, file_name, model_file = ''):\n\tlevel_root = path_to_files.count(\"\\\\\")\n\n\tdocument = ''\n\tif model_file:\n\t\tdocument = Document(model_file)\n\telse:\n\t\tdocument = Document()\n\n\tfor root, dir_names, file_names in os.walk(path_to_files):\n\t\tlevel_path = root.count(\"\\\\\")\n\t\tlevel = level_path - level_root\n\t\tlevel +=1\n\t\t# header = parte(root,-1, \"\\\\\")\n\t\t# document.add_heading(header, level = level)\n\n\t\tif len(file_names) == 0:\n\t\t\tcontinue\n\t\t# level += 1\n\t\tfor file in file_names:\n\t\t\tif \"pdf\" in file:\n\t\t\t\t f_name = parteAte(file, -1, '.')\n\t\t\t\t document.add_heading(f_name)\n\t\t\t\t #document.add_page_break()\n\t\t\tif \"png\" in file:\n\t\t\t\t abs_path = os.path.join(root, file)\n\t\t\t\t document.add_picture(abs_path,width=Inches(7))\n\tfile_name = file_name + '.docx'\n\tabs_file = os.path.join(path_to_files, file_name)\n\tdocument.save(abs_file)\n\n\ndef word_to_pdf(path, file_name):\n\tword_file = file_name + '.docx'\n\tpdf_file = file_name + '.pdf'\n\twdFormatPDF = 17\n\n\tin_file = os.path.join(path, word_file)\n\tout_file = os.path.join(path, pdf_file)\n\n\tword = comtypes.client.CreateObject('Word.Application')\n\tdoc = word.Documents.Open(in_file)\n\tdoc.SaveAs(out_file, FileFormat=wdFormatPDF)\n\tdoc.Close()\n\tword.Quit()\n\n\n#percorreDiretorios()\n# arquivosParaImagem()\n\n# dirs = [ \"DOC01\",\"DOC02\",\"DOC03\",\"DOC04\", \"DOC05\", \"DOC06\", \"DOC07\", \"DOC08\", \"DOC09\", \"DOC10\", \"DOC11\", \"DOC12\", \"DOC13\"]\n# path_base = os.getcwd()\n# for dir_path in dirs:\n# \tpath = \"C:\\\\Users\\\\Lucas Salvador\\\\Desktop\\\\200715-LUCAS-RODAR-CODIGO\\\\\" + dir_path\n# \tprint(path)\n# \tgerar_documento(path, dir_path)\n# \tword_to_pdf(path_base, dir_path)\n# \tprint(\"====\")", "sub_path": "files.py", "file_name": "files.py", "file_ext": "py", "file_size_in_byte": 2563, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "pdf2image.convert_from_path", "line_number": 17, "usage_type": "call"}, {"api_name": "services.parteAte", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 26, "usage_type": "call"}, {"api_name": "docx.Document", "line_number": 43, "usage_type": "call"}, {"api_name": "docx.Document", "line_number": 45, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 47, "usage_type": "call"}, {"api_name": "services.parteAte", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "docx.shared.Inches", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "comtypes.client.client.CreateObject", "line_number": 78, "usage_type": "call"}, {"api_name": "comtypes.client.client", "line_number": 78, "usage_type": "attribute"}, {"api_name": "comtypes.client", "line_number": 78, "usage_type": "name"}]} +{"seq_id": "226853504", "text": "from flaskapp import app\nfrom flask import request, redirect, url_for, render_template, flash, make_response\nimport requests\nimport json\nimport binascii\nimport bitsv\nfrom flaskapp.bip39mnemonic import Bip39Mnemonic\nimport os\n# ファイル名をチェックする関数\nfrom werkzeug.utils import secure_filename\nimport polyglot # pip3 install polyglot-bitcoin\nimport requests\nimport json\nimport datetime\nimport time\n\n# import logging\n# logging.basicConfig(filename='example.log',level=logging.DEBUG)\n# logger = logging.getLogger(__name__)\n\n@app.route('/')\ndef index():\n #logger.error(\"warn test\")\n app.logger.debug('debug test')\n app.logger.info('info failed to log in')\n html = render_template('index.html', title=\"Home\")\n return html\n\n@app.route('/newlayout')\ndef newlayout():\n html = render_template('newlayout.html', title=\"HelloaaTitle\")\n return html\n\n@app.route('/download', defaults={'qtxid': \"\"}, methods=[\"GET\", \"POST\"])\n@app.route(\"/download/\", methods=[\"GET\", \"POST\"])\ndef download(qtxid=''):\n try:\n print(request.method)\n if request.method == \"GET\":\n html = render_template('download.html', title=\"download\", transaction=qtxid)\n return html\n elif request.method == \"POST\":\n txid = request.form[\"transaction\"]\n url = \"https://api.whatsonchain.com/v1/bsv/test/tx/hash/\" + txid\n headers = {\"content-type\": \"application/json\"}\n r = requests.get(url, headers=headers)\n data = r.json()\n op_return = data['vout'][0]['scriptPubKey']['opReturn']\n upload_data = data['vout'][0]['scriptPubKey']['asm'].split()[3] ##uploaddata (charactor)\n upload_mimetype = op_return['parts'][1] ##MEDIA_Type: image/png, image/jpeg, text/plain, text/html, text/css, text/javascript, application/pdf, audio/mp3\n upload_charset = op_return['parts'][2] ##ENCODING: binary, utf-8 (Definition polyglot/upload.py)\n upload_filename = op_return['parts'][3] ##filename\n print(\"upload_mimetype: \" + upload_mimetype)\n print(\"upload_charset: \" + upload_charset)\n print(\"upload_filename: \" + upload_filename)\n response = make_response()\n if upload_charset == 'binary': #47f0706cdef805761a975d4af2a418c45580d21d4d653e8410537a3de1b1aa4b\n #print(binascii.hexlify(upload_data))\n response.data = binascii.unhexlify(upload_data)\n elif upload_charset == 'utf-8': #cc80675a9a64db116c004b79d22756d824b16d485990a7dfdf46d4a183b752b2\n response.data = op_return['parts'][0]\n else:\n print('upload_charset' + upload_charset)\n response.data = ''\n downloadFilename = upload_filename\n response.headers[\"Content-Disposition\"] = 'attachment; filename=' + downloadFilename\n response.mimetype = upload_mimetype\n return response\n except Exception as e:\n print(e)\n\n\n@app.route('/mnemonic', methods=[\"GET\", \"POST\"])\ndef mnemonic():\n if request.method == \"GET\":\n html = render_template('mnemonic.html', title=\"mnemonic\")\n return html\n elif request.method == \"POST\":\n mnemonic = request.form[\"mnemonic\"] #app.config['TESTNET_MNEMONIC']\n bip39Mnemonic = Bip39Mnemonic(mnemonic, passphrase=\"\", network=\"test\")\n privateKey = bitsv.Key(bip39Mnemonic.privatekey_wif, network = 'test')\n address = privateKey.address\n balance_satoshi = privateKey.get_balance()\n balance_bsv = float(balance_satoshi) / float(100000000)\n html = render_template(\n 'mnemonic.html',\n privatekey_wif = bip39Mnemonic.privatekey_wif,\n address = address,\n balance_satoshi = balance_satoshi,\n balance_bsv = balance_bsv,\n title=\"mnemonic\")\n return html\n\n@app.route(\"/upload\", methods=[\"GET\"])\ndef upload_file():\n if request.method == 'GET':\n html = render_template('upload.html', title=\"upload\")\n return html\n # リクエストがポストかどうかの判別\n elif request.method == 'POST':\n bsv_mnemonic = request.form[\"mnemonic\"] #app.config['TESTNET_MNEMONIC']\n bip39Mnemonic = Bip39Mnemonic(bsv_mnemonic, passphrase=\"\", network=\"test\")\n \n # ファイルがなかった場合の処理\n if 'file' not in request.files:\n print('ファイルがありません')\n flash('ファイルがありません')\n return redirect(request.url)\n # データの取り出し\n req_file = request.files['file']\n print(req_file)\n stream = req_file.stream\n #img_array = np.asarray(bytearray(stream.read()), dtype=np.uint8)\n\n # ファイル名がなかった時の処理\n if req_file.filename == '':\n flash('ファイルがありません')\n return redirect(request.url)\n # ファイルのチェック\n if req_file and allwed_file(req_file.filename):\n # 危険な文字を削除(サニタイズ処理)\n #filename = secure_filename(req_file.filename)\n # ファイルの保存\n #filepath = os.path.join(app.config['UPLOAD_FOLDER'], req_file.filename)\n #req_file.save(filepath)\n uploader = polyglot.Upload(bip39Mnemonic.privatekey_wif, 'test')\n print(uploader.network)\n req_file_bytearray = bytearray(stream.read())\n print(req_file_bytearray)\n #transaction = uploader.bcat_parts_send_from_binary(req_file_bytearray)\n media_type = uploader.get_media_type_for_file_name(req_file.filename)\n encoding = uploader.get_encoding_for_file_name(req_file.filename)\n print(media_type)\n print(encoding)\n rawtx = uploader.b_create_rawtx_from_binary(req_file_bytearray, media_type, encoding, req_file.filename)\n txid = uploader.send_rawtx(rawtx)\n #transaction = uploader.upload_b(filepath)\n #['5cd293a25ecf0b346ede712ceb716f35f1f78e2c5245852eb8319e353780c615']\n print(txid)\n # アップロード後のページに転送\n html = render_template(\n 'uploaded.html', \n transaction = txid, \n privatekey_wif = bip39Mnemonic.privatekey_wif,\n title=\"mnemonic\")\n\n return html\n else:\n html = render_template(\n 'uploaded.html', \n transaction = \"error\", \n privatekey_wif = bip39Mnemonic.privatekey_wif,\n title=\"mnemonic\")\n return html\n\n# アップロードされる拡張子の制限\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'gif', 'txt'])\n\ndef allwed_file(filename):\n # .があるかどうかのチェックと、拡張子の確認\n # OKなら1、だめなら0\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\nfrom io import StringIO\nimport multiprocessing\n\n@app.route('/note', defaults={'qaddr': \"\"}, methods=[\"GET\", \"POST\"])\n@app.route('/note/', methods=[\"GET\", \"POST\"])\ndef note(qaddr=''):\n try:\n if request.method == \"GET\":\n ## get bsv text list\n html = render_template('note.html', title=\"note\")\n if qaddr == '':\n return html\n network_api = bitsv.network.NetworkAPI(network='test')\n transactions = network_api.get_transactions(qaddr)\n res_get_textdata = []\n startindex = 0\n maxtakecount = 20 ##5 items\n print(len(transactions))\n #処理前の時刻\n t1 = time.time()\n for i in range(startindex, len(transactions), maxtakecount):\n txs = transactions[i:maxtakecount+i]\n print(txs)\n p = multiprocessing.Pool(6) # プロセス数を6に設定\n result = p.map(get_textdata, txs) ## arg must be array\n #print(result)\n for item in result:\n #print(\"item\")\n if item is not None and item.mimetype == \"text/plain\":\n #print(item.data)\n res_get_textdata.append(item.data)\n print(len(res_get_textdata))\n\n \n # 処理後の時刻\n t2 = time.time()\n \n # 経過時間を表示\n elapsed_time = t2-t1\n print(f\"経過時間:{elapsed_time}\")\n # print(res_get_textdata)\n # for item in res_get_textdata:\n # if item is not None:\n # print(item)\n # for i in range(0, len(transactions), maxcount):\n # res_get_textdata = get_transactions_datalist(transactions[i:maxcount+i])\n html = render_template('note.html', title=\"note\", textdata_list=res_get_textdata)\n return html\n elif request.method == \"POST\":\n mnemonic_words = request.form[\"mnemonic_words\"]\n bip39Mnemonic = Bip39Mnemonic(mnemonic_words, passphrase=\"\", network=\"test\")\n privateKey = bitsv.Key(bip39Mnemonic.privatekey_wif, network = 'test')\n transactions = privateKey.get_transactions()\n print(\"transactions\")\n print(transactions)\n\n textdata_list = []\n for txid in reversed(transactions):\n res_get_textdata = get_textdata(txid)\n if res_get_textdata != None and res_get_textdata.mimetype == 'text/plain':\n textdata_list.append(res_get_textdata.data.decode('utf-8'))\n print(\"textdata_list\")\n print(textdata_list)\n\n\n message = request.form[\"message\"]\n bip39Mnemonic = Bip39Mnemonic(mnemonic_words, passphrase=\"\", network=\"test\")\n #stream = StringIO(message)\n #stream = message.stream\n\n encoding = \"utf-8\"\n print(\"bip39Mnemonic.privatekey_wif\")\n print(bip39Mnemonic.privatekey_wif)\n uploader = polyglot.Upload(bip39Mnemonic.privatekey_wif, network='test')\n #req_file_bytearray = bytearray()\n #req_file_bytearray.extend(map(ord, message))\n #req_file_bytearray = bytearray(stream.read())\n #print(req_file_bytearray)\n message_bytes = message.encode(encoding)\n message_bytes_length = len(message_bytes)\n print(message_bytes_length)\n if(message_bytes_length >= 100000): #more less 100kb = 100000bytes.\n html = render_template('note.html', title=\"note\", error_msg=\"text data have to be 100kb or less\")\n return html\n\n req_bytearray = bytearray(message_bytes)\n #transaction = uploader.bcat_parts_send_from_binary(req_file_bytearray)\n media_type = \"text/plain\"\n print(media_type)\n print(encoding)\n file_name = format(datetime.date.today(), '%Y%m%d')\n print(uploader.filter_utxos_for_bcat())\n rawtx = uploader.b_create_rawtx_from_binary(req_bytearray, media_type, encoding, file_name)\n txid = uploader.send_rawtx(rawtx)\n #transaction = uploader.upload_b(filepath)\n #['5cd293a25ecf0b346ede712ceb716f35f1f78e2c5245852eb8319e353780c615']\n print(\"upload txid\")\n print(txid)\n # アップロード後のページに転送\n # html = render_template(\n # 'uploaded.html', \n # transaction = txid, \n # #privatekey_wif = bip39Mnemonic.privatekey_wif,\n # title=\"mnemonic\")\n\n # return html\n if txid == \"\":\n html = render_template('note.html', title=\"note\", error_msg=\"upload failed\")\n return html\n\n html = render_template('note.html', title=\"note\", uploaded_message=message, textdata_list=textdata_list)\n return html\n except Exception as e:\n print(e)\n\nclass ResponseTx:\n\tdef __init__(self, data, mimetype, charset, filename):\n\t\tself.data = data\n\t\tself.mimetype = mimetype\n\t\tself.charset = charset\n\t\tself.filename = filename\n\ndef get_textdata(txid):\n try:\n #print(\"txid\")\n #print(txid)\n #time.sleep(0.1)\n if txid != \"\":\n url = \"https://api.whatsonchain.com/v1/bsv/test/tx/hash/\" + txid\n headers = {\"content-type\": \"application/json\"}\n r = requests.get(url, headers=headers)\n data = r.json()\n op_return = data['vout'][0]['scriptPubKey']['opReturn']\n if op_return is None:\n return None\n hex_upload_data = data['vout'][0]['scriptPubKey']['asm'].split()[3] ##uploaddata (charactor)\n parts = op_return['parts']\n if parts is None:\n return None\n upload_mimetype = parts[1] ##MEDIA_Type: image/png, image/jpeg, text/plain, text/html, text/css, text/javascript, application/pdf, audio/mp3\n upload_charset = parts[2] ##ENCODING: binary, utf-8 (Definition polyglot/upload.py)\n upload_filename = parts[3] ##filename\n # print(\"upload_mimetype: \" + upload_mimetype)\n # print(\"upload_charset: \" + upload_charset)\n # print(\"upload_filename: \" + upload_filename)\n # print(\"hex_upload_data: \" + hex_upload_data)\n # response = make_response()\n if upload_charset == 'binary': #47f0706cdef805761a975d4af2a418c45580d21d4d653e8410537a3de1b1aa4b\n #print(binascii.hexlify(upload_data))\n upload_data = binascii.unhexlify(hex_upload_data)\n elif upload_charset == 'utf-8': #cc80675a9a64db116c004b79d22756d824b16d485990a7dfdf46d4a183b752b2\n upload_data = parts[0]\n else:\n #print('upload_charset' + upload_charset)\n upload_data = ''\n # downloadFilename = upload_filename\n # response.headers[\"Content-Disposition\"] = 'attachment; filename=' + downloadFilename\n # response.mimetype = upload_mimetype\n #print(upload_data)\n # return response]\n return ResponseTx(upload_data, upload_mimetype, upload_charset, upload_filename)\n except Exception as e:\n print(e)\n\n\n\ndef get_transactions_datalist(txids):\n try:\n url = \"https://api.whatsonchain.com/v1/bsv/test/txs\"\n headers = {\"content-type\": \"application/json\"}\n json_data = json.dumps({\"txids\" : [\"2a566f32c51227d56ba9bdebe42d9857aeeb50cff074fc553c0d08bc250e0f7c\"]})\n print(json_data)\n\n r = requests.post(url, json_data, headers=headers)\n data = r.json()\n print(json.dumps(data, indent=4))\n for i in range(len(data)):\n op_return = data[i]['vout'][0]['scriptPubKey']['opReturn']\n upload_data = data[i]['vout'][0]['scriptPubKey']['asm'].split()[3] ##uploaddata (charactor)\n if op_return != None:\n textdata = binascii.unhexlify(upload_data)\n print(textdata)\n # parts = op_return['parts']\n # if parts != None:\n # upload_mimetype = parts[1] ##MEDIA_Type: image/png, image/jpeg, text/plain, text/html, text/css, text/javascript, application/pdf, audio/mp3\n # upload_charset = parts[2] ##ENCODING: binary, utf-8 (Definition polyglot/upload.py)\n # upload_filename = parts[3] ##filename\n # print(\"upload_mimetype: \" + upload_mimetype)\n # print(\"upload_charset: \" + upload_charset)\n # print(\"upload_filename: \" + upload_filename)\n # response = make_response()\n # if upload_charset == 'binary': #47f0706cdef805761a975d4af2a418c45580d21d4d653e8410537a3de1b1aa4b\n # #print(binascii.hexlify(upload_data))\n # response.data = binascii.unhexlify(upload_data)\n # elif upload_charset == 'utf-8': #cc80675a9a64db116c004b79d22756d824b16d485990a7dfdf46d4a183b752b2\n # response.data = op_return['parts'][0]\n # else:\n # print('upload_charset' + upload_charset)\n # response.data = ''\n # downloadFilename = upload_filename\n # response.headers[\"Content-Disposition\"] = 'attachment; filename=' + downloadFilename\n # response.mimetype = upload_mimetype\n # print(response.data)\n return None\n except Exception as e:\n print(e)\n", "sub_path": "flaskapp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 16755, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flaskapp.app.logger.debug", "line_number": 24, "usage_type": "call"}, {"api_name": "flaskapp.app.logger", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flaskapp.app", "line_number": 24, "usage_type": "name"}, {"api_name": "flaskapp.app.logger.info", "line_number": 25, "usage_type": "call"}, {"api_name": "flaskapp.app.logger", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flaskapp.app", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 26, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 21, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 31, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 29, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 29, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 38, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 38, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 39, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 42, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 42, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 56, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 59, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 34, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 34, "usage_type": "name"}, {"api_name": "flaskapp.app.route", "line_number": 35, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 75, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 75, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 78, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 78, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 79, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 79, "usage_type": "name"}, {"api_name": "flaskapp.bip39mnemonic.Bip39Mnemonic", "line_number": 80, "usage_type": "call"}, {"api_name": "bitsv.Key", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 85, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 73, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 96, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 96, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 97, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 100, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 100, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 101, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 101, "usage_type": "name"}, {"api_name": "flaskapp.bip39mnemonic.Bip39Mnemonic", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 105, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 105, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 108, "usage_type": "call"}, {"api_name": "flask.request.url", "line_number": 108, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 108, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 110, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 110, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.request.url", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "polyglot.Upload", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 141, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 149, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 94, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 94, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 171, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 171, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 173, "usage_type": "call"}, {"api_name": "bitsv.network.NetworkAPI", "line_number": 176, "usage_type": "call"}, {"api_name": "bitsv.network", "line_number": 176, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 183, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 187, "usage_type": "call"}, {"api_name": "time.time", "line_number": 199, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 210, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 212, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 212, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 213, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 213, "usage_type": "name"}, {"api_name": "flaskapp.bip39mnemonic.Bip39Mnemonic", "line_number": 214, "usage_type": "call"}, {"api_name": "bitsv.Key", "line_number": 215, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 229, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 229, "usage_type": "name"}, {"api_name": "flaskapp.bip39mnemonic.Bip39Mnemonic", "line_number": 230, "usage_type": "call"}, {"api_name": "polyglot.Upload", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 246, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 254, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 254, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 271, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 274, "usage_type": "call"}, {"api_name": "flaskapp.app.route", "line_number": 167, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 167, "usage_type": "name"}, {"api_name": "flaskapp.app.route", "line_number": 168, "usage_type": "call"}, {"api_name": "flaskapp.app", "line_number": 168, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 294, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 313, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 334, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 337, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 339, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 344, "usage_type": "call"}]} +{"seq_id": "56942311", "text": "import json\r\nimport os.path\r\n\r\nfrom Config.Model.Plugin.Default import Default\r\nfrom Config.Model.Plugin.IPConfig import IPConfig\r\nfrom Config.Model.Plugin.ManualScreenShot import ManualScreenShot\r\nfrom Config.Model.Plugin.NMap import NMap\r\nfrom Config.Model.Plugin.NetScanner import NetScanner\r\nfrom Config.Model.Plugin.NetStat import NetStat\r\nfrom Config.Model.Plugin.PyKeyLogger import PyKeyLogger\r\nfrom Config.Model.Plugin.TShark import TShark\r\n\r\n\r\nclass PluginsController:\r\n def __init__(self, base_dir, config_file_name):\r\n self.base_dir = base_dir\r\n self.config_file_name = config_file_name\r\n self.plugin_names = [directory for directory in os.listdir(os.path.join(base_dir, 'plugins', 'collectors')) if\r\n os.path.isdir(os.path.join(base_dir, 'plugins', 'collectors', directory))]\r\n\r\n self.initialize_and_scaffold_config_files()\r\n\r\n def initialize_and_scaffold_config_files(self):\r\n for plugin_name in self.plugin_names:\r\n if not os.path.isfile(self.plugins_config_file(plugin_name)):\r\n new_file = open(self.plugins_config_file(plugin_name), 'w')\r\n\r\n if plugin_name == 'ipconfig':\r\n data = IPConfig(plugin_name).data\r\n elif plugin_name == 'manualscreenshot':\r\n data = ManualScreenShot(plugin_name).data\r\n elif plugin_name == 'netscanner':\r\n data = NetScanner(plugin_name).data\r\n elif plugin_name == 'netstat':\r\n data = NetStat(plugin_name).data\r\n elif plugin_name == 'nmap':\r\n data = NMap(plugin_name).data\r\n elif plugin_name == 'pykeylogger':\r\n data = PyKeyLogger(plugin_name).data\r\n elif plugin_name == 'tshark':\r\n data = TShark(plugin_name).data\r\n elif plugin_name == 'netscanner':\r\n data = NetScanner(plugin_name).data\r\n else:\r\n data = Default(plugin_name).data\r\n\r\n with open(self.plugins_config_file(plugin_name), 'w') as data_file:\r\n json.dump(data, data_file, sort_keys=True, indent=4, separators=(',', ': '))\r\n\r\n new_file.close()\r\n\r\n def plugins_config_file(self, plugin_name):\r\n return os.path.join(self.base_dir, 'plugins', 'collectors', plugin_name, self.config_file_name)\r\n", "sub_path": "venv/lib/python2.7/site-packages/dss/Config/Controller/PluginController.py", "file_name": "PluginController.py", "file_ext": "py", "file_size_in_byte": 2452, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "name"}, {"api_name": "os.path.path.join", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.path.isdir", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 19, "usage_type": "name"}, {"api_name": "os.path.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 25, "usage_type": "name"}, {"api_name": "Config.Model.Plugin.IPConfig.IPConfig", "line_number": 29, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.ManualScreenShot.ManualScreenShot", "line_number": 31, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.NetScanner.NetScanner", "line_number": 33, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.NetStat.NetStat", "line_number": 35, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.NMap.NMap", "line_number": 37, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.PyKeyLogger.PyKeyLogger", "line_number": 39, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.TShark.TShark", "line_number": 41, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.NetScanner.NetScanner", "line_number": 43, "usage_type": "call"}, {"api_name": "Config.Model.Plugin.Default.Default", "line_number": 45, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 53, "usage_type": "name"}]} +{"seq_id": "175497360", "text": "\"\"\"\nPergunta e calcula a estatisticas de idade das listas_entrevistados\n\nEste codigo é dividido em 4 partes\n1a. parte ler o arquivo json\n2a. parte fazendo novas perguntas\n3a. parte salvando tudono arquivo\n4a. parte calculando e mostrando as estatisticas\n\"\"\"\nimport meuprojeto\nimport statistics\nimport json\nimport sh\n\n\ndef carrega_dados():\n \"\"\"\n Carrega as informaçoes do arquivo json.\n\n Popula a lista lista_entrevisados com instancia da classe.\n Entrevista com os valores que vem do arquivo json.\n \"\"\"\n global lista_entrevistados\n\n def pega_dados(obj):\n \"\"\"\n Cria uma instancia nova de Entrevista.\n\n Usa os dados vindo do json atraves do objeto 'obj'\n para nome, idade e ano_informado\n Retorna a instancia Entrevista()\n \"\"\"\n\n instancia = meuprojeto.Entrevista(\n nome=obj[\"nome\"],\n idade=obj[\"idade\"],\n ano=obj[\"ano\"]\n )\n return instancia\n\n try:\n arquivo_json = open(\"dados.json\", \"r\") # Abre o arquivo no disco\n # Converte em um diconario json ->python\n dados_json = json.load(arquivo_json)\n entrevistas = dados_json['Entrevistas']\n lista_entrevistados = [pega_dados(entrevista)\n for entrevista in entrevistas]\n except Exception as erro:\n print(\"Ocorreu um erro ao carregar o arquivo.\")\n print(f'O erro é: {erro}')\n\n\ndef novos_dados():\n \"\"\"\n Pergunta novos nomes e anos de nascimentos.\n Enquanto o usuarioo digitar 'parar' ao perguntado o nome\n o programa pergunta o ano de nascimento e calcula a idade\n \"\"\"\n\n pode_parar = False\n\n while pode_parar == False:\n entrevistado = meuprojeto.Entrevista()\n if entrevistado.pergunta_nome().lower() == 'parar':\n pode_parar = True\n else:\n try:\n entrevistado.pergunta_idade()\n # x = 1000 / 0\n except ZeroDivisionError:\n print(\"Ocorreu um erro mas a lista foi salva\")\n lista_entrevistados.append(entrevistado)\n except Exception as erro:\n print(\"Ocorreu um erro mas a lista NAO foi salva\")\n print(f'O tipo de erro foi {(type(erro))}')\n print(f'A menssagen foi {erro}')\n else:\n lista_entrevistados.append(entrevistado)\n\n\ndef salvar_dados():\n \"\"\"\n Salva as informaçoes geradas num arquivo json.\n Converte o dicionario Python para JSON e salva os dados da lista\n 'lista_entrevistados\n Cria a lista no formato [{nome=obj.nome, ano=obj.ano_informado, idade=obj.idade}]\n Transforma a lista em um dicionario {\"Entrevistas\":lista}\n \"\"\"\n\n lista_salvar = [\n dict(nome=obj.nome, ano=obj.ano_informado, idade=obj.idade)\n for obj in lista_entrevistados\n\n ]\n dict_salvar = {'Entrevistas': lista_salvar}\n dict_salvar = json.dumps(dict_salvar, indent=4, sort_keys=False)\n try:\n arquivo_json = open(\"dados.json\", \"w\") # Abre o arquivo e limpa\n arquivo_json.write(dict_salvar) # Escreve os dados no arquivo\n arquivo_json.close() # Fecha e salva o arquivo\n except Exception as erro:\n print(\"Ocorreu um erro ao carregar o arquivo.\")\n print(f'O erro é: {erro}')\n\n\ndef calcular_dados():\n \"\"\"\n Calcula as estatisticas de idades>:\n\n 1. Mostra a menor idade calculada\n 2. Mostra a maior idade calculada\n 3. Mostra a media de idades dos adultos\n 4. Mostrar a quantidade de nascimentos por decadas\n\n O que temos: [1970, 1981, 1998, 2002, 1990, 1970 ]\n O que queremos:{1980: 10, 1990: 15, 2000: 5}\n\n 1o passo: converter anos em decadas\n 1985 / 10 = 198,5 int -> 198 * 10 = 1980\n 2o passo: criar uma lista nova(set_decadas) com as decadas sem repetir\n 3o passo: contar as decadas na lista original(lista_decadas) usando a lista nova\n Para cada decada dentro da lista nova(set_decadas)contar qtd vezes\n ela ela apareçe na lista original(lista_decadas)\n\n \"\"\"\n\n menor_idade = min([objeto.idade for objeto in lista_entrevistados])\n maior_idade = max([objeto.idade for objeto in lista_entrevistados])\n\n media_adultos = statistics.median_high([\n objeto.idade for objeto in lista_entrevistados if objeto.idade >= 18])\n\n lista_decadas = [int(objeto.ano_informado / 10) *\n 10 for objeto in lista_entrevistados]\n set_decadas = set(lista_decadas)\n qtd_nascimento = {decada: lista_decadas.count(\n decada) for decada in set_decadas}\n\n print(\"\\nResultados:\")\n print('-------------------------------')\n print(f'Quantidade de Entrevistas: {len(lista_entrevistados )}')\n print(f'Menor idade informada: {(menor_idade)}')\n print(f'Maior idade informada: {(maior_idade)}')\n print(f'Media de idade dos adultos informados: {(media_adultos)}')\n print('\\nNascimento por decadas')\n print('-------------------------------')\n for decada, quantidade in qtd_nascimento.items():\n print(f'{decada}: {quantidade} nascimentos')\n print('\\n\\n')\n resposta_ok = False\n while resposta_ok == False:\n try:\n resposta = input('Deseja mostrar os dados num arquivo ?(s/n')\n resposta = resposta[0].lower()\n if resposta == 's' or resposta == 'n':\n resposta_ok = True\n except:\n continue\n if resposta == 's':\n sh.gedit(\"dados.json\")\n\n\ncarrega_dados()\nnovos_dados()\nsalvar_dados()\ncalcular_dados()\n", "sub_path": "rodarprojeto.py", "file_name": "rodarprojeto.py", "file_ext": "py", "file_size_in_byte": 5498, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "meuprojeto.Entrevista", "line_number": 34, "usage_type": "call"}, {"api_name": "json.load", "line_number": 44, "usage_type": "call"}, {"api_name": "meuprojeto.Entrevista", "line_number": 63, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 96, "usage_type": "call"}, {"api_name": "statistics.median_high", "line_number": 130, "usage_type": "call"}, {"api_name": "sh.gedit", "line_number": 160, "usage_type": "call"}]} +{"seq_id": "307903097", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('academic', '0002_auto_20160417_0305'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='campusdrive',\n name='company_description',\n field=models.CharField(max_length=1000),\n ),\n migrations.AlterField(\n model_name='campusdrive',\n name='drive_on',\n field=models.DateTimeField(default=datetime.datetime(2016, 4, 17, 3, 28, 18, 992373, tzinfo=utc)),\n ),\n ]\n", "sub_path": "academic/migrations/0003_auto_20160417_0328.py", "file_name": "0003_auto_20160417_0328.py", "file_ext": "py", "file_size_in_byte": 697, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "call"}, {"api_name": "django.utils.timezone.utc", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "6431699", "text": "import os\nimport sqlalchemy\nfrom sqlalchemy import desc\nfrom models import db, Contact, Group, groups_contacts\nfrom flask_migrate import Migrate\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n##Setting the place for the db to run\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/emssseeeaoo.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n#Initializing the db (after registering the Models)\ndb.init_app(app)\n#migration engine\nmigrate = Migrate(app, db)\n\ndef no_response():\n no_response = jsonify({\"error\": 400, \"message\":\"no member found\" })\n no_response.status_code = 400\n return no_response\n\ndef getAll(table):\n entries = table.query.all()\n arr = []\n for e in entries:\n entry = e.not_dict()\n arr.append(entry)\n return arr\n\ndef getID(anID, table):\n if anID is not None:\n entry = table.query.get(anID)\n return jsonify({\"data\": entry.to_dict()})\n\n return(no_response())\n\ndef deleteOne(anID, table):\n if id is not None:\n entry = table.query.get(anID)\n arr = []\n arr.append(entry)\n db.session.delete(entry)\n db.session.commit()\n return jsonify({\"deleted\": \"%s\" % arr})\n \n return(no_response())\n\ndef updateGroup(groupID, request):\n if groupID is not None:\n info = request.get_json() or {}\n group = Group.query.get(groupID)\n group.name = info[\"name\"]\n db.session.commit() \n return jsonify({\"status_code\":\"200\",\"data\":group.not_dict()})\n \n return(no_response())\n\ndef updateContact(contactID, request):\n if contactID is not None:\n info = request.get_json() or {} \n contact = Contact.query.get(contactID) \n contact.full_name = info[\"full_name\"] \n contact.email = info[\"email\"] \n contact.address = info[\"address\"] \n contact.phone = info[\"phone\"] \n if info[\"groups\"] is not None:\n for g in info[\"groups\"]:\n group = Group.query.get(g)\n if group is not None:\n contact.groups.append(group)\n else:\n return jsonify(\"error\")\n db.session.commit()\n return jsonify({\"status_code\":\"200\",\"data\":contact.not_dict()})\n\n return(no_response())\n \n\n@app.route('/', methods=['GET'])\ndef default(): \n return(\"TEST\")\n \n@app.route('/groups', methods=['GET'])\ndef allGroups(): \n return jsonify({\"data\": getAll(Group)})\n \n@app.route('/contacts', methods=['GET'])\ndef allContacts(): \n return jsonify({\"data\": getAll(Contact)})\n\n@app.route('/group/', methods=['GET','PUT','DELETE'])\ndef groupID(id): \n if id > 0:\n if request.method == 'GET':\n return(getID(id, Group))\n elif request.method == 'PUT':\n return(updateGroup(id, request))\n elif request.method == 'DELETE':\n return(deleteOne(id, Group))\n else:\n return(\"NOTHING\")\n\n@app.route('/group/add', methods=['POST'])\ndef groupAdd(): \n info = request.get_json() or {}\n group = Group(\n name=info[\"name\"]\n )\n print(info[\"name\"])\n db.session.add(group)\n db.session.commit()\n return jsonify({\"response\":\"ok\"})\n\n@app.route('/contact/', methods=['GET','PUT','DELETE'])\ndef contactID(id): \n if id > 0:\n if request.method == 'GET':\n return(getID(id, Contact))\n elif request.method == 'PUT':\n return(updateContact(id, request))\n elif request.method == 'DELETE':\n return(deleteOne(id, Contact))\n else:\n return(\"NOTHING\")\n\n@app.route('/contact/add', methods=['POST'])\ndef contactAdd(): \n info = request.get_json() or {}\n contact = Contact(\n full_name=info[\"full_name\"],\n email = info[\"email\"],\n address = info[\"address\"],\n phone = info[\"phone\"]\n ) \n if info[\"groups\"] is not None:\n for g in info[\"groups\"]:\n group = Group.query.get(g)\n if group is not None:\n contact.groups.append(group)\n else:\n return jsonify(\"error\")\n \n db.session.add(contact)\n db.session.commit()\n return jsonify({\"response\":\"ok\"})\n \napp.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))", "sub_path": "Project/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 4322, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 10, "usage_type": "call"}, {"api_name": "models.db.init_app", "line_number": 15, "usage_type": "call"}, {"api_name": "models.db", "line_number": 15, "usage_type": "name"}, {"api_name": "flask_migrate.Migrate", "line_number": 17, "usage_type": "call"}, {"api_name": "models.db", "line_number": 17, "usage_type": "argument"}, {"api_name": "flask.jsonify", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 35, "usage_type": "call"}, {"api_name": "models.db.session.delete", "line_number": 44, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 44, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 44, "usage_type": "name"}, {"api_name": "models.db.session.commit", "line_number": 45, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 52, "usage_type": "name"}, {"api_name": "models.Group.query.get", "line_number": 53, "usage_type": "call"}, {"api_name": "models.Group.query", "line_number": 53, "usage_type": "attribute"}, {"api_name": "models.Group", "line_number": 53, "usage_type": "name"}, {"api_name": "models.db.session.commit", "line_number": 55, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 55, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 62, "usage_type": "name"}, {"api_name": "models.Contact.query.get", "line_number": 63, "usage_type": "call"}, {"api_name": "models.Contact.query", "line_number": 63, "usage_type": "attribute"}, {"api_name": "models.Contact", "line_number": 63, "usage_type": "name"}, {"api_name": "models.Group.query.get", "line_number": 70, "usage_type": "call"}, {"api_name": "models.Group.query", "line_number": 70, "usage_type": "attribute"}, {"api_name": "models.Group", "line_number": 70, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 74, "usage_type": "call"}, {"api_name": "models.db.session.commit", "line_number": 75, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 75, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 75, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 87, "usage_type": "call"}, {"api_name": "models.Group", "line_number": 87, "usage_type": "argument"}, {"api_name": "flask.jsonify", "line_number": 91, "usage_type": "call"}, {"api_name": "models.Contact", "line_number": 91, "usage_type": "argument"}, {"api_name": "flask.request.method", "line_number": 96, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 96, "usage_type": "name"}, {"api_name": "models.Group", "line_number": 97, "usage_type": "argument"}, {"api_name": "flask.request.method", "line_number": 98, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 98, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 99, "usage_type": "argument"}, {"api_name": "flask.request.method", "line_number": 100, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 100, "usage_type": "name"}, {"api_name": "models.Group", "line_number": 101, "usage_type": "argument"}, {"api_name": "flask.request.get_json", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 107, "usage_type": "name"}, {"api_name": "models.Group", "line_number": 108, "usage_type": "call"}, {"api_name": "models.db.session.add", "line_number": 112, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 112, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 112, "usage_type": "name"}, {"api_name": "models.db.session.commit", "line_number": 113, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 113, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 113, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 114, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 119, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 119, "usage_type": "name"}, {"api_name": "models.Contact", "line_number": 120, "usage_type": "argument"}, {"api_name": "flask.request.method", "line_number": 121, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 121, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 122, "usage_type": "argument"}, {"api_name": "flask.request.method", "line_number": 123, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 123, "usage_type": "name"}, {"api_name": "models.Contact", "line_number": 124, "usage_type": "argument"}, {"api_name": "flask.request.get_json", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 130, "usage_type": "name"}, {"api_name": "models.Contact", "line_number": 131, "usage_type": "call"}, {"api_name": "models.Group.query.get", "line_number": 139, "usage_type": "call"}, {"api_name": "models.Group.query", "line_number": 139, "usage_type": "attribute"}, {"api_name": "models.Group", "line_number": 139, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 143, "usage_type": "call"}, {"api_name": "models.db.session.add", "line_number": 145, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 145, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 145, "usage_type": "name"}, {"api_name": "models.db.session.commit", "line_number": 146, "usage_type": "call"}, {"api_name": "models.db.session", "line_number": 146, "usage_type": "attribute"}, {"api_name": "models.db", "line_number": 146, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 147, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 149, "usage_type": "call"}]} +{"seq_id": "20054702", "text": "from django.db.models.signals import post_save, pre_save\nfrom django.dispatch import receiver\nfrom uuslug import slugify\n\nfrom products.models import (Variation,\n AttributeType,\n AttributeValue,\n Product,\n Category,\n Currency,\n Thumbnail,\n ProductImage)\nfrom utils import thumbnail_creator\n\n\n# TODO: bu signal içerisinde kar marjı varsa price 'ı update et, yoksa, kar marjını bulup kaydet.\ndef product_post_save_receiver_for_variation(sender, instance, created, *args, **kwargs):\n product = instance\n variations = product.variation_set.all()\n if variations.count() == 0:\n new_var = Variation()\n new_var.product = product\n new_var.title = \"Default\"\n new_var.price = product.price\n # new_var.buying_curreny = Currency.objects.get(name=\"TURK LIRASI\") buna gerek yok.\n new_var.save()\n\n\n# This receiver function creates predefined product attributes for saved product\ndef product_post_save_receiver_for_attributes(sender, instance, *args, **kwargs):\n # print(\"sender:\", sender)\n try:\n valueset = instance.valueset\n except:\n valueset = \"Error\"\n\n print(\"valueset:\", valueset)\n create_featureset(instance=instance, valueset=valueset) # buna valueset 'i nasıl göndereceğiz.?\n\n\n# aşağıdaki fonksiyon çalışıyor aslında iki kez çalışacak bu önce product'ı get_or_create yapacak,\n# create yaptığında çalışıp emty value olarak yaratacak, sonra biz bir daha valuset ile birlikte\n# çağıracağız.\ndef create_featureset(instance=None, valueset=None): # instance içerisinde valuset var ama sıkıntı yaratıyor.\n\n def get_cell_for_field(field_name):\n importer_map = instance.importer_map\n try:\n field_object = importer_map.fields_set.get(product_field=field_name)\n cell_value_index = int(field_object.get_xml_field())\n cell_value = instance.valueset[cell_value_index]\n except:\n cell_value = \"\"\n return cell_value\n\n # featureları al\n product_features = AttributeType.objects.filter(product_type=instance.product_type)\n # eklenenleri al\n assigned_product_features = AttributeType.objects.filter(product=instance)\n # aradaki farka bak : product feature olarak eklenmemiş feature var mı?\n difference = list(set(product_features) - set(assigned_product_features))\n print(len(difference))\n # eğer varsa:\n if len(difference) > 0: # ilkinde eklenmişse sonradan valuseti nasıl ekleyeceğiz.? Update edeceğiz.\n for feature in difference: # burada sadece 1 feature varsa sıkıntı olabilir, non iterable diyordu sanki\n feature.product.add(instance)\n feature.save()\n # sonrasında da boş değer yaratıyoruz. Aslında burada import ederken value olacak\n # o yüzden value empty olmayabilir.\n if valueset is not \"Error\":\n # 1-) get value for the feature\n print(\"get_cell_for_field :\",get_cell_for_field(feature))\n feature_value = get_cell_for_field(feature)\n\n # 2-) create or update Value for the feature\n attribute_value, attr_created = AttributeValue.objects.get_or_create(attribute_type=feature,\n product=instance)\n attribute_value.value = feature_value\n attribute_value.save()\n else:\n AttributeValue.objects.create(attribute_type=feature, product=instance, value=\"\")\n else: # eklenmemiş ürün feature'ı yok o zaman update et\n if valueset is not \"Error\":\n for feature in assigned_product_features:\n print(\"values will be updated for feature:\", feature)\n feature_value = get_cell_for_field(feature)\n # update values\n attribute_value, attr_created = AttributeValue.objects.get_or_create(attribute_type=feature,\n product=instance)\n attribute_value.value = feature_value\n attribute_value.save()\n\n\n# This receiver function creates attribute types for existing products after an attribute created\ndef attribute_type_post_save_receiver(sender, instance, *args, **kwargs):\n # 1 - tüm productlar içerisinde product_type 'ı yeni yaratılan attibute'un product_type'ı aynı olanları süz.\n products = Product.objects.filter(product_type=instance.product_type)\n print(products)\n # 2 - süzülen productlara yeni attribute' u ekle:\n for product in products:\n print(instance)\n assigned_product_features = AttributeType.objects.filter(product=product)\n print(\"assigned product features :%s\" % assigned_product_features)\n if instance not in assigned_product_features:\n instance.product.add(product)\n AttributeValue.objects.create(attribute_type=instance, product=product, value=\"\")\n\n\ndef create_slug(instance, sender, new_slug=None):\n print(instance)\n slug = slugify(instance.title)\n if new_slug is not None:\n slug = new_slug\n qs = sender.objects.filter(slug=slug)\n exists = qs.exists()\n if exists:\n new_slug = \"%s-%s\" % (slug, qs.first().id)\n return create_slug(instance, sender=sender, new_slug=new_slug)\n return slug\n\n\ndef productimage_post_save_receiver_for_thumbnail(sender, instance, created, *args, **kwargs):\n print('sender : ', sender)\n print('instance', instance)\n print('instance.product', instance.product)\n\n if sender and instance.image: # image downloader ile create ediince henüz image set edilmemiş oluyor.\n hd, hd_created = Thumbnail.objects.get_or_create(product=instance.product,\n main_image=instance,\n type='hd')\n sd, sd_created = Thumbnail.objects.get_or_create(product=instance.product,\n main_image=instance,\n type='sd')\n mid, mid_created = Thumbnail.objects.get_or_create(product=instance.product,\n main_image=instance,\n type='medium')\n micro, micro_created = Thumbnail.objects.get_or_create(product=instance.product,\n main_image=instance,\n type='micro')\n\n # hd_max = (width, height)\n hd_max = (900, 1024)\n sd_max = (500, 600)\n mid_max = (250, 300)\n micro_max = (150, 150)\n\n media_path = instance.get_image_path()\n print('mediapath nedir?: ', media_path)\n owner_slug = instance.product.slug\n print('owner slug nedir?: ', owner_slug)\n\n if hd_created:\n thumbnail_creator.create_new_thumb(media_path, hd, owner_slug, hd_max[0], hd_max[1])\n\n if sd_created:\n thumbnail_creator.create_new_thumb(media_path, sd, owner_slug, sd_max[0], sd_max[1])\n\n if mid_created:\n thumbnail_creator.create_new_thumb(media_path, mid, owner_slug, mid_max[0], mid_max[1])\n\n if micro_created:\n thumbnail_creator.create_new_thumb(media_path, micro, owner_slug, micro_max[0], micro_max[1])\n\n # yukarıdaki gibi if 'ler olduğunda sadece ilk resme ilişkin thumnail yaratıyor. Biz tamamı,\n # için thumbnail yaratmak istiyoruz. Ama bu sefer de thumb resme ait mi değil mi bulmamız gerek.\n\n # thumbnail_creator.create_new_thumb(media_path, hd, owner_slug, hd_max[0], hd_max[1])\n # thumbnail_creator.create_new_thumb(media_path, sd, owner_slug, sd_max[0], sd_max[1])\n # thumbnail_creator.create_new_thumb(media_path, mid, owner_slug, mid_max[0], mid_max[1])\n # thumbnail_creator.create_new_thumb(media_path, micro, owner_slug, micro_max[0], micro_max[1])\n\npost_save.connect(productimage_post_save_receiver_for_thumbnail, sender=ProductImage)\npost_save.connect(product_post_save_receiver_for_attributes, sender=Product)\npost_save.connect(product_post_save_receiver_for_variation, sender=Product)\npost_save.connect(attribute_type_post_save_receiver, sender=AttributeType)\n\n\n# TODO : Bunu normal olarak product ve kategori post save olarak yaratamaz mıyız? (mixin vb. yöntemle)\n@receiver(pre_save) # tüm objeler pre_save olmadan çalışıyor...\ndef slug_pre_save_receiver(sender, instance, *args, **kwargs):\n # print(\"pre_save_receiver_çalıştı...\")\n\n list_of_models = ('Product', 'Category')\n # print(\"sender:\", sender.__name__)\n\n if sender.__name__ in list_of_models: # this is the dynamic part you want\n if not instance.slug:\n instance.slug = create_slug(instance, sender)\n else:\n pass\n # print(\"sender list of models içinde değil\")\n\n\n# if sender.__name__ == 'Category':\n# instance.order = instance.id\n\n\n# @receiver(post_save, sender=Category)\n# def category_order_receiver(sender, instance, *args, **kwargs):\n# print(\"post save category çalışıyor mu?\")\n# instance.order = instance.id\n# # instance.save() # bu satır patlatıyor...\n\n\n\n", "sub_path": "app/products/signals.py", "file_name": "signals.py", "file_ext": "py", "file_size_in_byte": 9569, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "products.models.Variation", "line_number": 21, "usage_type": "call"}, {"api_name": "products.models.AttributeType.objects.filter", "line_number": 57, "usage_type": "call"}, {"api_name": "products.models.AttributeType.objects", "line_number": 57, "usage_type": "attribute"}, {"api_name": "products.models.AttributeType", "line_number": 57, "usage_type": "name"}, {"api_name": "products.models.AttributeType.objects.filter", "line_number": 59, "usage_type": "call"}, {"api_name": "products.models.AttributeType.objects", "line_number": 59, "usage_type": "attribute"}, {"api_name": "products.models.AttributeType", "line_number": 59, "usage_type": "name"}, {"api_name": "products.models.AttributeValue.objects.get_or_create", "line_number": 76, "usage_type": "call"}, {"api_name": "products.models.AttributeValue.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "products.models.AttributeValue", "line_number": 76, "usage_type": "name"}, {"api_name": "products.models.AttributeValue.objects.create", "line_number": 81, "usage_type": "call"}, {"api_name": "products.models.AttributeValue.objects", "line_number": 81, "usage_type": "attribute"}, {"api_name": "products.models.AttributeValue", "line_number": 81, "usage_type": "name"}, {"api_name": "products.models.AttributeValue.objects.get_or_create", "line_number": 88, "usage_type": "call"}, {"api_name": "products.models.AttributeValue.objects", "line_number": 88, "usage_type": "attribute"}, {"api_name": "products.models.AttributeValue", "line_number": 88, "usage_type": "name"}, {"api_name": "products.models", "line_number": 97, "usage_type": "name"}, {"api_name": "products.models.Product.objects.filter", "line_number": 97, "usage_type": "call"}, {"api_name": "products.models.Product.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "products.models.Product", "line_number": 97, "usage_type": "name"}, {"api_name": "products.models", "line_number": 98, "usage_type": "argument"}, {"api_name": "products.models", "line_number": 100, "usage_type": "name"}, {"api_name": "products.models.AttributeType.objects.filter", "line_number": 102, "usage_type": "call"}, {"api_name": "products.models.AttributeType.objects", "line_number": 102, "usage_type": "attribute"}, {"api_name": "products.models.AttributeType", "line_number": 102, "usage_type": "name"}, {"api_name": "products.models.AttributeValue.objects.create", "line_number": 106, "usage_type": "call"}, {"api_name": "products.models.AttributeValue.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "products.models.AttributeValue", "line_number": 106, "usage_type": "name"}, {"api_name": "uuslug.slugify", "line_number": 111, "usage_type": "call"}, {"api_name": "products.models.Thumbnail.objects.get_or_create", "line_number": 128, "usage_type": "call"}, {"api_name": "products.models.Thumbnail.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "products.models.Thumbnail", "line_number": 128, "usage_type": "name"}, {"api_name": "products.models.Thumbnail.objects.get_or_create", "line_number": 131, "usage_type": "call"}, {"api_name": "products.models.Thumbnail.objects", "line_number": 131, "usage_type": "attribute"}, {"api_name": "products.models.Thumbnail", "line_number": 131, "usage_type": "name"}, {"api_name": "products.models.Thumbnail.objects.get_or_create", "line_number": 134, "usage_type": "call"}, {"api_name": "products.models.Thumbnail.objects", "line_number": 134, "usage_type": "attribute"}, {"api_name": "products.models.Thumbnail", "line_number": 134, "usage_type": "name"}, {"api_name": "products.models.Thumbnail.objects.get_or_create", "line_number": 137, "usage_type": "call"}, {"api_name": "products.models.Thumbnail.objects", "line_number": 137, "usage_type": "attribute"}, {"api_name": "products.models.Thumbnail", "line_number": 137, "usage_type": "name"}, {"api_name": "utils.thumbnail_creator.create_new_thumb", "line_number": 153, "usage_type": "call"}, {"api_name": "utils.thumbnail_creator", "line_number": 153, "usage_type": "name"}, {"api_name": "utils.thumbnail_creator.create_new_thumb", "line_number": 156, "usage_type": "call"}, {"api_name": "utils.thumbnail_creator", "line_number": 156, "usage_type": "name"}, {"api_name": "utils.thumbnail_creator.create_new_thumb", "line_number": 159, "usage_type": "call"}, {"api_name": "utils.thumbnail_creator", "line_number": 159, "usage_type": "name"}, {"api_name": "utils.thumbnail_creator.create_new_thumb", "line_number": 162, "usage_type": "call"}, {"api_name": "utils.thumbnail_creator", "line_number": 162, "usage_type": "name"}, {"api_name": "django.db.models.signals.post_save.connect", "line_number": 172, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_save", "line_number": 172, "usage_type": "name"}, {"api_name": "products.models.ProductImage", "line_number": 172, "usage_type": "name"}, {"api_name": "django.db.models.signals.post_save.connect", "line_number": 173, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_save", "line_number": 173, "usage_type": "name"}, {"api_name": "products.models.Product", "line_number": 173, "usage_type": "name"}, {"api_name": "django.db.models.signals.post_save.connect", "line_number": 174, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_save", "line_number": 174, "usage_type": "name"}, {"api_name": "products.models.Product", "line_number": 174, "usage_type": "name"}, {"api_name": "django.db.models.signals.post_save.connect", "line_number": 175, "usage_type": "call"}, {"api_name": "django.db.models.signals.post_save", "line_number": 175, "usage_type": "name"}, {"api_name": "products.models.AttributeType", "line_number": 175, "usage_type": "name"}, {"api_name": "django.dispatch.receiver", "line_number": 179, "usage_type": "call"}, {"api_name": "django.db.models.signals.pre_save", "line_number": 179, "usage_type": "argument"}]} +{"seq_id": "512910647", "text": "import os\n\nfrom mimetypes import guess_type\n\nfrom django.conf import settings\nfrom django.db.models import Q\nfrom django.urls import reverse\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView, UpdateView\nfrom django.views.generic.list import ListView\nfrom digitalmarket.mixins import (\n LoginRequiredMixin,\n MultiSlugMixim,\n SubmitBtnMixin\n )\nfrom wsgiref.util import FileWrapper\n\nfrom .forms import ProductAddForm, ProductModelForm\nfrom .mixins import ProductManagerMixin\nfrom .models import Product\n\n\n\n\nclass ProductCreateView(LoginRequiredMixin, SubmitBtnMixin ,CreateView):\n model = Product\n template_name = \"form.html\"\n form_class = ProductModelForm\n #success_url = \"/products/\"\n submit_btn = \"Add\"\n\n def form_valid(self, form):\n user = self.request.user\n form.instance.user = user\n valid_data = super(ProductCreateView, self).form_valid(form)\n form.instance.managers.add(user)\n return valid_data\n\n\nclass ProductUpdateView(ProductManagerMixin, SubmitBtnMixin, MultiSlugMixim, UpdateView):\n model = Product\n template_name = \"form.html\"\n form_class = ProductModelForm\n #success_url = \"/products/\"\n submit_btn = \"Update\"\n\n \nclass ProductDetailView(MultiSlugMixim, DetailView):\n model = Product\n\nclass ProductDownloadView(MultiSlugMixim, DetailView):\n model = Product\n \n def get(self, request, *args, **kwargs):\n obj = self.get_object()\n if obj in request.user.myproducts.products.all():\n filepath = os.path.join(settings.PROTECTED_ROOT, obj.media.path)\n guessed_type = guess_type(filepath)[0]\n #wrapper = FileWrapper(filepath) #, blksize=5) Get AttributeError: 'str' object has no attribute 'read' \n mimetype = 'application/force-download'\n if guessed_type:\n mimetype = guessed_type\n response = HttpResponse(filepath, content_type=mimetype)\n\n if not request.GET.get(\"preview\"):\n response[\"Content-Disposition\"] = \"attachment; filename=%s\" %(obj.media.name)\n \n response[\"X-SendFile\"] = str(obj.media.name) \n return response\n else:\n raise Http404 \n\nclass ProductListView(ListView):\n model = Product\n\n def get_queryset(self, *args, **kwargs):\n qs = super(ProductListView, self).get_queryset(**kwargs)\n query = self.request.GET.get(\"q\")\n if query:\n qs = qs.filter(Q(title__icontains=query)|Q(description__icontains=query)).order_by(\"title\")\n return qs\n\ndef create_view(request):\n form = ProductModelForm(request.POST or None)\n if form.is_valid():\n print (form.cleaned_data.get(\"publish\"))\n instance = form.save(commit=False)\n instance.sale_price = instance.price\n instance.save()\n template = \"form.html\"\n context = {\n \"form\":form,\n \"submit_btn\": \"Create\"\n }\n return render(request, template, context) \n\ndef update_view(request, object_id=None):\n product = get_object_or_404(Product, id=object_id)\n form = ProductModelForm(request.POST or None, instance=product)\n if form.is_valid():\n instance = form.save(commit=False)\n # instance.sale_price = instance.price\n instance.save()\n template = \"form.html\"\n context = {\n \"object\": product,\n \"form\": form,\n \"submit_btn\": \"Update\"\n }\n return render(request, template, context)\n\n\n\ndef detail_slug_view(request, slug=None):\n product = Product.objects.get(slug=slug)\n try:\n product = get_object_or_404(Product, slug=slug)\n except Product.MultupleObjectsReturned:\n product = Product.objects.filter(slug=slug).order_by(\"-title\").first() \n template = \"detail_view.html\"\n context = {\n \"object\": product\n }\n return render(request, template, context)\n\ndef detail_view(request, object_id=None):\n product = get_object_or_404(Product, id=object_id)\n template = \"detail_view.html\"\n context = {\n \"object\": product\n }\n return render(request, template, context)\n\n\ndef list_view(request):\n queryset = Product.objects.all()\n template = \"list_view.html\"\n context = {\n \"queryset\": queryset\n }\n return render(request, template, context)", "sub_path": "src/products/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4488, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "digitalmarket.mixins.LoginRequiredMixin", "line_number": 27, "usage_type": "name"}, {"api_name": "digitalmarket.mixins.SubmitBtnMixin", "line_number": 27, "usage_type": "name"}, {"api_name": "django.views.generic.edit.CreateView", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 28, "usage_type": "name"}, {"api_name": "forms.ProductModelForm", "line_number": 30, "usage_type": "name"}, {"api_name": "mixins.ProductManagerMixin", "line_number": 42, "usage_type": "name"}, {"api_name": "digitalmarket.mixins.SubmitBtnMixin", "line_number": 42, "usage_type": "name"}, {"api_name": "digitalmarket.mixins.MultiSlugMixim", "line_number": 42, "usage_type": "name"}, {"api_name": "django.views.generic.edit.UpdateView", "line_number": 42, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 43, "usage_type": "name"}, {"api_name": "forms.ProductModelForm", "line_number": 45, "usage_type": "name"}, {"api_name": "digitalmarket.mixins.MultiSlugMixim", "line_number": 50, "usage_type": "name"}, {"api_name": "django.views.generic.detail.DetailView", "line_number": 50, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 51, "usage_type": "name"}, {"api_name": "digitalmarket.mixins.MultiSlugMixim", "line_number": 53, "usage_type": "name"}, {"api_name": "django.views.generic.detail.DetailView", "line_number": 53, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 54, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "django.conf.settings.PROTECTED_ROOT", "line_number": 59, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 59, "usage_type": "name"}, {"api_name": "mimetypes.guess_type", "line_number": 60, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 65, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 73, "usage_type": "name"}, {"api_name": "django.views.generic.list.ListView", "line_number": 75, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 76, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 82, "usage_type": "call"}, {"api_name": "forms.ProductModelForm", "line_number": 86, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 97, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 100, "usage_type": "call"}, {"api_name": "models.Product", "line_number": 100, "usage_type": "argument"}, {"api_name": "forms.ProductModelForm", "line_number": 101, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 112, "usage_type": "call"}, {"api_name": "models.Product.objects.get", "line_number": 117, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 117, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 117, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 119, "usage_type": "call"}, {"api_name": "models.Product", "line_number": 119, "usage_type": "argument"}, {"api_name": "models.Product.MultupleObjectsReturned", "line_number": 120, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 120, "usage_type": "name"}, {"api_name": "models.Product.objects.filter", "line_number": 121, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 121, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 121, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 126, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 129, "usage_type": "call"}, {"api_name": "models.Product", "line_number": 129, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 134, "usage_type": "call"}, {"api_name": "models.Product.objects.all", "line_number": 138, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 138, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 138, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 143, "usage_type": "call"}]} +{"seq_id": "644559505", "text": "import logging\n\nimport psycopg2\n\n\nclass PostgresManager:\n \"\"\"docstring for Postgres\"\"\"\n _instance = None\n\n def __new__(cls):\n if cls._instance is None:\n cls._instance = object.__new__(cls)\n\n cls._instance.connect()\n\n return cls._instance\n\n def __init__(self):\n self.connection = self._instance.connection\n self.cursor = self._instance.cursor\n\n def select(self, query):\n try:\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n\n except Exception as error:\n logging.warning('error execting query \"{}\", error: {}'.format(query, error))\n return None\n else:\n return result\n\n def select_with_args(self, query, args):\n try:\n self.cursor.execute(query, args)\n result = self.cursor.fetchall()\n\n except Exception as error:\n logging.warning('error execting query \"{}\", error: {}'.format(query, error))\n return None\n else:\n return result\n\n def insert(self, query):\n try:\n result = self.cursor.execute(query)\n except Exception as error:\n logging.warning('error execting query \"{}\", error: {}'.format(query, error))\n return None\n else:\n return result\n\n def insert_with_args(self, query, values):\n try:\n result = self.cursor.execute(query, values)\n print(result)\n except Exception as error:\n logging.warning('error execting query \"{}\", error: {}'.format(query, error))\n return None\n else:\n return result\n\n def commit_changes(self):\n self.connection.commit()\n\n def __del__(self):\n self.connection.close()\n self.cursor.close()\n\n def connect(self):\n\n # normally the db_credenials would be fetched from a config file or the enviroment\n # meaning shouldn't be hardcoded as follow\n hostname = \"uni-frank.camb6ystrb7z.eu-central-1.rds.amazonaws.com\" # os.environ[\"DATABASE_IP\"]\n port = 5432 # os.environ[\"DATABASE_PORT\"]\n username = \"politicai\" # os.environ[\"DATABASE_USERNAME\"]\n password = \"KdzR7Z^h9YbW&yk9$nCGatG#2eQ$NH\" # os.environ[\"DATABASE_PASSWORD\"]\n database = \"university\" # os.environ[\"DATABASE_NAME\"]\n db_config = {'dbname': database, 'host': hostname,\n 'password': password, 'port': port, 'user': username}\n\n try:\n print('connecting to PostgreSQL database...')\n connection = PostgresManager._instance.connection = psycopg2.connect(**db_config)\n cursor = PostgresManager._instance.cursor = connection.cursor()\n cursor.execute('SELECT VERSION()')\n\n db_version = cursor.fetchone()\n\n except Exception as error:\n logging.error('Error: connection not established {}'.format(error))\n PostgresManager._instance = None\n\n else:\n print('connection established\\n{}'.format(db_version[0]))\n", "sub_path": "flask_app/utility/postgres_manager.py", "file_name": "postgres_manager.py", "file_ext": "py", "file_size_in_byte": 3065, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.warning", "line_number": 28, "usage_type": "call"}, {"api_name": "logging.warning", "line_number": 39, "usage_type": "call"}, {"api_name": "logging.warning", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.warning", "line_number": 58, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 84, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 91, "usage_type": "call"}]} +{"seq_id": "324224334", "text": "from werkzeug.exceptions import RequestEntityTooLarge\n\nimport DAO\nfrom formhandler import signup_validator, fill_user, login_validator, new_recipe_validator, save_recipe_image, \\\n fill_recipe, edit_recipe_validator\nfrom utils import login_required\n\nfrom flask import Blueprint, render_template, request, jsonify, session, redirect, url_for, flash\n\nroutes = Blueprint('routes', __name__)\n\n# TODO: Add a remove recipe function\n# TODO: Add a search function\n# TODO: Enforce 9 results per page (flask-paginate extension can help with this)\n\n\n@routes.route('/')\ndef index():\n recipes = DAO.fetch_recipes()\n return render_template(\"recepten.html\", recipes=recipes)\n\n\n@routes.route(\"/recipe\", methods=[\"GET\", \"POST\"])\ndef recipe():\n\n if request.method == \"POST\":\n\n selected_recipe = DAO.fetch_recipe(request.form.get(\"selected_recipe\"))\n author = DAO.fetch_author(selected_recipe.user_id)\n\n return render_template(\"recept.html\", selected_recipe=selected_recipe, author=author)\n\n else:\n return redirect(url_for(\"routes.index\"))\n\n\n@routes.route(\"/favorite_recipes\")\n@login_required\ndef favorite_recipes():\n\n user_id = session.get('user_id')\n favorites = DAO.fetch_favorites(user_id)\n\n return render_template(\"favorieten.html\", recipes=favorites)\n\n\n@routes.route('/add_recipe', methods=[\"GET\", \"POST\"])\n@login_required\ndef add_recipe():\n\n if request.method == \"POST\":\n\n try:\n message = new_recipe_validator(request)\n\n except RequestEntityTooLarge as err:\n print(\"File too large: \", err)\n flash(\"The file you tried to upload is too large\")\n return redirect(url_for(\"routes.error\"))\n\n if message:\n flash(message)\n return render_template(\"recept_toevoegen.html\")\n else:\n new_recipe = fill_recipe(request, save_recipe_image(request), session.get('user_id'))\n\n DAO.writetodatabase(new_recipe)\n\n flash(\"Recipe successfully added\")\n return redirect(url_for(\"routes.add_recipe\"))\n\n else:\n return render_template(\"recept_toevoegen.html\")\n\n\n@routes.route('/my_recipes', methods=[\"GET\"])\n@login_required\ndef my_recipes():\n\n user_recipes = DAO.fetch_user_recipes(session.get(\"user_id\"))\n author = DAO.fetch_author(session.get(\"user_id\"))\n\n return render_template(\"mijn_recepten.html\", user_recipes=user_recipes, author=author)\n\n\n@routes.route('/edit_recipe', methods=[\"POST\"])\n@login_required\ndef edit_recipe():\n\n selected_recipe = DAO.fetch_recipe(request.form.get(\"selected_recipe\"))\n\n return render_template(\"change_recipe.html\", selected_recipe=selected_recipe)\n\n\n@routes.route('/update_recipe', methods=[\"POST\"])\n@login_required\ndef update_recipe():\n\n try:\n message = edit_recipe_validator(request)\n except RequestEntityTooLarge as err:\n print(\"File too large: \", err)\n flash(\"file too large\")\n return redirect(url_for(\"routes.error\"))\n\n if message:\n flash(message)\n return redirect(url_for(\"routes.error\"))\n else:\n try:\n DAO.update_recipe(request)\n except Exception as err:\n print(\"Could not write to database: \", err)\n flash(\"Could not write to database\")\n redirect(url_for(\"routes.error\"))\n\n updated_recipe = DAO.fetch_recipe(request.form.get(\"recipe_id\"))\n flash(\"Recipe updated\")\n return render_template(\"recept.html\", selected_recipe=updated_recipe)\n\n\n@routes.route('/remove_recipe', methods=['POST'])\n@login_required\ndef remove_recipe():\n\n recipe_id = request.form.get('recipe')\n print(recipe_id)\n\n try:\n DAO.delete_recipe(recipe_id)\n except Exception as err:\n print(\"Could not remove from database: \", err)\n flash(\"Could not remove from database\")\n return redirect(url_for('routes.error'))\n\n flash('Recept verwijderd')\n return redirect(url_for('routes.my_recipes'))\n\n\n@routes.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n\n # User reached route via POST(i.e. via a form)\n if request.method == \"POST\":\n\n # Clear any existing sessions\n session.clear()\n\n # Check if user filled in the from\n message = login_validator(request)\n if message:\n return render_template(\"error.html\", error=message)\n else:\n if not DAO.checkname(request.form.get(\"username\")):\n return render_template(\"login.html\", message=\"Not a valid username\")\n\n user = DAO.fetch_user(request)\n\n if user:\n session[\"user_id\"] = user.user_id\n flash(\"You have logged in\")\n return redirect(url_for(\"routes.my_recipes\"))\n else:\n return render_template(\"login.html\", message=\"Username and or password incorrect\")\n\n # User reached route via GET (i.e by clicking a link)\n else:\n return render_template(\"login.html\")\n\n\n@routes.route(\"/logout\")\n@login_required\ndef logout():\n\n session.clear()\n flash(\"You have logged out\")\n return redirect(url_for(\"routes.index\"))\n\n\n@routes.route('/signup', methods=[\"GET\", \"POST\"])\ndef signup():\n\n # User reached route via POST (i.e filling out form)\n if request.method == \"POST\":\n\n message = signup_validator(request)\n\n if message:\n return render_template(\"error.html\", error=message)\n else:\n new_user = fill_user(request)\n\n if DAO.checkname(new_user.username):\n return render_template(\"error.html\", error=\"Username already in use\")\n elif DAO.check_email(new_user.email):\n return render_template(\"error.html\", error=\"Email already in use\")\n\n if not DAO.writetodatabase(new_user):\n return render_template(\"error.html\", error=\"Something went wrong writing to the database\")\n else:\n return render_template(\"login.html\", message=\"You were successfully registered!\")\n\n # User reached route via GET (i.e redirect or a link)\n else:\n return render_template(\"signup.html\")\n\n\n@routes.route('/error')\ndef error():\n return render_template(\"error.html\")\n\n\n@routes.route('/checkname', methods=[\"POST\"])\ndef checkname():\n\n name = request.form.get(\"name\")\n if DAO.checkname(name):\n return jsonify(False)\n else:\n return jsonify(True)\n\n\n@routes.route('/check_email', methods=[\"POST\"])\ndef check_email():\n\n email = request.form.get(\"mail\")\n if DAO.check_email(email):\n return jsonify(False)\n else:\n return jsonify(True)\n\n\n@routes.route('/favorite', methods=[\"POST\"])\n@login_required\ndef favorite():\n\n user = session.get('user_id')\n recipe_id = int(request.form.get(\"recipe_id\"))\n if DAO.check_for_favorite(user, recipe_id):\n print(\"DAO returned True\")\n return jsonify(True)\n else:\n print(\"DAO Returned False\")\n return jsonify(False)\n\n\n@routes.route('/alter_favorite', methods=[\"POST\"])\n@login_required\ndef alter_favorite():\n\n user_id = session.get(\"user_id\")\n recipe_id = int(request.form.get(\"recipe_id\"))\n\n action = DAO.alter_favorite(user_id, recipe_id)\n\n return jsonify(action)\n ########### On the backend ###############\n # if button is clicked:\n # if recipe is favorite\n # Change to not favorite\n # return not favorite\n # else:\n # Change to favorite\n # return favorite\n\n ########## On the frontend ##############\n\n # if button is clicked:\n # Send recipe_id and / or user_id to server to server\n # With response:\n # if response is no favorite:\n # Change the button_image (with class?) to not favorite\n # else:\n # Change the button_image to favorite\n\n # Also check this if page is loaded and style the button accordingly?\n # Or is it better to send while rendering the template?\n\n", "sub_path": "routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 7858, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Blueprint", "line_number": 10, "usage_type": "call"}, {"api_name": "DAO.fetch_recipes", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "DAO.fetch_recipe", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "name"}, {"api_name": "DAO.fetch_author", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 41, "usage_type": "name"}, {"api_name": "DAO.fetch_favorites", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 44, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 38, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 51, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 51, "usage_type": "name"}, {"api_name": "formhandler.new_recipe_validator", "line_number": 54, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "argument"}, {"api_name": "werkzeug.exceptions.RequestEntityTooLarge", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 63, "usage_type": "call"}, {"api_name": "formhandler.fill_recipe", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 65, "usage_type": "argument"}, {"api_name": "formhandler.save_recipe_image", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 65, "usage_type": "name"}, {"api_name": "DAO.writetodatabase", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 70, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 70, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 73, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 48, "usage_type": "name"}, {"api_name": "DAO.fetch_user_recipes", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 80, "usage_type": "name"}, {"api_name": "DAO.fetch_author", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 81, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 83, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 77, "usage_type": "name"}, {"api_name": "DAO.fetch_recipe", "line_number": 90, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 90, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 90, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 90, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 92, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 87, "usage_type": "name"}, {"api_name": "formhandler.edit_recipe_validator", "line_number": 100, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 100, "usage_type": "argument"}, {"api_name": "werkzeug.exceptions.RequestEntityTooLarge", "line_number": 101, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 103, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 108, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 108, "usage_type": "call"}, {"api_name": "DAO.update_recipe", "line_number": 111, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 111, "usage_type": "argument"}, {"api_name": "flask.flash", "line_number": 114, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 115, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 115, "usage_type": "call"}, {"api_name": "DAO.fetch_recipe", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 117, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 117, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 117, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 119, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 96, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 126, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 126, "usage_type": "name"}, {"api_name": "DAO.delete_recipe", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 136, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 137, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 123, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 144, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 144, "usage_type": "name"}, {"api_name": "flask.session.clear", "line_number": 147, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 147, "usage_type": "name"}, {"api_name": "formhandler.login_validator", "line_number": 150, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 150, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 152, "usage_type": "call"}, {"api_name": "DAO.checkname", "line_number": 154, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 154, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 154, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 154, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 155, "usage_type": "call"}, {"api_name": "DAO.fetch_user", "line_number": 157, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 157, "usage_type": "argument"}, {"api_name": "flask.session", "line_number": 160, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 161, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 162, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 162, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 164, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 168, "usage_type": "call"}, {"api_name": "flask.session.clear", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 175, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 177, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 177, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 172, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 184, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 184, "usage_type": "name"}, {"api_name": "formhandler.signup_validator", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 186, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 189, "usage_type": "call"}, {"api_name": "formhandler.fill_user", "line_number": 191, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 191, "usage_type": "argument"}, {"api_name": "DAO.checkname", "line_number": 193, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 194, "usage_type": "call"}, {"api_name": "DAO.check_email", "line_number": 195, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 196, "usage_type": "call"}, {"api_name": "DAO.writetodatabase", "line_number": 198, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 199, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 201, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 205, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 210, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 216, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 216, "usage_type": "name"}, {"api_name": "DAO.checkname", "line_number": 217, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 218, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 220, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 226, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 226, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 226, "usage_type": "name"}, {"api_name": "DAO.check_email", "line_number": 227, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 228, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 230, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 237, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 238, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 238, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 238, "usage_type": "name"}, {"api_name": "DAO.check_for_favorite", "line_number": 239, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 241, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 244, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 234, "usage_type": "name"}, {"api_name": "flask.session.get", "line_number": 251, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 251, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 252, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 252, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 252, "usage_type": "name"}, {"api_name": "DAO.alter_favorite", "line_number": 254, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 256, "usage_type": "call"}, {"api_name": "utils.login_required", "line_number": 248, "usage_type": "name"}]} +{"seq_id": "396398123", "text": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2013 PolyBeacon, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom stripe.middleware import api\nfrom stripe.tests.middleware import base\n\n\nclass TestCase(base.TestCase):\n\n def test_create_queue_caller(self):\n self._create_queue_caller(queue_id=1)\n\n def test_create_queue_member(self):\n self._create_queue_member(agent_id=1, queue_id=1)\n\n def test_list_queue_callers(self):\n queue_id = 1\n callers = self._create_queue_caller(queue_id=queue_id)\n self._list_queue_callers(len(callers), queue_id)\n\n def test_list_queue_members(self):\n agent_id = 1\n queue_id = 1\n members = self._create_queue_member(\n agent_id=agent_id, queue_id=queue_id\n )\n self._list_queue_members(len(members), queue_id)\n\n def _list_queue_callers(self, total_callers, queue_id, status=None):\n res = self.middleware_api.list_queue_callers(\n queue_id=queue_id,\n status=status,\n )\n self.assertEqual(len(res), total_callers)\n\n def _list_queue_members(self, total_members, queue_id, status=None):\n res = self.middleware_api.list_queue_members(\n queue_id=queue_id,\n status=status,\n )\n self.assertEqual(len(res), total_members)\n\n def test_get_queue_caller(self):\n queue_id = 1\n callers = self._create_queue_caller(queue_id=queue_id)\n res = self.middleware_api.get_queue_caller(\n uuid=callers[0]['uuid'],\n queue_id=queue_id,\n )\n self.assertEqual(res['uuid'], callers[0]['uuid'])\n\n def test_get_queue_member(self):\n agent_id = 1\n queue_id = 1\n members = self._create_queue_member(\n agent_id=agent_id, queue_id=queue_id\n )\n res = self.middleware_api.get_queue_member(\n agent_id=agent_id,\n queue_id=queue_id,\n )\n self.assertEqual(res['extension'], members[0]['extension'])\n\n def test__set_queue_caller_status(self):\n queue_id = 1\n status = api.QueueCallerStatus.RINGING\n callers = self._create_queue_caller(queue_id=queue_id)\n self.middleware_api._set_queue_caller_status(\n queue_id=queue_id, status=status,\n uuid=callers[0]['uuid'],\n )\n res = self.middleware_api.get_queue_caller(\n uuid=callers[0]['uuid'],\n queue_id=queue_id,\n )\n self.assertEqual(res['uuid'], callers[0]['uuid'])\n self.assertEqual(res['status'], unicode(status))\n callers.pop(0)\n self._list_queue_callers(len(callers), queue_id)\n self._list_queue_callers(1, queue_id, status=status)\n", "sub_path": "stripe/tests/middleware/test_api.py", "file_name": "test_api.py", "file_ext": "py", "file_size_in_byte": 3235, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "stripe.tests.middleware.base.TestCase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "stripe.tests.middleware.base", "line_number": 21, "usage_type": "name"}, {"api_name": "stripe.middleware.api.QueueCallerStatus", "line_number": 79, "usage_type": "attribute"}, {"api_name": "stripe.middleware.api", "line_number": 79, "usage_type": "name"}]} +{"seq_id": "605570464", "text": "import copy\nimport glob\nimport random\nimport re\nfrom collections import OrderedDict\nfrom typing import Tuple, List, Union\n\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\nfrom faker import Faker\n\nfrom .base import Block, to_imsize, denorm, bbox\nfrom .lorem import cn_lorem\nfrom . import layout\n\n\ndef load_fonts(roots: List[str]) -> List[ImageFont.FreeTypeFont]:\n fonts = []\n for r in roots:\n for f in glob.glob(r):\n try:\n font = ImageFont.truetype(f)\n fonts.append(f)\n except Exception as e:\n pass\n return fonts\n\n\nfonts_en = load_fonts([\"/workspace/post-generator/asset/fonts_en/**/*.ttf\"])\n# fonts_cn = load_fonts([\"/workspace/post-generator/asset/fonts_cn/**/*.ttf\",\n# \"/workspace/post-generator/asset/fonts_cn/**/*.otf\"])\n# fonts_cn = None\nfonts_cn = load_fonts([\"/workspace/post-generator/asset/fonts_cn/**/*.otf\"])\n\nfake = Faker(OrderedDict([\n ('en-US', 1),\n ('zh_CN', 2),\n ('zh_TW', 3),\n]))\n\n\ndef rand_xy(wh: np.ndarray, imsize: int) -> np.ndarray:\n m = np.clip(np.array([imsize, imsize]) - wh, 0, None)\n x = np.random.randint(0, m[0] + 1)\n y = np.random.randint(0, m[1] + 1)\n return np.array([x, y])\n\n\ndef rand_lines(i_lang, max_words, max_lines) -> List[str]:\n f, _, _ = {\n 0: (fake[\"en-US\"], \"This is a sample text\", 16),\n 1: (fake[\"zh_CN\"], \"这是一个很简单的中文测试\", 16),\n 2: (fake[\"zh_TW\"], \"這是一個很簡單的中文測試\", 16)\n }[i_lang]\n\n # n_lines = np.radnom.randint(1, max_lines + 1)\n n_lines = np.clip(np.random.normal(1, 2), 1, max_lines).astype(np.int32)\n # lines = [f.text(np.random.randint(5, max_words + 1))[:-1]\n # for _ in range(n_lines)]\n lines = [cn_lorem(np.random.randint(5, max_words + 1))\n for _ in range(n_lines)]\n\n return lines\n\n\ndef rand_text_by_wh(box_wh: np.ndarray, i_lang: int, font_path: str) -> str:\n f, t, s = {\n 0: (fake[\"en-US\"], \"This is a sample text\", 16),\n 1: (fake[\"zh_CN\"], \"这是一个很简单的中文测试\", 16),\n 2: (fake[\"zh_TW\"], \"這是一個很簡單的中文測試\", 16)\n }[i_lang]\n\n bw, bh = box_wh\n font = ImageFont.truetype(font_path, s)\n w, h = font.getsize(t)\n\n try:\n text = f.text(max_nb_chars=int(len(t) * bw / w))[:-1]\n w, h = font.getsize(text)\n fontsize = int(s * bw / w)\n except:\n text = \"\"\n fontsize = 0\n\n return text, fontsize\n\n\ndef randbox():\n # return layout.rand_box(np.array([500, 500])).clone(_Box, fonts_cn, 1)\n return layout.Box().clone(_Box, fonts_cn, 1)\n\n# def rand_text(fake: Faker, lang: int):\n# parts = [\" \".join(fake.words(np.random.randint(1, 6)))\n# for _ in range(np.random.randint(1, 5))]\n# for i, p in enumerate(parts):\n# if random.random() < 0.2:\n# if random.random() < 0.5:\n# parts[i] = p.split(\" \")\n# else:\n# parts[i] = [p]\n# return parts\n\n\nclass EmptyBoxError(Exception):\n pass\n\n\nclass EmptyLineError(Exception):\n pass\n\n\nclass Opt:\n def __init__(self, choices=[]):\n self.choices = choices\n\n def one(self):\n e = random.choice(self.choices)\n if e is None:\n return None\n if callable(e):\n return e()\n if isinstance(e, Opt):\n return e.one()\n if isinstance(e, tuple):\n return self._tobox(e)\n\n def _tobox(self, e):\n p, children = e\n b = _Box(fonts_en, p)\n for c in children:\n if isinstance(c, tuple):\n c = self._tobox(c)\n elif callable(c):\n c = c()\n elif isinstance(c, Opt):\n c = c.one()\n else:\n raise Exception\n\n if c is not None:\n b.insert(c)\n\n if len(b.children) == 0:\n raise EmptyBoxError\n elif len(b.children) == 1 and isinstance(b.children[0], _Box):\n return b.children[0]\n else:\n return b\n\n\n# def _ln(): return _Text(\n# \" \".join(fake[\"en-US\"].words(np.random.randint(3, 7))), 0, fonts_en)\n\n\n# def _wd(): return _Text(\n# \" \".join(fake[\"en-US\"].words(np.random.randint(1, 4))), 0, fonts_en)\n\n\n# hkw = Opt([\n# ({\"i_align\": 0}, [_wd, ({\"i_align\": 0}, [_wd]), _wd]),\n# ({\"i_align\": 0}, [_wd, ({\"i_align\": 0}, [_wd])]),\n# ({\"i_align\": 0}, [({\"i_align\": 0}, [_wd]), _wd]),\n# ])\n# hln = Opt([None, None, _ln, _ln, hkw])\n# hln = Opt([kw])\n# mln = Opt([\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, _ln]),\n# ({\"i_align\": 1, \"dapart\": 0}, [hkw, _ln]),\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, hkw]),\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, _ln, _ln]),\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, _ln, hkw]),\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, hkw, _ln]),\n# ({\"i_align\": 1, \"dapart\": 0}, [_ln, _ln, hkw]),\n# # (HOR, [vln, vln, hln, hln, hln]),\n# ])\n\n\nclass Textbox(Block):\n fake = {\n 0: fake[\"en-US\"],\n 1: fake[\"zh_CN\"],\n 2: fake[\"zh_TW\"],\n }\n fonts = {\n 0: fonts_en,\n # 1: fonts_cn,\n # 2: fonts_cn,\n }\n\n def __init__(self, param={}):\n pspace = OrderedDict(\n [\n # 0: en, 1: cn, 2: tw\n # (\"i_lang\", lambda *a: random.choice([0, 1, 2])),\n (\"i_lang\", lambda *a: random.choice([1])),\n (\"n_words\", lambda *a: np.random.randint(3, 10)),\n (\"n_lines\", lambda *a: np.random.randint(1, 4)),\n ]\n )\n super().__init__(pspace)\n\n def sample(self, imsize):\n super().sample(imsize)\n\n # _text = [\"aaa bbb ccc \", [\"ddd \"]]\n # # root = to_box(\n # # rand_text(self.fake[self.param[\"i_lang\"]]), self.param[\"i_lang\"])\n # t = rand_text(self.fake[self.param[\"i_lang\"]])\n # print(t)\n # root = to_box(t, self.param[\"i_lang\"])\n root = mln.one()\n im, infos = root.sample(imsize)\n return im, infos\n\n\nclass BoxLayoutGroupText(Block):\n def __init__(self):\n def _wh(p, *a):\n _wh = np.clip(np.random.normal(0.7, 0.1, 2), 0.5, 1)\n _wh = np.clip(_wh, 0, 2 - 2 * p[\"_cxy\"])\n _wh = np.clip(_wh, 0, 2 * p[\"_cxy\"])\n return _wh\n\n pspace = OrderedDict(\n [\n (\"_cxy\", lambda *a: np.random.uniform(0.15, 0.85, 2)),\n (\"_wh\", _wh),\n (\"bbox\", bbox), # (x1, y1, x2, y2)\n ]\n )\n super().__init__(pspace)\n\n def sample(self, imsize: int):\n super().sample(imsize)\n x0, y0, x1, y1 = self.param[\"bbox\"]\n root = layout.rand_box(np.array([x1 - x0, y1 - y0]))\n root.xy = np.array([x0, y0], dtype=np.int32)\n root.set_xy()\n\n ims, infos = [], []\n for b in root.leafs():\n cp = copy.deepcopy(random.choice(self.blocks))\n _im, _info = cp.sample(imsize, tuple(b.bbox()))\n ims.append(_im)\n infos.append(_info)\n\n return ims, infos\n\n\nclass _Line(layout.Box, Block):\n def __init__(self, t: str):\n super().__init__()\n self.t = t\n\n def __repr__(self):\n return \"<{}>\".format(self.t)\n\n def sample(self, imsize):\n raise NotImplementedError\n\n def _render(self, imsize: int, font: ImageFont, param: dict):\n im = Image.new(\"RGBA\", (imsize, imsize))\n draw = ImageDraw.Draw(im)\n draw.text(self.xy, self.t, param[\"rgb\"], font)\n\n bbox = im.getbbox()\n if bbox is None:\n raise EmptyLineError\n\n return im, [self.info(im, cat=\"Line\", bbox=bbox)]\n # return im, []\n\n # def _render(self, imsize: int):\n # im = Image.new(\"RGBA\", (imsize, imsize))\n # draw = ImageDraw.Draw(im)\n # tks = re.split(r\"(\\s)\", self.t) if self.lang == 0 else list(self.t)\n\n # dx, y = tuple(self.xy)\n # infos = []\n # for tk in tks:\n # if len(tk) == 0:\n # continue\n # draw.text((dx, y), tk, self.param[\"rgb\"], self._font)\n\n # _im = Image.new(\"RGBA\", (imsize, imsize))\n # _draw = ImageDraw.Draw(_im)\n # _draw.text((dx, y), tk, self.param[\"rgb\"], self._font)\n # _bbox = _im.getbbox()\n # # if _bbox is not None:\n # # infos.append(self.info(_im, bbox=_bbox, cat=\"Token\"))\n\n # w, _ = self._font.getsize(tk)\n # dx += w\n\n # if len(infos) > 1:\n # self.update_param(im.getbbox(), imsize)\n # infos.append(self.info(im, cat=\"Box\"))\n\n # # draw.text(tuple(self.xy), self.t, self.param[\"rgb\"], self._font)\n # self._font = None # avoid calling this function twice\n # return im, infos\n\n\nclass _Box(layout.Box, Block):\n max_param_shift = 3 # max number of parameters to modify\n\n def __init__(self, fonts, i_lang, param={}):\n self._fonts = fonts\n self._font = None # save load time\n\n pspace = OrderedDict(\n [\n # (\"i_lang\", lambda *a: random.choice([1])),\n (\"i_lang\", i_lang),\n (\"i_font\", lambda *a: np.random.randint(0, len(fonts))),\n (\"fontsize\", lambda *a: int(np.clip(np.random.normal(20, 5), 7, None))),\n (\"_rgb\", lambda *a: np.random.uniform(0, 1, 3)),\n (\"_a\", lambda *a: np.array([1.0])),\n (\"_xy\", lambda *a: np.random.uniform(0, 0.5, 2)),\n (\"rgb\", denorm(\"_rgb\", 256)),\n (\"xy\", to_imsize(\"_xy\")),\n # 0 for hor, 1 for ver\n (\"i_align\", lambda *a: random.choice([0, 1])),\n # (\"i_align\", lambda *a: 1),\n (\n \"anchor\",\n lambda *a: random.choice([0.0, 0.5, 1.0]),\n # lambda *a: random.choice([None]),\n ), # None for random\n (\"dapart\", lambda p, *a:\n int(np.clip(np.random.normal(p[\"fontsize\"] / 2, p[\"fontsize\"] / 4), 0, None))),\n # (\"dapart\", lambda p, *a: 0)\n ]\n )\n super().__init__(pspace, param)\n\n # self.param_shift = OrderedDict(\n # [\n # (\"i_font\", lambda *a: np.random.randint(0, len(fonts))),\n # (\n # \"textsize\",\n # lambda p:\n # p + int(np.clip(np.random.normal(5, 3), -3, None)),\n # ),\n # (\"_rgb\", lambda *a: np.random.uniform(0, 1, 3)),\n # # (\"i_align\", lambda *a: random.choice([0, 1])),\n # ]\n # )\n # self.after_param_shift = OrderedDict(\n # [\n # (\"dapart\", lambda p, *a:\n # int(np.clip(np.random.normal(p[\"textsize\"], p[\"textsize\"] / 4), 0, None))),\n # (\"rgb\", denorm(\"_rgb\", 256)),\n # ]\n # )\n # self.after_param_shift.update(param)\n\n def __repr__(self) -> str:\n return \"<_Box({}, {}): {}>\".format(self.rxy, self.wh, str(self.children))\n\n def sample(self, imsize: int) -> Tuple[Image.Image, List[dict]]:\n self = randbox()\n self._sample_param(imsize)\n\n # sample text\n for b in self.leafs():\n # text, fontsize = rand_text_by_wh(\n # b.wh, self.param[\"i_lang\"], self._fonts[b.param[\"i_font\"]])\n # if len(text) > 0:\n # t = _Text(text, self._fonts)\n # b.param[\"fontize\"] = fontsize\n # b.insert(t)\n b.param[\"i_align\"] = 1\n b._font = ImageFont.truetype(\n self._fonts[b.param[\"i_font\"]], b.param[\"fontsize\"])\n\n for t in rand_lines(self.param[\"i_lang\"], max_words=15, max_lines=3):\n b.insert(_Line(t))\n\n wh = self._sample_align()\n self.wh = np.array(wh, dtype=np.int32)\n\n # TODO: 確保在Image裡面\n # self.xy = np.array(self.param[\"xy\"], dtype=np.int32)\n self.xy = self.param[\"xy\"] = rand_xy(self.wh, imsize)\n self.set_xy()\n # self.xy = np.zeros(2)\n # self.set_xy()\n\n return self._render(imsize)\n\n def _sample_param(self, imsize):\n super().sample(imsize)\n self.param[\"xy\"] = self.xy\n self.param[\"wh\"] = self.wh\n for c in self.children:\n c._sample_param(imsize)\n\n def _render(self, imsize, *args, **kwargs):\n im = Image.new(\"RGBA\", (imsize, imsize))\n\n # (for debug) draw bbox\n # if self.xy is not None:\n # draw = ImageDraw.Draw(im)\n # bbox = np.concatenate((self.xy, self.xy + self.wh))\n # draw.rectangle(tuple(bbox), fill=None, outline=(200, 0, 0))\n\n infos = []\n for c in self.children:\n try:\n if isinstance(c, _Line):\n font = ImageFont.truetype(\n self._fonts[self.param[\"i_font\"]], self.param[\"fontsize\"])\n _im, _infos = c._render(imsize, font, self.param)\n else:\n _im, _infos = c._render(imsize)\n\n im.alpha_composite(_im)\n infos += _infos\n except (EmptyLineError, EmptyBoxError):\n pass\n\n im = im.rotate(np.random.randint(-60, 60))\n\n bbox = im.getbbox()\n if bbox is None:\n raise EmptyBoxError\n # infos.append(self.info(im, bbox=bbox, cat=\"Box\"))\n\n return im, infos\n\n def _sample_align(self):\n m = {0: layout.HOR, 1: layout.VER}\n\n # init each child's (w, h) in order to align\n for c in self.children:\n if isinstance(c, _Box):\n wh = c._sample_align()\n c.param[\"wh\"] = wh\n elif isinstance(c, _Line):\n wh = self._font.getsize(c.t)\n else:\n raise Exception(\"Unknown type\")\n c.wh = np.array(wh, dtype=np.int32)\n\n return layout.align(\n self.children, by=m[self.param[\"i_align\"]],\n anchor=self.param[\"anchor\"], dapart=self.param[\"dapart\"],\n )\n\n def _sample_shift_param(self, imsize, parent=None):\n \"\"\"@Deprecated\"\"\"\n if parent is None:\n super().sample(imsize)\n else:\n for k in random.sample(\n self.param_shift.keys(), np.random.randint(1, self.max_param_shift + 1)\n # self.param_shift.keys(), np.random.randint(1, 2)\n ):\n p = copy.deepcopy(parent.param)\n p[k] = self.param_shift[k](parent.param[k])\n\n for k, v in self.after_param_shift.items():\n if callable(v):\n p[k] = v(p, imsize)\n else:\n p[k] = v\n self.param = p\n\n for c in self.children:\n if isinstance(c, _Box):\n c._sample_param(imsize, self)\n else:\n print(c)\n raise Exception(\"Unsupported type\")\n\n\n# class _FixedBox(_Box):\n# max_param_shift = 3 # max number of parameters to modify\n# base_text = \"This is a sample text\"\n# base_size = 16\n\n# def __init__(self, fonts, xy, wh, param={}):\n# param.update(dict(xy=xy, wh=wh))\n# pspace = OrderedDict(\n# [\n# (\"i_font\", lambda *a: np.random.randint(0, len(fonts))),\n# (\"_rgb\", lambda *a: np.random.uniform(0, 1, 3)),\n# (\"_a\", lambda *a: np.array([1.0])),\n# (\"rgb\", denorm(\"_rgb\", 256)),\n# # 0 for hor, 1 for ver\n# (\"i_align\", lambda *a: random.choice([0, 1])),\n# (\n# \"anchor\",\n# lambda *a: random.choice([0.0, 0.5, 1.0]),\n# # lambda *a: random.choice([None]),\n# ), # None for random\n# # (\"dapart\", lambda p, *a:\n# # int(np.clip(np.random.normal(p[\"textsize\"], p[\"textsize\"] / 4), 0, None))),\n# ]\n# )\n# super().__init__(pspace, param)\n# self.param_shift = OrderedDict(\n# [\n# (\"i_font\", lambda *a: np.random.randint(0, len(fonts))),\n# (\"_rgb\", lambda *a: np.random.uniform(0, 1, 3)),\n# ]\n# )\n# self.after_param_shift = OrderedDict(\n# [\n# # (\"dapart\", lambda p, *a:\n# # int(np.clip(np.random.normal(p[\"textsize\"], p[\"textsize\"] / 4), 0, None))),\n# (\"rgb\", denorm(\"_rgb\", 256)),\n# ]\n# )\n# self.after_param_shift.update(param)\n# self._fonts = fonts\n# self.xy = xy\n# self.wh = wh\n\n# def sample(self, imsize: int) -> Tuple[Image.Image, List[dict]]:\n# self._sample_param(imsize)\n# for b in self.leafs():\n# text, fontsize = rand_text_by_wh(\n# self.param[\"wh\"], self._fonts[self.param[\"i_font\"]], self.base_text, self.base_size)\n# t = _Text(text, 0, self._fonts)\n# b.param[\"textsize\"] = fontsize\n# # t.xy, t.wh = b.xy, b.wh\n# # print(b.xy)\n# # print(t.xy)\n# b.insert(t)\n# return self._render(imsize)\n", "sub_path": "mysrc/fakedata/blocks/text.py", "file_name": "text.py", "file_ext": "py", "file_size_in_byte": 17287, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.List", "line_number": 17, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 20, "usage_type": "call"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 22, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 22, "usage_type": "name"}, {"api_name": "PIL.ImageFont.FreeTypeFont", "line_number": 17, "usage_type": "attribute"}, {"api_name": "PIL.ImageFont", "line_number": 17, "usage_type": "name"}, {"api_name": "faker.Faker", "line_number": 35, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 44, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.int32", "line_number": 57, "usage_type": "attribute"}, {"api_name": "lorem.cn_lorem", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 60, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 66, "usage_type": "attribute"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 74, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 74, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 117, "usage_type": "call"}, {"api_name": "base.Block", "line_number": 178, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 191, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 196, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 197, "usage_type": "attribute"}, {"api_name": "base.Block", "line_number": 216, "usage_type": "name"}, {"api_name": "numpy.clip", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 219, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 220, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 221, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 226, "usage_type": "attribute"}, {"api_name": "base.bbox", "line_number": 228, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 237, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 242, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 242, "usage_type": "call"}, {"api_name": "base.Block", "line_number": 250, "usage_type": "name"}, {"api_name": "PIL.ImageFont", "line_number": 261, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 262, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 262, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 263, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 263, "usage_type": "name"}, {"api_name": "base.bbox", "line_number": 266, "usage_type": "name"}, {"api_name": "base.bbox", "line_number": 267, "usage_type": "name"}, {"api_name": "base.bbox", "line_number": 270, "usage_type": "name"}, {"api_name": "base.Block", "line_number": 304, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 315, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 316, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 317, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 318, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 319, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 319, "usage_type": "attribute"}, {"api_name": "base.denorm", "line_number": 320, "usage_type": "call"}, {"api_name": "base.to_imsize", "line_number": 321, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 323, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 327, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 331, "usage_type": "attribute"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 374, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 374, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 381, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 381, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 361, "usage_type": "name"}, {"api_name": "PIL.Image.Image", "line_number": 361, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 361, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 361, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 400, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 400, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 412, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 412, "usage_type": "name"}, {"api_name": "numpy.random.randint", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 423, "usage_type": "attribute"}, {"api_name": "base.bbox", "line_number": 425, "usage_type": "name"}, {"api_name": "base.bbox", "line_number": 426, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 444, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 444, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 456, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 457, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 457, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 460, "usage_type": "call"}]} +{"seq_id": "493044422", "text": "# This library will handle ASA objects and policy\n\nimport re # going to need regex\nimport ipaddress #need this for ip address handing\nfrom pprint import pprint #helps with debugging\n\n\n\ndef fgt_obj_str(obj_dict):\n '''\n Create Fortigate objects from the object dictionary\n\n This will return a string with all of the objects which could be copied and pasted or otherwise used\n\n '''\n obj_str = \"config firewall address\\n\" #config firewall address moves one into the address object area of the CLI\n\n for obj_name, obj_data in obj_dict.items():\n\n obj_str += \"edit \" + obj_name + \"\\n\"\n\n if obj_data['type'] == \"fqdn\":\n obj_str += \"set type fqdn\\n\"\n obj_str += \"set fqdn \" + obj_data['fqdn'] + \"\\n\"\n\n elif obj_data['type'] == \"host\":\n obj_str += \"set type ipmask \\n\" #fgt does not have a specific\n obj_str += \"set subnet %s 255.255.255.255\\n\" %( obj_data['host'] )\n\n elif obj_data['type'] == \"subnet\":\n obj_str += \"set type ipmask \\n\"\n netmask = ipaddress.ip_network(obj_data['network'] + '/' + obj_data['prefixlen']).netmask\n obj_str += \"set subnet %s %s \\n\" %( obj_data['network'], netmask )\n\n elif obj_data['type'] == \"range\":\n obj_str += \"set type iprange \\n\"\n obj_str += \"set start-ip %s\\n\" %( obj_data['range first'] )\n obj_str += \"set end-ip %s\\n\" %( obj_data['range last'] )\n\n if \"desc\" in obj_data:\n obj_str += \"set comment %s\\n\" %( obj_data['desc'] )\n\n return obj_str\n", "sub_path": "fgt.py", "file_name": "fgt.py", "file_ext": "py", "file_size_in_byte": 1558, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "ipaddress.ip_network", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "568562115", "text": "#!/usr/local/bin/python3.6\n# pip install pycodestyle\n# edit $HOME/.config/pycodestyle\n# add this\n#\n#[pycodestyle]\n#max-line-length = 120\n\n\n\nimport os\nimport re\nimport subprocess\nimport delegator\nimport glob\nimport sys\n\nsys.path.insert(0,'/Users/teacher/PycharmProjects/untitled/4.021')\n\nimport name_dictionary\n\n\ndef generate_drive_credential():\n\n from apiclient.discovery import build\n from httplib2 import Http\n from oauth2client import file, client, tools\n\n SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'\n store = file.Storage('/Users/teacher/PycharmProjects/untitled/1.040/credentials_drive.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('client_id.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = discovery.build('drive', 'v3', http=creds.authorize(Http()))\n\n\n\ndef generate_sheets_credential():\n\n\n from apiclient.discovery import build\n from httplib2 import Http\n from oauth2client import file, client, tools\n\n # Setup the Sheets API\n SCOPES = 'https://www.googleapis.com/auth/spreadsheets'\n store = file.Storage('/Users/teacher/PycharmProjects/untitled/1.040/credentials_sheets.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('/Users/teacher/PycharmProjects/untitled/1.040/google_sheets_client_secret.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('sheets', 'v4', http=creds.authorize(Http()))\n return service\n\ndef generate_drive_credential():\n\n from apiclient.discovery import build\n from httplib2 import Http\n from oauth2client import file, client, tools\n\n SCOPES = 'https://www.googleapis.com/auth/drive'\n store = file.Storage('/Users/teacher/PycharmProjects/untitled/1.040/credentials_drive.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('/Users/teacher/PycharmProjects/untitled/1.040/google_drive_client_secret.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('drive', 'v3', http=creds.authorize(Http()))\n return service \n\n\n\n\nservice_sheets = generate_sheets_credential()\nservice_drive = generate_drive_credential()\ndef extract_functions(orig_file):\n import re\n outfile_name = orig_file.replace('.py', '.functions.py')\n outfile = open(outfile_name, 'w', encoding='utf8')\n with open(orig_file, 'r', encoding='utf8') as infile:\n line = True\n while line:\n# print(\"starting over looking for function\")\n# print('reading this ' + str(line))\n line = infile.readline()\n start_def = re.search(\"^(def|class) \\s+ .+ \" , line, re.X | re.M | re.S)\n if start_def:\n# print(\"starting function because found this \" + line)\n outfile.write(line)\n in_function = True\n while in_function:\n line = infile.readline()\n# print('reading this line ' + line)\n\n end_of_function = re.search(\"^[a-zA-Z]\", line, re.X | re.M | re.S)\n new_function = re.search(\"^(def|class) \\s+ .+ \" , line, re.X | re.M | re.S)\n\n if end_of_function and not new_function:\n in_function = False\n start_def = False\n elif end_of_function and new_function:\n in_function = True\n start_def = True\n# print(\"found new function witht his line \" + line)\n outfile.write(line)\n\n else:\n outfile.write(line)\n# print('wrote this line ' + line)\n\ndef extract_single_function(orig_file, function):\n import re\n function_file = orig_file.replace('.py', '.functions.py')\n extracted_function = ''\n with open(function_file, 'r', encoding='utf8') as infile:\n line = True\n while line:\n print(\"looking for this function : \" + function)\n line = infile.readline()\n start_def = re.search(\"^(def|class) \\s+ \" + function , line, re.X | re.M | re.S)\n if start_def:\n print(\"entering function!\")\n print('writing this' + str(line))\n extracted_function += line\n print(\"reading this\" + str(line))\n inside_function = True\n while inside_function:\n print('reading this ' + str(line))\n line = infile.readline()\n inside_function = re.search(\"^(\\s+ | \\# ) .+ \" , line, re.X | re.M | re.S)\n if inside_function:\n print(\"writing this inside function \" + str(line))\n extracted_function += line\n extracted_function += line\n return extracted_function\n\n\n# Clear out old files\nfor file in glob.glob('*functions*'):\n #print(file)\n os.remove(file)\n\nfor filename in os.listdir('.'):\n #print(filename)\n do_this_file = False\n if len(sys.argv) > 1:\n if filename in sys.argv:\n do_this_file = True\n else:\n if filename.endswith('.py'):\n do_this_file = True\n if do_this_file:\n for key in name_dictionary.name_dict:\n print(key)\n match = re.match('.+' + key + '.+', filename)\n match2 = re.match('function', filename)\n if match and not match2:\n # construct query here\n print('matches a file in dictionary ' + filename)\n rubric_file = name_dictionary.name_dict[key] + ' - Python 4.036 - Fried Chicken - Rubric'\n# rubric_file = name_dictionary.name_dict[key] + ' - Python 4.025_Serena_Williams_simulator - Rubric'\n# rubric_file = name_dictionary.name_dict[key] + ' - Python 4.021/4.022 - The Rock Says Bad Lossy Compression - Rubric'\n # print(rubric_file)\n query = 'name=' + \"'\" + rubric_file + \"'\"\n # Google drive API to get ID of file\n page_token = None\n response = service_drive.files().list(q=query,\n spaces='drive',\n fields='nextPageToken, files(id, name)',\n pageToken=page_token).execute()\n for file in response.get('files', []):\n print(\"File is {} id is {}\".format(file.get('name'), file.get('id')))\n spreadsheet_id = file.get('id')\n\n datapoints = []\n value = ''\n\n # Find whether or not there is a help\n cmd = 'grep \"#\" ' + filename + ' | grep help | wc -l '\n c = delegator.run(cmd)\n help_comments = int(c.out)\n \n # sheets API to make edit to file if help_comment is found \n if help_comments > 0:\n value = '0'\n else:\n value = '-5'\n # Edit Google sheet for helps\n range_name = 'Rubric' + '!B4' \n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n\n # Find number of PEP8 errors\n cmd = 'pycodestyle --max-line-length=120 --ignore=E305,E226,E241,W504,W293 ' + filename + ' | wc -l '\n c = delegator.run(cmd)\n side_errors = int(c.out)\n side_errors = min(side_errors, 14)\n side_errors *= -1\n\n # sheets API to make edit to file for number of errors\n value = str(side_errors)\n # Edit Google sheet for PEP8 errors (B9)\n range_name = 'Rubric' + '!B9'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n \n with open(filename, 'r', encoding='utf8') as myfile:\n filename_data = myfile.read()\n\n\n \n # extract functions and create python test file\n extract_functions(filename)\n functions_filename = filename.replace('.py', '.functions.py')\n cmd = ' cat ' + functions_filename + \\\n ' /Users/teacher/PycharmProjects/untitled/4.036/var/4.036.test.py > /tmp/4.036.test.py'\n c = delegator.run(cmd)\n \n # Check for function with 2 inputs\n search_object = re.search(r\"^def \\s fried_chicken_problem_1\\(.+ , .+ \\)\", filename_data, re.X| re.M | re.S)\n if not search_object:\n value = '-5'\n else:\n value = '0'\n range_name = 'Rubric' + '!F2'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n \n # test to see if test 1 is correct\n cmd = 'python3 /tmp/4.036.test.py testAutograde.test_fried_chicken_1 2>&1 |grep -i fail |wc -l'\n c = delegator.run(cmd)\n failures = int(c.out)\n if failures > 0:\n value = '-10'\n else:\n value = '0'\n range_name = 'Rubric' + '!F3'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n\n # test to see if test 2 is correct\n cmd = 'python3 /tmp/4.036.test.py testAutograde.test_fried_chicken_2 2>&1 |grep -i fail |wc -l'\n c = delegator.run(cmd)\n failures = int(c.out)\n if failures > 0:\n value = '-10'\n else:\n value = '0'\n range_name = 'Rubric' + '!F4'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n \n # Check for function with 2 inputs\n search_object = re.search(r\"^def \\s fried_chicken_problem_2\\(.+ , .+ \\)\", filename_data, re.X| re.M | re.S)\n if not search_object:\n value = '-5'\n else:\n value = '0'\n range_name = 'Rubric' + '!F7'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n\n # test to see if test 3 is correct\n cmd = 'python3 /tmp/4.036.test.py testAutograde.test_fried_chicken_3 2>&1 |grep -i fail |wc -l' \n c = delegator.run(cmd)\n failures = int(c.out)\n if failures > 0:\n value = '-10'\n else:\n value = '0'\n range_name = 'Rubric' + '!F8'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n \n # test to see if test 4 is correct\n cmd = 'python3 /tmp/4.036.test.py testAutograde.test_fried_chicken_4 2>&1 |grep -i fail |wc -l'\n c = delegator.run(cmd)\n failures = int(c.out)\n if failures > 0:\n value = '-10'\n else:\n value = '0'\n range_name = 'Rubric' + '!F9'\n datapoint = { 'range': range_name,\n 'values': [[value]]\n }\n datapoints.append(datapoint)\n\n\n\n\n\n\n\n body = {'valueInputOption': 'USER_ENTERED',\n 'data':datapoints}\n result = service_sheets.spreadsheets().values().batchUpdate(spreadsheetId=spreadsheet_id,\n body=body).execute()\n", "sub_path": "4.036/autograder_4.036.py", "file_name": "autograder_4.036.py", "file_ext": "py", "file_size_in_byte": 13016, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.path.insert", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "oauth2client.file.Storage", "line_number": 30, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 30, "usage_type": "name"}, {"api_name": "oauth2client.client.flow_from_clientsecrets", "line_number": 33, "usage_type": "call"}, {"api_name": "oauth2client.client", "line_number": 33, "usage_type": "name"}, {"api_name": "oauth2client.tools.run_flow", "line_number": 34, "usage_type": "call"}, {"api_name": "oauth2client.tools", "line_number": 34, "usage_type": "name"}, {"api_name": "httplib2.Http", "line_number": 35, "usage_type": "call"}, {"api_name": "oauth2client.file.Storage", "line_number": 48, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 48, "usage_type": "name"}, {"api_name": "oauth2client.client.flow_from_clientsecrets", "line_number": 51, "usage_type": "call"}, {"api_name": "oauth2client.client", "line_number": 51, "usage_type": "name"}, {"api_name": "oauth2client.tools.run_flow", "line_number": 52, "usage_type": "call"}, {"api_name": "oauth2client.tools", "line_number": 52, "usage_type": "name"}, {"api_name": "apiclient.discovery.build", "line_number": 53, "usage_type": "call"}, {"api_name": "httplib2.Http", "line_number": 53, "usage_type": "call"}, {"api_name": "oauth2client.file.Storage", "line_number": 63, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 63, "usage_type": "name"}, {"api_name": "oauth2client.client.flow_from_clientsecrets", "line_number": 66, "usage_type": "call"}, {"api_name": "oauth2client.client", "line_number": 66, "usage_type": "name"}, {"api_name": "oauth2client.tools.run_flow", "line_number": 67, "usage_type": "call"}, {"api_name": "oauth2client.tools", "line_number": 67, "usage_type": "name"}, {"api_name": "apiclient.discovery.build", "line_number": 68, "usage_type": "call"}, {"api_name": "httplib2.Http", "line_number": 68, "usage_type": "call"}, {"api_name": "re.search", "line_number": 86, "usage_type": "call"}, {"api_name": "re.X", "line_number": 86, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 86, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 86, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 95, "usage_type": "call"}, {"api_name": "re.X", "line_number": 95, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 95, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 95, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 96, "usage_type": "call"}, {"api_name": "re.X", "line_number": 96, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 96, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 96, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 120, "usage_type": "call"}, {"api_name": "re.X", "line_number": 120, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 120, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 120, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 130, "usage_type": "call"}, {"api_name": "re.X", "line_number": 130, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 130, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 130, "usage_type": "attribute"}, {"api_name": "oauth2client.file", "line_number": 139, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 139, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 141, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 141, "usage_type": "argument"}, {"api_name": "os.listdir", "line_number": 143, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 146, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 147, "usage_type": "attribute"}, {"api_name": "name_dictionary.name_dict", "line_number": 153, "usage_type": "attribute"}, {"api_name": "re.match", "line_number": 155, "usage_type": "call"}, {"api_name": "re.match", "line_number": 156, "usage_type": "call"}, {"api_name": "name_dictionary.name_dict", "line_number": 160, "usage_type": "attribute"}, {"api_name": "oauth2client.file", "line_number": 171, "usage_type": "name"}, {"api_name": "oauth2client.file.get", "line_number": 172, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 172, "usage_type": "name"}, {"api_name": "oauth2client.file.get", "line_number": 173, "usage_type": "call"}, {"api_name": "oauth2client.file", "line_number": 173, "usage_type": "name"}, {"api_name": "delegator.run", "line_number": 180, "usage_type": "call"}, {"api_name": "delegator.run", "line_number": 197, "usage_type": "call"}, {"api_name": "delegator.run", "line_number": 221, "usage_type": "call"}, {"api_name": "re.search", "line_number": 224, "usage_type": "call"}, {"api_name": "re.X", "line_number": 224, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 224, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 224, "usage_type": "attribute"}, {"api_name": "delegator.run", "line_number": 237, "usage_type": "call"}, {"api_name": "delegator.run", "line_number": 251, "usage_type": "call"}, {"api_name": "re.search", "line_number": 264, "usage_type": "call"}, {"api_name": "re.X", "line_number": 264, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 264, "usage_type": "attribute"}, {"api_name": "re.S", "line_number": 264, "usage_type": "attribute"}, {"api_name": "delegator.run", "line_number": 277, "usage_type": "call"}, {"api_name": "delegator.run", "line_number": 291, "usage_type": "call"}]} +{"seq_id": "4338574", "text": "from django.test.testcases import TestCase\nfrom 臺灣言語工具.解析整理.拆文分析器 import 拆文分析器\nfrom 搜揣.加入排序特徵 import _巡字物件存在無\n\n\nclass 單元試驗(TestCase):\n def test_兩个字_拄好一詞_有佇內底(self):\n 比對 = 拆文分析器.對齊句物件('媠媠', 'sui2-sui2').篩出字物件()\n 欲揣 = 拆文分析器.建立句物件('媠sui2').篩出字物件()\n self.assertTrue(_巡字物件存在無(欲揣, 比對))\n\n def test_跨兩个詞_兩詞中央字_有佇內底(self):\n 整句 = 拆文分析器.對齊句物件('媠媠姑娘', 'sui2-sui2 koo1-niu5').篩出字物件()\n 比對 = 整句[1:3]\n 欲揣 = 拆文分析器.建立句物件('媠姑').篩出字物件()\n self.assertTrue(_巡字物件存在無(欲揣, 比對))\n\n def test_跨兩个詞_拄好兩詞_有佇內底(self):\n 比對 = 拆文分析器.對齊句物件('媠媠姑娘', 'sui2-sui2 koo1-niu5').篩出字物件()\n 欲揣 = 拆文分析器.建立句物件('媠媠姑娘').篩出字物件()\n self.assertTrue(_巡字物件存在無(欲揣, 比對))\n\n def test_無佇內底(self):\n 比對 = 拆文分析器.對齊句物件('媠', 'sui2').篩出字物件()\n 欲揣 = 拆文分析器.建立句物件('豬').篩出字物件()\n self.assertFalse(_巡字物件存在無(欲揣, 比對))\n\n def test_無佇內底_媠姑揣媠媠(self):\n 比對 = 拆文分析器.對齊句物件('媠姑', 'sui2-koo1').篩出字物件()\n 欲揣 = 拆文分析器.建立句物件('媠媠').篩出字物件()\n self.assertFalse(_巡字物件存在無(欲揣, 比對))\n", "sub_path": "試驗/搜揣/test加入排序特徵試驗_巡字物件存在無.py", "file_name": "test加入排序特徵試驗_巡字物件存在無.py", "file_ext": "py", "file_size_in_byte": 1689, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.test.testcases.TestCase", "line_number": 6, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.對齊句物件", "line_number": 8, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 8, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.建立句物件", "line_number": 9, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 9, "usage_type": "name"}, {"api_name": "搜揣.加入排序特徵._巡字物件存在無", "line_number": 10, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.對齊句物件", "line_number": 13, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 13, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.建立句物件", "line_number": 15, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 15, "usage_type": "name"}, {"api_name": "搜揣.加入排序特徵._巡字物件存在無", "line_number": 16, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.對齊句物件", "line_number": 19, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 19, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.建立句物件", "line_number": 20, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 20, "usage_type": "name"}, {"api_name": "搜揣.加入排序特徵._巡字物件存在無", "line_number": 21, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.對齊句物件", "line_number": 24, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 24, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.建立句物件", "line_number": 25, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 25, "usage_type": "name"}, {"api_name": "搜揣.加入排序特徵._巡字物件存在無", "line_number": 26, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.對齊句物件", "line_number": 29, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 29, "usage_type": "name"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器.建立句物件", "line_number": 30, "usage_type": "call"}, {"api_name": "臺灣言語工具.解析整理.拆文分析器.拆文分析器", "line_number": 30, "usage_type": "name"}, {"api_name": "搜揣.加入排序特徵._巡字物件存在無", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "59629063", "text": "import re\nimport spacy\nfrom collections import Counter\nimport en_core_web_sm\nnlp = en_core_web_sm.load()\nfrom pprint import pprint\n\ndef get_amounts(string):\n \"\"\"Returns all the amounts found in the string 'sent' in a list\n\n Getting the amounts for example: RM10 RM10.00 RM100,000.00\n\n Parameters\n ----------\n sent : str\n original string without any prior preprocessing\n\n \"\"\"\n split = string.split(' ')\n #Matches any string that begins with RM\n #contains only numbers, comma, period\n r = re.compile(\"\\ARM[0-9,.]+\")\n amount = list(filter(r.match, split))\n return amount\n\ndef get_bank_accounts(string):\n \"\"\"Returns all the amounts found in the string 'sent' in a list\n\n Getting the amounts for example: RM10 RM10.00 RM100,000.00\n\n Parameters\n ----------\n sent : str\n original string without any prior preprocessing\n\n \"\"\"\n split = string.split(' ')\n #Matches any string that contains only numbers or hyphens,\n #Minimum length of 6 characters, maximum length of 18 characters\n r = re.compile(\"[0-9\\-]{6,18}\")\n bank_accounts = list(filter(r.match, split))\n return bank_accounts\n\ndef get_entities(sent):\n \"\"\"Returns all the entities found in the string 'sent' in a dictionary\n \n Doesn't do any prior preprocessing at all\n\n Parameters\n ----------\n sent : str\n string in which all the entities need to be extracted from\n\n \"\"\"\n res = {}\n #Using spacy's pre-trained model to do high level classification of entities\n entities_dict = dict([(str(x), x.label_) for x in nlp(sent).ents])\n\n #Getting the amounts for example: RM10 RM10.00 RM100,000.00\n amounts = get_amounts(sent)\n bank_accounts = get_bank_accounts(sent)\n\n #Removing all amounts and bank_accounts from the dictionary created by spacy\n for key in amounts:\n if key in entities_dict:\n del entities_dict[key]\n for key in bank_accounts:\n if key in entities_dict:\n del entities_dict[key]\n\n #Grouping the keys according to their values\n res = {n:[k for k in entities_dict.keys() if entities_dict[k] == n] for n in set(entities_dict.values())}\n #Adding AMOUNT and BANK_ACC into the dictionary\n res['AMOUNT'] = amounts\n res['BANK_ACC'] = bank_accounts\n return res\n\nif __name__ == '__main__':\n # Code mostly modified from https://towardsdatascience.com/named-entity-recognition-with-nltk-and-spacy-8c4a7d88e7da\n # To test whether if it works just run this file: \"py entity_extraction.py\"\n from bs4 import BeautifulSoup\n import requests\n import re\n\n def url_to_string(url):\n res = requests.get(url)\n html = res.text\n soup = BeautifulSoup(html, 'html5lib')\n for script in soup([\"script\", \"style\", 'aside']):\n script.extract()\n return \" \".join(re.split(r'[\\n\\t]+', soup.get_text()))\n\n ny_bb = url_to_string('https://www.theedgemarkets.com/article/bursa-malaysia-1q-net-profit-rm121m-rm65m-year-earlier')\n test_string = 'I want to deposit RM10 RM10.00 RM100,000.00 into my bank account 9990-6000-43141 99694039900 541421'\n entities_dict = get_entities(ny_bb)\n pprint(entities_dict)\n test_dict = get_entities(test_string)\n pprint(test_dict)", "sub_path": "entity_extraction.py", "file_name": "entity_extraction.py", "file_ext": "py", "file_size_in_byte": 3252, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "en_core_web_sm.load", "line_number": 5, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 22, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 40, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 86, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 88, "usage_type": "call"}, {"api_name": "re.split", "line_number": 91, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 96, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "341872149", "text": "#!/usr/bin/python3\n\"\"\"[a script that lists all states with a name starting with N (upper N)\nfrom the database hbtn_0e_0_usa:]\n\"\"\"\n\nimport MySQLdb\nfrom sys import argv\n\n\nif __name__ == \"__main__\":\n \"\"\"[validate the quantity of arguments passed]\n \"\"\"\n if len(argv) != 4:\n print('Usage: 1-filter_states.py username password database')\n exit(1)\n\n db = MySQLdb.connect('localhost', argv[1], argv[2], argv[3], port=3306)\n cur = db.cursor()\n\n cur.execute(\"\"\"\n SELECT\n *\n FROM\n states\n WHERE\n name\n LIKE BINARY\n \"N%\"\n ORDER BY\n id ASC\"\"\")\n\n rows = cur.fetchall()\n for row in rows:\n print(row)\n\n cur.close()\n db.close()\n", "sub_path": "0x0F-python-object_relational_mapping/1-filter_states.py", "file_name": "1-filter_states.py", "file_ext": "py", "file_size_in_byte": 752, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 13, "usage_type": "argument"}, {"api_name": "MySQLdb.connect", "line_number": 17, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 17, "usage_type": "name"}]} +{"seq_id": "94188660", "text": "from celery import shared_task\nfrom django.core.mail import send_mail\nfrom .models import Order\n@shared_task\ndef order_created(order_id):\n \"\"\"Task to send an e-mail notification when an order is\n successfully created\"\"\"\n order=Order.objects.get(id=order_id)\n subject=f\"Order nr. {order.id}\"\n message=f\"Дорогой, {order.first_name},\\n\\n\" \\\n f\"Вы успешно разместили заказ\" \\\n f\"Номер вашего заказа {order.id}\"\n mail_sent=send_mail(subject, message, 'admin@myshop.com',\n [order.email] )\n return mail_sent", "sub_path": "orders/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 594, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "models.Order.objects.get", "line_number": 8, "usage_type": "call"}, {"api_name": "models.Order.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "models.Order", "line_number": 8, "usage_type": "name"}, {"api_name": "django.core.mail.send_mail", "line_number": 13, "usage_type": "call"}, {"api_name": "celery.shared_task", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "79799796", "text": "import scipy.io as scio\nfrom matplotlib import pyplot as plt\nimport cofiCostFunc\nimport numpy as np\nimport checkNNGradients\nimport scipy.optimize as opt\n\ndef serialize(X, Theta):\n return np.concatenate((X.flatten(), Theta.flatten()))\n\n\ndef deserialize(params, num_users, num_movies, num_features):\n X = np.reshape(params[0:num_movies * num_features], (num_movies, num_features))\n Theta = np.reshape(params[num_movies * num_features:], (num_users, num_features))\n return X, Theta\n\n\n# 协同过滤\n# ######################## loading movie ratings dataset ################\nif __name__ == \"__main__\":\n # load moving ratings dataset\n data = scio.loadmat(\"../machine-learning-ex8/ex8/ex8_movies.mat\")\n Y = data[\"Y\"]\n R = data[\"R\"]\n print(Y)\n # visualize Y data\n plt.imshow(Y)\n # plt.show()\n movie_params = scio.loadmat(\"../machine-learning-ex8/ex8/ex8_movieParams.mat\")\n # reduce datset\n num_users = 4\n num_movies = 5\n num_features = 3\n X = movie_params[\"X\"][0:num_movies, 0:num_features]\n R = R[0:num_movies, 0:num_users]\n Y = Y[0:num_movies, 0:num_users]\n Theta = movie_params[\"Theta\"][0:num_users, 0:num_features]\n params = serialize(X, Theta)\n cost, grad = cofiCostFunc.cotiCostFunc(params, Y, R, num_users, num_movies, num_features, 1.5)\n print(\"cost is {}, expected cost is 31.34\".format(cost))\n grad_numerically = checkNNGradients.compute_grad_numerically(params, Y, R, num_users, num_movies, num_features, 1.5)\n print(\"grad is {}, grad_numerically is {}\".format(grad, grad_numerically))\n # ========= parse movie_ids =======================\n movie_list = []\n with open(\"../machine-learning-ex8/ex8/movie_ids.txt\", encoding='latin-1') as file:\n lines = file.readlines()\n for line in lines:\n token = line.strip().split(\" \")\n movie_list.append(' '.join(token[1:]))\n movie_list = np.array(movie_list)\n # reproduce my ratings\n ratings = np.zeros(1682)\n ratings[0] = 4\n ratings[6] = 3\n ratings[11] = 5\n ratings[53] = 4\n ratings[63] = 5\n ratings[65] = 3\n ratings[68] = 5\n ratings[97] = 2\n ratings[182] = 4\n ratings[225] = 5\n ratings[354] = 5\n # get Y, R\n Y = data[\"Y\"]\n R = data[\"R\"]\n # now I become user0\n Y = np.insert(Y, 0, ratings, axis=1)\n R = np.insert(R, 0, ratings != 0, axis=1) # type casting*****\n # some params\n n_features = 50\n n_movie, n_user = Y.shape\n l = 10\n X = np.random.standard_normal((n_movie, n_features))\n Theta = np.random.standard_normal((n_user, n_features))\n param = serialize(X, Theta)\n # normalized ratings\n Y_mean = np.reshape(np.mean(Y, 1), (Y.shape[0], 1))\n normalized_Y = Y - Y_mean\n\n res = opt.minimize(fun=cofiCostFunc.regularized_cost,\n x0=param,\n args=(normalized_Y, R, n_user, n_movie, n_features, l),\n method='TNC',\n jac=cofiCostFunc.regularized_gradient)\n print(res)\n X_train, Theta_train = deserialize(res.x, n_user, n_movie, n_features)\n prediction = X_train@Theta_train.T\n my_preds = prediction[:, 0].reshape((-1, 1)) + Y_mean # I'm user 0\n idxs = np.argsort(my_preds.flatten())[::-1][:10] # Descending order\n for m in movie_list[idxs]:\n # show top 10\n print(m)\n", "sub_path": "programming_ex8/ex8/ex8_cofi.py", "file_name": "ex8_cofi.py", "file_ext": "py", "file_size_in_byte": 3342, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.concatenate", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 14, "usage_type": "call"}, {"api_name": "scipy.io.loadmat", "line_number": 22, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "scipy.io.loadmat", "line_number": 29, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 29, "usage_type": "name"}, {"api_name": "cofiCostFunc.cotiCostFunc", "line_number": 39, "usage_type": "call"}, {"api_name": "checkNNGradients.compute_grad_numerically", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.insert", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.insert", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.random.standard_normal", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.random.standard_normal", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.reshape", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 78, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 81, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 81, "usage_type": "name"}, {"api_name": "cofiCostFunc.regularized_cost", "line_number": 81, "usage_type": "attribute"}, {"api_name": "cofiCostFunc.regularized_gradient", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.argsort", "line_number": 90, "usage_type": "call"}]} +{"seq_id": "629459046", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom common.models import ApiModel\n\n\nAGREED_TO_REQUEST = \"AGREED_TO_REQUEST\" # User is available and Agreed for a ride request\nDENY_REQUEST = \"DENY_REQUEST\" # User is available but denies request\nCANCEL_PROMISE = \"CANCEL_PROMISE\" # User is available but Cancels ride promise\nASKED_FOR_RIDE = \"ASKED_FOR_RIDE\" # User is in Need and Asks for a ride\nCANCEL_REQUEST = \"CANCEL_REQUEST\" # User is in Need but he Cancels ride request\n\nclass Device(ApiModel):\n serialize_fields = [\n 'id',\n ('user__id', 'user'),\n 'active',\n 'date_created',\n 'device_id',\n 'registration_id',\n 'device_type',\n ]\n user = models.ForeignKey(User, related_name='device') # one user can have more than one phone (needed for testing)\n active = models.BooleanField(default=True)\n date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n device_id = models.CharField(max_length=150, null=False)\n registration_id = models.CharField(max_length=1024, null=False)\n device_type = models.CharField(max_length=64, blank=True, null=True)\n\n\n", "sub_path": "notification/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1213, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "common.models.ApiModel", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 22, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 22, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "8766856", "text": "import os,sys,pickle\nimport os.path as osp\nimport numpy as np\nimport numpy.random as npr\nfrom utils.base import readPickle,writePickle\n\n\nclass BijectionFunctions():\n\n def __init__(self, bijectionType, randomPixelsFile=\"./randomPixels.pkl\", maxPixelNum=None):\n self.bijectionType = bijectionType\n self.randomPixelsFile = randomPixelsFile\n self.randomPixels = self.load_random_pixels()\n self.availableBijections = ['rtVal = self.random_pixel_shuffle({})']\n if maxPixelNum: self.set_random_pixels(maxPixelNum)\n\n def load_random_pixels(self):\n randomPixelsFile = self.randomPixelsFile\n if osp.exists(randomPixelsFile):\n return readPickle(randomPixelsFile)\n return None\n \n def set_random_pixels(self,numPixels):\n if osp.exists(self.randomPixelsFile):\n print(\"overwriting current randomPixelsFile: {}\".format(self.randomPixelsFile))\n self.randomPixels = npr.permutation(numPixels)\n writePickle(self.randomPixelsFile,self.randomPixels)\n \n def random_pixel_shuffle(self,data):\n if self.randomPixels is None: self.set_random_pixels(data.size)\n if data.size < self.randomPixels.size:\n print(\"[util/bijectionFunction.py random_pixel_shuffle]:\")\n print(\"data.size < randomPixels.size\")\n sys.exit(1)\n remainder = np.arange(self.randomPixels.size,data.size)\n randomPixels = np.hstack((self.randomPixels,remainder))\n rdata = data.ravel()[randomPixels].reshape(data.shape)\n return rdata \n \n def applyBijection(self,data):\n if self.bijectionType is None:\n return data\n if self.bijectionType not in self.availableBijections:\n print(\"Uknown bijection. Please use one from the list below.\")\n print(\"-\"*30)\n for name in self.availableBijections: print(name)\n print(\"-\"*30)\n sys.exit()\n exec(self.bijectionType.format('data'))\n return rtVal\n\n\n \n", "sub_path": "lib/utils/bijectionFunctions.py", "file_name": "bijectionFunctions.py", "file_ext": "py", "file_size_in_byte": 2045, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.exists", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "name"}, {"api_name": "utils.base.readPickle", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.random.permutation", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "name"}, {"api_name": "utils.base.writePickle", "line_number": 27, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 36, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "556504176", "text": "import pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\n\n\ndf = pd.read_csv('loansData_clean_full.csv')\n\nx1 = df['Annual.Income']\ny1 = df['Interest.Rate']\n\nX1 = sm.add_constant(x1)\n\ninc_int_model = sm.OLS(y1, X1).fit()\n\nprint(inc_int_model.summary())\n\n\nx2 = df[['Annual.Income', 'Home.Owner']]\ny2 = df['Interest.Rate']\n\nX2 = sm.add_constant(x2)\n\ninc_int_own_model = sm.OLS(y2, X2).fit()\n\nprint(inc_int_own_model.summary())\n\n", "sub_path": "multivariate.py", "file_name": "multivariate.py", "file_ext": "py", "file_size_in_byte": 435, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 6, "usage_type": "call"}, {"api_name": "statsmodels.api.add_constant", "line_number": 11, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 11, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 13, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 13, "usage_type": "name"}, {"api_name": "statsmodels.api.add_constant", "line_number": 21, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 21, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 23, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 23, "usage_type": "name"}]} +{"seq_id": "336484766", "text": "# coding: utf-8\n\nimport os\n\nimport numpy as np\nfrom PIL import Image\nimport glob\n\nimport tensorflow as tf\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets\n\n\ndef numpy_ndarray_to_jpeg_files( images, shape, dir_path, labals ):\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n images = images * 255 # 画像データの値を0~255の範囲に変更する\n for i in range( images.shape[0] ):\n image_array = images[i].reshape(shape)\n out_img = Image.fromarray(image_array)\n out_img = out_img.convert(\"L\") # グレースケール\n l = str(np.argmax(labals[i]))\n if not os.path.exists( os.path.join( dir_path,l) ):\n os.mkdir( os.path.join( dir_path,l) )\n fname = str(i) + \"-\" + l + \".jpg\"\n out_img.save( os.path.join( dir_path, l, fname ), format=\"JPEG\")\n return\n\ndef write_image_by_tfrecord( image_obj, label, writer ):\n image = np.array(image_obj)\n height = image.shape[0]\n width = image.shape[1]\n image_raw = image.tostring() # binary 化.\n example = tf.train.Example(features=tf.train.Features(feature={\n \"height\": tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),\n \"width\": tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),\n \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),\n \"image\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_raw]))\n }))\n # レコード書込\n writer.write( example.SerializeToString() )\n return\n\ndef fpath_list_to_tfrecord( fpath_list, result_fpath ):\n with tf.python_io.TFRecordWriter( result_fpath ) as writer:\n for fpath in fpath_list:\n fname = os.path.basename(fpath)\n label = int( fname[ fname.rfind(\"-\") + 1 : -4] ) # ファイル名からラベルを取得\n with Image.open(fpath).convert(\"L\") as image_obj: # グレースケール\n write_image_by_tfrecord( image_obj, label, writer )\n return\n \ndef tfrecord_to_jpegs( tfrecord_fpath, jpeg_dir ):\n if not os.path.exists(jpeg_dir):\n os.mkdir(jpeg_dir)\n iterator = tf.python_io.tf_record_iterator(tfrecord_fpath) \n for i,record in enumerate(iterator):\n example = tf.train.Example()\n example.ParseFromString(record) # バイナリデータからの読み込み\n height = example.features.feature[\"height\"].int64_list.value[0]\n width = example.features.feature[\"width\"].int64_list.value[0]\n label = example.features.feature[\"label\"].int64_list.value[0]\n image_array = example.features.feature[\"image\"].bytes_list.value[0]\n\n image = np.fromstring( image_array, dtype=np.uint8)\n image = image.reshape([height, width])\n img = Image.fromarray( image, \"L\") # グレースケール\n fname = \"tfrecords_{0}-{1}.jpg\".format(i, label )\n img.save( os.path.join( jpeg_dir, fname ) )\n return\n\n\ndef read_and_decode_by_tensorflow(fname_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(fname_queue) # 次のレコードの key と value が返ってきます\n features = tf.parse_single_example(\n serialized_example,\n features={\n \"height\": tf.FixedLenFeature([], tf.int64),\n \"width\": tf.FixedLenFeature([], tf.int64),\n \"label\": tf.FixedLenFeature([], tf.int64),\n \"image\": tf.FixedLenFeature([], tf.string), # binary を tf.string で受け取る.\n })\n image_raw = tf.decode_raw(features[\"image\"], tf.uint8)\n height = tf.cast(features[\"height\"], tf.int32)\n width = tf.cast(features[\"width\"], tf.int32)\n label = tf.cast(features[\"label\"], tf.int32)\n image = tf.reshape( image_raw, tf.stack([height, width]) )\n return image, label\n\n\ndef tensorflow_read_and_write( tfrecord_fpath, result_dir ):\n if not os.path.exists(result_dir):\n os.mkdir(result_dir)\n fname_queue = tf.train.string_input_producer([tfrecord_fpath]) # TFRecordファイルからキューを作成\n images_gen, labels_gen = read_and_decode_by_tensorflow(fname_queue) # キューからデコードされた画像データとラベルを取得する処理を定義\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer()) # 初期化\n try:\n coord = tf.train.Coordinator() # スレッドのコーディネーター\n threads = tf.train.start_queue_runners(coord=coord) # グラフで収集されたすべてのキューランナーを開始\n for i in range(10000):\n image, label = sess.run([images_gen, labels_gen]) # 次のキューから画像データとラベルを取得\n img = Image.fromarray( image, \"L\" ) # グレースケール\n fname = \"tfrecords_{0}-{1}.jpg\".format(str(i), label) \n img.save( os.path.join( result_dir, fname ) ) # 画像を保存\n finally:\n coord.request_stop() # すべてのスレッドが停止するように要求\n coord.join(threads) # スレッドが終了するのを待つ\n return\n\n\n# jpeg ファイルの作成.\nmnist = read_data_sets(\"MNIST_data\",one_hot=True)\n# print(type(mnist.test.images)) # numpy.ndarray\n# print(mnist.test.images.shape) # (10000, 784)\njpeg_dir = \"mnist_jpeg_train2\"\nnumpy_ndarray_to_jpeg_files( mnist.train.images, (28,28),\n jpeg_dir, mnist.train.labels )\n# jpeg_dir = \"mnist_jpeg_test2\"\n# numpy_ndarray_to_jpeg_files( mnist.test.images, (28,28),\n# jpeg_dir, mnist.test.labels )\n\n# tfrecord 作成.\n#fpath_list = glob.glob( os.path.join( jpeg_dir , \"*.jpg\") )\n#tfrecord_fpath = \"mnist_train.tfrecord\"\n# fpath_list_to_tfrecord( fpath_list, tfrecord_fpath )\n\n# tfrecord の読み込み.\n# jpeg_dir2 = \"from_tfrecord_jpeg\"\n# tfrecord_to_jpegs( tfrecord_fpath, jpeg_dir2 )\n\n# tensorflow での読み込み.\n# jpeg_dir3 = \"from_tfrecord_jpeg_by_tf\"\n# tensorflow_read_and_write( tfrecord_fpath, jpeg_dir3 )\n", "sub_path": "npair_loss/my_data_build.py", "file_name": "my_data_build.py", "file_ext": "py", "file_size_in_byte": 6051, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.exists", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 15, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 19, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 19, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.train.Example", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Features", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.train.Feature", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Int64List", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.train.Feature", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Int64List", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.train.Feature", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Int64List", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.train.Feature", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.train.BytesList", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.python_io.TFRecordWriter", "line_number": 44, "usage_type": "call"}, {"api_name": "tensorflow.python_io", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 48, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 48, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.python_io.tf_record_iterator", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.python_io", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Example", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.fromstring", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 64, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 66, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 66, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "tensorflow.TFRecordReader", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.parse_single_example", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.FixedLenFeature", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.int64", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.FixedLenFeature", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.int64", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tensorflow.FixedLenFeature", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.int64", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.FixedLenFeature", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.string", "line_number": 81, "usage_type": "attribute"}, {"api_name": "tensorflow.decode_raw", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.uint8", "line_number": 83, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 84, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 86, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.stack", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path", "line_number": 92, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.train.string_input_producer", "line_number": 94, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 94, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 97, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.train.Coordinator", "line_number": 100, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tensorflow.train.start_queue_runners", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 101, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 104, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 104, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.learn.python.learn.datasets.mnist.read_data_sets", "line_number": 114, "usage_type": "call"}]} +{"seq_id": "285521658", "text": "from django.core.management.base import BaseCommand\nfrom django.conf import settings\nimport os, json\nfrom verses.models import Tag1, Tag2, Tag3\n\nclass Command(BaseCommand):\n help = 'Fill DB with static data'\n\n def handle(self, *args, **kwargs):\n file_handler = open(os.path.join(settings.BASE_DIR, 'static_tag_data.json'))\n data = json.load(file_handler)\n all_tags = data[\"outline\"]\n for tag1_data in all_tags:\n tag1 = tag1_data[\"text\"]\n tag1_obj = Tag1.objects.create(name=tag1)\n print(\"Created new tag1 named:\",tag1)\n all_tag2_data = tag1_data[\"outline\"]\n for tag2_data in all_tag2_data:\n tag2 = tag2_data[\"text\"]\n tag2_obj = Tag2.objects.create(parent_tag=tag1_obj,name=tag2)\n print(\"Created new tag2 named:\",tag2)\n all_tag3_data = tag2_data[\"outline\"]\n for tag3_data in all_tag3_data:\n tag3 = tag3_data[\"text\"]\n try:\n Tag3.objects.create(parent_tag=tag2_obj,name=tag3)\n except:\n print(\"Duplicate found\")\n print(\"Created new tag3 named:\",tag3)\n\n \n ", "sub_path": "verses/management/commands/static_tag_data.py", "file_name": "static_tag_data.py", "file_ext": "py", "file_size_in_byte": 1255, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 6, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.conf.settings.BASE_DIR", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 10, "usage_type": "name"}, {"api_name": "json.load", "line_number": 11, "usage_type": "call"}, {"api_name": "verses.models.Tag1.objects.create", "line_number": 15, "usage_type": "call"}, {"api_name": "verses.models.Tag1.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "verses.models.Tag1", "line_number": 15, "usage_type": "name"}, {"api_name": "verses.models.Tag2.objects.create", "line_number": 20, "usage_type": "call"}, {"api_name": "verses.models.Tag2.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "verses.models.Tag2", "line_number": 20, "usage_type": "name"}, {"api_name": "verses.models.Tag3.objects.create", "line_number": 26, "usage_type": "call"}, {"api_name": "verses.models.Tag3.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "verses.models.Tag3", "line_number": 26, "usage_type": "name"}]} +{"seq_id": "203322197", "text": "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright 2015 by Ecpy Authors, see AUTHORS for more details.\n#\n# Distributed under the terms of the BSD license.\n#\n# The full license is in the file LICENCE, distributed with this software.\n# -----------------------------------------------------------------------------\n\"\"\"Test the capabilities of the execution editor model.\n\n\"\"\"\nfrom __future__ import (division, unicode_literals, print_function,\n absolute_import)\n\nfrom time import sleep\n\nimport pytest\nimport enaml\n\nfrom ecpy.utils.container_change import ContainerChange\nfrom ecpy.tasks.api import RootTask, ComplexTask, SimpleTask\nfrom ecpy.tasks.tasks.logic.loop_task import LoopTask\nfrom ecpy.measure.editors.api import Editor\nfrom ecpy.measure.editors.execution_editor.editor_model import\\\n ExecutionEditorModel\n\nfrom ecpy.testing.util import process_app_events\n\nwith enaml.imports():\n from ecpy.measure.editors.execution_editor import ExecutionEditor\n from ecpy.testing.windows import PageTestingWindow\n\n\n@pytest.fixture\ndef task():\n \"\"\"Create a basic task hierarchy for testing.\n\n \"\"\"\n root = RootTask()\n root.add_child_task(0, SimpleTask(name='simp1'))\n\n comp = ComplexTask(name='comp1',\n wait={'activated': True, 'no_wait': ['test']})\n comp.add_child_task(0, SimpleTask(name='simp2',\n parallel={'activated': True,\n 'pool': 'test'}))\n\n root.add_child_task(1, comp)\n return root\n\n\ndef test_model_observe_parallel(task):\n \"\"\"Test that the model is properly updated when the parallel setting of a\n task changes.\n\n \"\"\"\n model = ExecutionEditorModel(root=task)\n assert model.pools == ['test']\n\n task.children[0].parallel = {'activated': True, 'pool': 'test2'}\n assert 'test2' in model.pools\n\n task.children[0].parallel = {'activated': False, 'pool': 'test2'}\n assert 'test2' not in model.pools\n\n model.unbind_observers()\n task.children[0].parallel = {'activated': True, 'pool': 'test2'}\n assert 'test2' not in model.pools\n\n\ndef test_model_observe_wait(task):\n \"\"\"Test that the model is properly updated when the wait setting of a task\n change.\n\n \"\"\"\n model = ExecutionEditorModel(root=task)\n assert model.pools == ['test']\n\n child = task.children[1].children[0]\n\n child.wait = {'activated': True, 'wait': ['test2']}\n assert 'test2' in model.pools\n\n child.wait = {'activated': False, 'wait': ['test2']}\n assert 'test2' not in model.pools\n\n child.wait = {'activated': True, 'no_wait': ['test2']}\n assert 'test2' in model.pools\n\n child = task.children[1]\n\n child.wait = {'activated': True, 'wait': ['test3']}\n assert 'test3' in model.pools\n\n child.wait = {'activated': False, 'wait': ['test3']}\n assert 'test3' not in model.pools\n\n\ndef test_model_observe_child_member(task):\n \"\"\"Test that replacing a child does trigger the expected behavior.\n\n \"\"\"\n model = ExecutionEditorModel(root=task)\n assert model.pools == ['test']\n\n c = LoopTask(name='comp2', parallel={'activated': True,\n 'pool': 'test2'})\n task.add_child_task(2, c)\n assert 'test2' in model.pools\n\n c.children = [SimpleTask(name='simp3', parallel={'activated': True,\n 'pool': 'test3'})]\n assert 'test3' in model.pools\n\n c.children = []\n assert sorted(model.pools) == sorted(['test', 'test2'])\n\n c.task = SimpleTask(name='simp3', parallel={'activated': True,\n 'pool': 'test4'})\n assert 'test4' in model.pools\n\n c.task = None\n assert sorted(model.pools) == sorted(['test', 'test2'])\n\n\ndef test_model_observe_child_adding_removing(task):\n \"\"\"Test that adding removing a child does trigger the expected behavior.\n\n \"\"\"\n model = ExecutionEditorModel(root=task)\n assert model.pools == ['test']\n\n c = ComplexTask(name='comp2', parallel={'activated': True,\n 'pool': 'test2'})\n task.add_child_task(2, c)\n assert 'test2' in model.pools\n\n c.add_child_task(0, SimpleTask(name='simp3', parallel={'activated': True,\n 'pool': 'test3'}))\n assert 'test3' in model.pools\n\n task.move_child_task(2, 0)\n assert sorted(model.pools) == sorted(['test', 'test2', 'test3'])\n\n task.remove_child_task(0)\n assert model.pools == ['test']\n\n model.root = None\n task.children[0].parallel = {'activated': True, 'pool': 'test2'}\n assert 'test2' not in model.pools\n\n # For coverage\n notification = ContainerChange(collapsed=[ContainerChange()])\n model._child_notifier_observer(notification)\n\n\ndef test_execution_editor_widget(windows, task, dialog_sleep):\n \"\"\"Test the behavior of the execution editor widget.\n\n \"\"\"\n dialog_sleep = dialog_sleep or 1\n task.children[1].children[0].parallel = {}\n\n def get_task_widget(editor):\n return editor.page_widget().widgets()[0].scroll_widget().widgets()[0]\n\n editor = ExecutionEditor(declaration=Editor(id='ecpy.execution_editor'),\n selected_task=task)\n window = PageTestingWindow(widget=editor)\n window.show()\n process_app_events()\n sleep(dialog_sleep)\n\n ctask = task.children[1]\n editor.selected_task = ctask\n process_app_events()\n sleep(dialog_sleep)\n\n ced = get_task_widget(editor)\n ced.widgets()[0].checked = not ctask.stoppable\n process_app_events()\n assert ced.widgets()[0].checked == ctask.stoppable\n sleep(dialog_sleep)\n\n ctask.parallel['pool'] = 'test_'\n ced.widgets()[1].checked = True\n process_app_events()\n assert 'test_' in editor.pool_model.pools\n sleep(dialog_sleep)\n\n ced.widgets()[3].checked = False\n process_app_events()\n sleep(dialog_sleep)\n ctask.wait['no_wait'] = ['test2']\n ced.widgets()[3].checked = True\n process_app_events()\n assert 'test2' in editor.pool_model.pools\n sleep(dialog_sleep)\n\n ced.widgets()[2].selected = 'test2'\n process_app_events()\n assert 'test' not in editor.pool_model.pools\n sleep(dialog_sleep)\n\n def get_popup_content(parent):\n return parent.children[-1].central_widget().widgets()\n\n ced.widgets()[2].children[0].children[0].triggered = True\n process_app_events()\n sleep(dialog_sleep)\n process_app_events() # So that the popup shows correctly\n popup_content = get_popup_content(ced.widgets()[2])\n popup_content[0].text = 'test3'\n popup_content[1].clicked = True\n process_app_events()\n assert 'test3' in editor.pool_model.pools\n sleep(dialog_sleep)\n process_app_events() # So that the popup is closed correctly\n\n ced.widgets()[2].children[0].children[0].triggered = True\n process_app_events()\n sleep(dialog_sleep)\n process_app_events() # So that the popup shows correctly\n popup_content = get_popup_content(ced.widgets()[2])\n popup_content[0].text = 'test4'\n popup_content[2].clicked = True\n process_app_events()\n assert 'test4' not in editor.pool_model.pools\n sleep(dialog_sleep)\n process_app_events() # So that the popup is closed correctly\n\n assert ced.widgets()[4].checked is False\n ced.widgets()[4].checked = True\n process_app_events()\n assert 'wait' in ctask.wait and 'no_wait' not in ctask.wait\n sleep(dialog_sleep)\n\n ced.widgets()[7].clicked = True\n process_app_events()\n sleep(dialog_sleep)\n popup_content = get_popup_content(ced.widgets()[7])\n check_box = popup_content[0].scroll_widget().widgets()[1]\n assert not check_box.checked\n check_box.checked = True\n process_app_events()\n sleep(dialog_sleep)\n popup_content[-2].clicked = True\n process_app_events()\n assert 'test3' in ctask.wait['wait']\n sleep(dialog_sleep)\n\n ced.widgets()[7].clicked = True\n process_app_events()\n sleep(dialog_sleep)\n popup_content = get_popup_content(ced.widgets()[7])\n check_box = popup_content[0].scroll_widget().widgets()[2]\n assert not check_box.checked\n check_box.checked = True\n process_app_events()\n sleep(dialog_sleep)\n popup_content[-1].clicked = True\n process_app_events()\n assert 'test_' not in ctask.wait['wait']\n sleep(dialog_sleep)\n\n editor.selected_task = task\n task.remove_child_task(1)\n process_app_events()\n assert ctask not in editor._cache\n sleep(dialog_sleep)\n\n editor.ended = True\n", "sub_path": "tests/measure/editors/test_execution_editor.py", "file_name": "test_execution_editor.py", "file_ext": "py", "file_size_in_byte": 8587, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "enaml.imports", "line_number": 29, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.RootTask", "line_number": 39, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.SimpleTask", "line_number": 40, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.ComplexTask", "line_number": 42, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.SimpleTask", "line_number": 44, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 34, "usage_type": "attribute"}, {"api_name": "ecpy.measure.editors.execution_editor.editor_model.ExecutionEditorModel", "line_number": 57, "usage_type": "call"}, {"api_name": "ecpy.measure.editors.execution_editor.editor_model.ExecutionEditorModel", "line_number": 76, "usage_type": "call"}, {"api_name": "ecpy.measure.editors.execution_editor.editor_model.ExecutionEditorModel", "line_number": 103, "usage_type": "call"}, {"api_name": "ecpy.tasks.tasks.logic.loop_task.LoopTask", "line_number": 106, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.SimpleTask", "line_number": 111, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.SimpleTask", "line_number": 118, "usage_type": "call"}, {"api_name": "ecpy.measure.editors.execution_editor.editor_model.ExecutionEditorModel", "line_number": 130, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.ComplexTask", "line_number": 133, "usage_type": "call"}, {"api_name": "ecpy.tasks.api.SimpleTask", "line_number": 138, "usage_type": "call"}, {"api_name": "ecpy.utils.container_change.ContainerChange", "line_number": 153, "usage_type": "call"}, {"api_name": "ecpy.measure.editors.execution_editor.ExecutionEditor", "line_number": 167, "usage_type": "call"}, {"api_name": "ecpy.measure.editors.api.Editor", "line_number": 167, "usage_type": "call"}, {"api_name": "ecpy.testing.windows.PageTestingWindow", "line_number": 169, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 171, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 172, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 176, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 177, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 181, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 183, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 187, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 189, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 192, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 193, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 196, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 198, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 201, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 203, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 209, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 210, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 211, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 215, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 217, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 218, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 221, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 222, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 223, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 227, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 229, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 230, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 234, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 236, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 239, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 240, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 245, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 246, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 248, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 250, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 253, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 254, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 259, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 260, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 262, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 264, "usage_type": "call"}, {"api_name": "ecpy.testing.util.process_app_events", "line_number": 268, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 270, "usage_type": "call"}]} +{"seq_id": "577654080", "text": "# -*- coding: utf-8 -*-\nfrom urllib.parse import unquote\nfrom flask import Flask,jsonify\nfrom other_api import request\n\napp = Flask(__name__)\n\nplayers_list = request.get_players_list()\n\n\n# poem = request.poem()\n# @app.route('/1627406006')\n# def poem():\n# return jsonify(poem)\n\n@app.route('/1627406006/')\ndef idiom(id):\n player_data = ''\n if id < 0 or id >= len(players_list):\n return \"id should be within 0 - {0}\".format(len(players_list))\n if id < len(players_list):\n player_data = request.get_player_detail(players_list[id])\n return jsonify(player_data)\n\n\n\nif __name__ == '__main__':\n app.run()\n", "sub_path": "flask_api/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 638, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "other_api.request.get_players_list", "line_number": 8, "usage_type": "call"}, {"api_name": "other_api.request", "line_number": 8, "usage_type": "name"}, {"api_name": "other_api.request.get_player_detail", "line_number": 22, "usage_type": "call"}, {"api_name": "other_api.request", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "44242365", "text": "import threading\nimport asyncio\nfrom typing import Dict, Union, List\nfrom unified_message_relay.Core.UMRType import UnifiedMessage, MessageEntity, ChatAttribute, ChatType, EntityType\nfrom unified_message_relay.Core import UMRDriver\nfrom unified_message_relay.Core import UMRLogging\nfrom unified_message_relay.Core import UMRConfig\nfrom unified_message_relay.Core.UMRMessageRelation import set_ingress_message_id, set_egress_message_id\nfrom unified_message_relay.Util.Helper import unparse_entities_to_markdown, escape_markdown\nfrom typing_extensions import Literal\nimport discord\nimport re\n\n\nbold_text = re.compile(r'(?:(?<=^)|(?<=[^*]))\\*\\*(.*?)\\*\\*(?:(?=$)|(?=[^*]))', re.RegexFlag.DOTALL)\nunderline_text = re.compile(r'(?:(?<=^)|(?<=[^_]))__(.*?)__(?:(?=$)|(?=[^_]))', re.RegexFlag.DOTALL)\nstrikethrough_text = re.compile(r'(?:(?<=^)|(?<=[^~]))~~(.*?)~~(?:(?=$)|(?=[^~]))', re.RegexFlag.DOTALL)\nitalic_text1 = re.compile(r'(?:(?<=^)|(?<=[^*]))\\*(.*?)\\*(?:(?=$)|(?=[^*]))', re.RegexFlag.DOTALL)\nitalic_text2 = re.compile(r'(?:(?<=^)|(?<=[^_]))_(.*?)_(?:(?=$)|(?=[^_]))', re.RegexFlag.DOTALL)\ncode_text = re.compile(r'(?:(?<=^)|(?<=[^`]))`(.*?)`(?:(?=$)|(?=[^`]))', re.RegexFlag.DOTALL)\ncode_block_text = re.compile(r'(?:(?<=^)|(?<=[^`]))```(.*?)```(?:(?=$)|(?=[^`]))', re.RegexFlag.DOTALL)\nquote_block_text = re.compile(r'^>>> (.*)', re.RegexFlag.DOTALL)\nquote_text = re.compile(r'^> (.*)')\nat_user_text = re.compile(r'<@(\\d+)>')\n\nordered_match_list = [\n (quote_block_text, EntityType.QUOTE_BLOCK),\n (quote_text, EntityType.QUOTE),\n (code_block_text, EntityType.CODE_BLOCK),\n (code_text, EntityType.CODE),\n (bold_text, EntityType.BOLD),\n (underline_text, EntityType.UNDERLINE),\n (strikethrough_text, EntityType.STRIKETHROUGH),\n (italic_text1, EntityType.ITALIC),\n (italic_text2, EntityType.ITALIC)\n]\n\n\ndef find_markdown(text: str, text_start: int = 0, text_end=-1, real_start: int = 0) -> (str, List[MessageEntity]):\n \"\"\"\n find nearest markdown block\n :param real_start: offset in plain text\n :param text_start: start pos in markdown text\n :param text_end: end pos in markdown text\n :param text: whole markdown text\n :return: matched_text, entity_list\n \"\"\"\n if text_end == -1:\n text_end = len(text)\n\n pos_list = list()\n entity_list: List[MessageEntity] = list()\n result = ''\n while True:\n pos_list.clear()\n text_slice = text[text_start:text_end]\n for regex_matcher, entity_type in ordered_match_list:\n try:\n _result = next(regex_matcher.finditer(text_slice))\n pos_list.append((_result, entity_type))\n except StopIteration:\n pass\n\n if not pos_list:\n return result + text_slice, entity_list\n\n match, entity_type = min(pos_list, key=lambda x: x[0].span(0)[0])\n outer_start = match.span(0)[0] + text_start\n outer_end = match.span(0)[1] + text_start\n inner_start = match.span(1)[0] + text_start\n inner_end = match.span(1)[1] + text_start\n delta = text[text_start:outer_start]\n real_start = real_start + len(delta)\n result += delta\n\n if entity_type not in (EntityType.CODE, EntityType.CODE_BLOCK):\n delta, _entity_list = find_markdown(text, inner_start, inner_end, real_start)\n else:\n delta = text[inner_start:inner_end]\n _entity_list = list()\n\n message_entity = MessageEntity(start=real_start,\n end=real_start + len(delta),\n entity_type=entity_type)\n entity_list.append(message_entity)\n real_start = real_start + len(delta)\n result += delta\n entity_list.extend(_entity_list)\n\n text_start = outer_end\n\n\nclass DiscordDriverConfig(UMRConfig.BaseDriverConfig):\n Base: Literal['Discord']\n BotToken: str\n ClientToken: str\n\n\nUMRConfig.register_driver_config(DiscordDriverConfig)\n\n\nclass DiscordDriver(UMRDriver.BaseDriverMixin, discord.Client):\n def __init__(self, name: str):\n self.loop = asyncio.new_event_loop()\n self.loop.set_exception_handler(self.handle_exception)\n discord.Client.__init__(self, loop=self.loop)\n\n self.name = name\n self.logger = UMRLogging.get_logger(self.name)\n\n self.config: DiscordDriverConfig = UMRConfig.config.Driver[self.name]\n\n def start(self):\n def run():\n nonlocal self\n self.logger.debug('Running start')\n asyncio.set_event_loop(self.loop)\n self.run(self.config.BotToken)\n\n t = threading.Thread(target=run)\n t.daemon = True\n UMRDriver.threads.append(t)\n t.start()\n\n self.logger.debug(f'Finished initialization')\n\n def run(self, *args, **kwargs):\n \"\"\"\n monkey patched start\n \"\"\"\n loop = self.loop\n\n async def runner():\n try:\n await discord.Client.start(self, *args, **kwargs)\n finally:\n await self.close()\n\n def stop_loop_on_completion(f):\n loop.stop()\n\n future = asyncio.ensure_future(runner(), loop=loop)\n future.add_done_callback(stop_loop_on_completion)\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n self.logger.info('Received signal to terminate bot and event loop.')\n finally:\n future.remove_done_callback(stop_loop_on_completion)\n self.logger.info('Cleaning up tasks.')\n discord.client._cleanup_loop(loop)\n\n if not future.cancelled():\n return future.result()\n\n async def on_ready(self):\n self.logger.info('Logged on as ' + str(self.user))\n\n async def on_message(self, message: discord.Message):\n # don't respond to ourselves\n if message.author == self.user:\n return\n\n self.logger.debug(message)\n\n if isinstance(message.author, discord.User):\n from_user = message.author.display_name\n user_id = message.author.id\n elif isinstance(message.author, discord.Member):\n from_user = message.author.display_name\n user_id = message.author.id\n else:\n self.logger.debug(f'Unseen user type: {str(message.author)}')\n from_user = message.author.display_name\n user_id = message.author.id\n\n if isinstance(message.channel, discord.DMChannel):\n _chat_type = ChatType.PRIVATE\n elif isinstance(message.channel, discord.GroupChannel):\n _chat_type = ChatType.GROUP\n elif isinstance(message.channel, discord.TextChannel):\n _chat_type = ChatType.GROUP\n else:\n self.logger.warning('Unsupported channel type')\n return\n\n chat_id = message.channel.id\n\n unified_message = UnifiedMessage(platform=self.name,\n chat_id=chat_id,\n chat_type=_chat_type,\n name=from_user,\n user_id=user_id,\n message_id=message.id)\n\n message_content = await self.parse_at(message.content)\n unified_message.text, unified_message.text_entities = find_markdown(message_content.replace('\\u200b', ''))\n\n if message.attachments:\n if message.attachments[0].proxy_url:\n unified_message.image = message.attachments[0].proxy_url\n if len(message.attachments) > 1:\n self.logger.warning('More than one attachment detected, not sure how it happens')\n\n set_ingress_message_id(src_platform=self.name, src_chat_id=chat_id, src_chat_type=_chat_type,\n src_message_id=message.id, user_id=user_id)\n\n await self.receive(unified_message)\n\n async def parse_at(self, message: str):\n user_ids = at_user_text.findall(message)\n if not user_ids:\n return message\n user_name_map = dict()\n for i in user_ids:\n try:\n user_id = int(i)\n user_name_map[user_id] = self.get_user(user_id).display_name\n except:\n pass\n\n def sub_username(match_obj):\n try:\n user_id = int(match_obj.group(1))\n return '@' + user_name_map[user_id]\n except:\n pass\n return '@unknown'\n\n message = at_user_text.sub(sub_username, message)\n return message\n\n\n async def send(self, to_chat: Union[int, str], chat_type: ChatType, message: UnifiedMessage):\n \"\"\"\n decorator for send new message\n :return:\n \"\"\"\n self.logger.debug('calling real send')\n return asyncio.run_coroutine_threadsafe(self._send(to_chat, chat_type, message), self.loop)\n\n async def _send(self, to_chat: int, chat_type: ChatType, message: UnifiedMessage):\n \"\"\"\n decorator for send new message\n :return:\n \"\"\"\n\n channel = self.get_channel(to_chat)\n if not channel:\n self.logger.error(f'Chat {to_chat} not found, please check your configuration')\n\n message_text = ''\n\n # name logic\n if message.chat_attrs.name:\n message_text += '**' + escape_markdown(message.chat_attrs.name) + '**\\u200b'\n if message.chat_attrs.reply_to:\n message_text += '** (➡️️' + message.chat_attrs.reply_to.name + ')**\\u200b'\n if message.chat_attrs.forward_from:\n message_text += '** (️️↩️' + message.chat_attrs.forward_from.name + ')**\\u200b'\n if message.chat_attrs.name:\n message_text += '**: **\\u200b'\n\n # at user\n if message.send_action.user_id:\n message_text += f'<@{message.send_action.user_id}> '\n\n message_text += unparse_entities_to_markdown(message,\n EntityType.PLAIN | EntityType.BOLD | EntityType.ITALIC |\n EntityType.CODE | EntityType.STRIKETHROUGH | EntityType.UNDERLINE |\n EntityType.CODE_BLOCK | EntityType.QUOTE | EntityType.QUOTE_BLOCK)\n\n if message.image:\n assert isinstance(channel, discord.TextChannel)\n outbound_message = await channel.send(content=message_text, file=discord.File(message.image))\n else:\n outbound_message = await channel.send(content=message_text)\n\n if message.chat_attrs:\n set_egress_message_id(src_platform=message.chat_attrs.platform,\n src_chat_id=message.chat_attrs.chat_id,\n src_chat_type=message.chat_attrs.chat_type,\n src_message_id=message.chat_attrs.message_id,\n dst_platform=self.name,\n dst_chat_id=to_chat,\n dst_chat_type=chat_type,\n dst_message_id=outbound_message.id, # useless message id\n user_id=0)\n\n def handle_exception(self, loop, context):\n # context[\"message\"] will always be there; but context[\"exception\"] may not\n msg = context.get(\"exception\", context[\"message\"])\n self.logger.exception('Unhandled exception: ', exc_info=msg)\n\n\nUMRDriver.register_driver('Discord', DiscordDriver)\n", "sub_path": "umr_discord_driver/driver.py", "file_name": "driver.py", "file_ext": "py", "file_size_in_byte": 11562, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "re.compile", "line_number": 15, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 15, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 16, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 16, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 17, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 17, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 18, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 18, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 19, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 19, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 20, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 20, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 21, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 21, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 22, "usage_type": "call"}, {"api_name": "re.RegexFlag", "line_number": 22, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 23, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 24, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.QUOTE_BLOCK", "line_number": 27, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 27, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.QUOTE", "line_number": 28, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 28, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE_BLOCK", "line_number": 29, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 29, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 30, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.BOLD", "line_number": 31, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 31, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.UNDERLINE", "line_number": 32, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 32, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.STRIKETHROUGH", "line_number": 33, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 33, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.ITALIC", "line_number": 34, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 34, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.ITALIC", "line_number": 35, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.MessageEntity", "line_number": 52, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE", "line_number": 76, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 76, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE_BLOCK", "line_number": 76, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.MessageEntity", "line_number": 82, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 39, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.MessageEntity", "line_number": 39, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRConfig.BaseDriverConfig", "line_number": 93, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRConfig", "line_number": 93, "usage_type": "name"}, {"api_name": "typing_extensions.Literal", "line_number": 94, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRConfig.register_driver_config", "line_number": 99, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRConfig", "line_number": 99, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRDriver.BaseDriverMixin", "line_number": 102, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRDriver", "line_number": 102, "usage_type": "name"}, {"api_name": "discord.Client", "line_number": 102, "usage_type": "attribute"}, {"api_name": "asyncio.new_event_loop", "line_number": 104, "usage_type": "call"}, {"api_name": "discord.Client.__init__", "line_number": 106, "usage_type": "call"}, {"api_name": "discord.Client", "line_number": 106, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRLogging.get_logger", "line_number": 109, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRLogging", "line_number": 109, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRConfig.config", "line_number": 111, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRConfig", "line_number": 111, "usage_type": "name"}, {"api_name": "asyncio.set_event_loop", "line_number": 117, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 120, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRDriver.threads.append", "line_number": 122, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRDriver.threads", "line_number": 122, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRDriver", "line_number": 122, "usage_type": "name"}, {"api_name": "discord.Client.start", "line_number": 135, "usage_type": "call"}, {"api_name": "discord.Client", "line_number": 135, "usage_type": "attribute"}, {"api_name": "asyncio.ensure_future", "line_number": 142, "usage_type": "call"}, {"api_name": "discord.client._cleanup_loop", "line_number": 151, "usage_type": "call"}, {"api_name": "discord.client", "line_number": 151, "usage_type": "attribute"}, {"api_name": "discord.Message", "line_number": 159, "usage_type": "attribute"}, {"api_name": "discord.User", "line_number": 166, "usage_type": "attribute"}, {"api_name": "discord.Member", "line_number": 169, "usage_type": "attribute"}, {"api_name": "discord.DMChannel", "line_number": 177, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType.PRIVATE", "line_number": 178, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType", "line_number": 178, "usage_type": "name"}, {"api_name": "discord.GroupChannel", "line_number": 179, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType.GROUP", "line_number": 180, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType", "line_number": 180, "usage_type": "name"}, {"api_name": "discord.TextChannel", "line_number": 181, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType.GROUP", "line_number": 182, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType", "line_number": 182, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.UnifiedMessage", "line_number": 189, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRMessageRelation.set_ingress_message_id", "line_number": 205, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 234, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType", "line_number": 234, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.UnifiedMessage", "line_number": 234, "usage_type": "name"}, {"api_name": "asyncio.run_coroutine_threadsafe", "line_number": 240, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRType.ChatType", "line_number": 242, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.UnifiedMessage", "line_number": 242, "usage_type": "name"}, {"api_name": "unified_message_relay.Util.Helper.escape_markdown", "line_number": 256, "usage_type": "call"}, {"api_name": "unified_message_relay.Util.Helper.unparse_entities_to_markdown", "line_number": 268, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.PLAIN", "line_number": 269, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 269, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.BOLD", "line_number": 269, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.ITALIC", "line_number": 269, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE", "line_number": 270, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 270, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.STRIKETHROUGH", "line_number": 270, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.UNDERLINE", "line_number": 270, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.CODE_BLOCK", "line_number": 271, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType", "line_number": 271, "usage_type": "name"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.QUOTE", "line_number": 271, "usage_type": "attribute"}, {"api_name": "unified_message_relay.Core.UMRType.EntityType.QUOTE_BLOCK", "line_number": 271, "usage_type": "attribute"}, {"api_name": "discord.TextChannel", "line_number": 274, "usage_type": "attribute"}, {"api_name": "discord.File", "line_number": 275, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRMessageRelation.set_egress_message_id", "line_number": 280, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRDriver.register_driver", "line_number": 296, "usage_type": "call"}, {"api_name": "unified_message_relay.Core.UMRDriver", "line_number": 296, "usage_type": "name"}]} +{"seq_id": "139752007", "text": "import re\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.wait import WebDriverWait\r\n\r\nfrom win10toast import ToastNotifier\r\n\r\ntoaster = ToastNotifier()\r\n\r\n\r\nclass GroupAuto():\r\n \"\"\"Auto post on all facebook groups using\r\n selenium python.\r\n\r\n Attributes:\r\n browser (TYPE): webdrive.Chrome\r\n URL (str): mbasic URL of facebook\r\n group_elem (TYPE): group elements by xpath\r\n login_elem (TYPE): login elements by xpath\r\n \"\"\"\r\n\r\n def __init__(self, hide=False):\r\n \"\"\"Initialize webdriver\r\n\r\n Args:\r\n hide (bool, optional): Display or hide\r\n browser\r\n \"\"\"\r\n super(GroupAuto, self).__init__()\r\n self.browser = webdriver.Chrome()\r\n\r\n self.URL = \"https://mbasic.facebook.com\"\r\n\r\n # login xpath collection\r\n self.login_elem = {\r\n \"user_input\": \"//input[@id='m_login_email']\",\r\n \"pass_input\": \"//input[@name='pass']\",\r\n \"login_btn\": \"//input[@value='Log In']\",\r\n }\r\n\r\n # group xpath collection\r\n self.group_elem = {\r\n \"post_textarea\": \"//textarea[@id='u_0_0']\",\r\n \"post_btn\": \"//input[@value='Post']\"\r\n }\r\n\r\n def login(self, username, password):\r\n \"\"\"Login facebook account\r\n\r\n Args:\r\n username (STRING): fb username\r\n password (STRING): fb password\r\n \"\"\"\r\n self.browser.get(self.URL)\r\n\r\n usr = self.browser.find_element_by_xpath(\r\n self.login_elem['user_input']\r\n )\r\n\r\n pwd = self.browser.find_element_by_xpath(\r\n self.login_elem['pass_input']\r\n )\r\n\r\n btn = self.browser.find_element_by_xpath(\r\n self.login_elem['login_btn']\r\n )\r\n\r\n # login user\r\n\r\n usr.send_keys(username)\r\n pwd.send_keys(password)\r\n btn.click()\r\n\r\n # wait for login button to disappear\r\n try:\r\n WebDriverWait(self.browser, 15).until_not(\r\n EC.presence_of_element_located((\r\n By.XPATH,\r\n self.login_elem['login_btn'])\r\n ))\r\n\r\n toaster.show_toast(\r\n \"Menudo.Space: FBAuto\",\r\n \"Sucessfully logged in.\",\r\n duration=3\r\n )\r\n\r\n except TimeoutException:\r\n print(\"Error: Invalid Credentials.\")\r\n self.browser.quit()\r\n\r\n def get_groups(self, limit=None):\r\n \"\"\"Get all groups in your facebook\r\n\r\n Args:\r\n limit (None, optional): Number of groups\r\n to be returned\r\n\r\n Returns:\r\n LIST: A list of group URLs\r\n \"\"\"\r\n self.browser.get(self.URL + \"/groups/?seemore\")\r\n\r\n try:\r\n WebDriverWait(self.browser, 3).until(\r\n EC.presence_of_element_located((\r\n By.XPATH,\r\n \"//h3[@class='br']\")\r\n ))\r\n except TimeoutException as e:\r\n # print(\"Error: Can't go to 'see all groups'\")\r\n # toaster.show_toast(\r\n # \"Menudo.Space: FBAuto\",\r\n # \"No groups found.\",\r\n # duration=3\r\n # )\r\n # self.browser.quit()\r\n raise e\r\n\r\n # extract all groups\r\n soup = BeautifulSoup(self.browser.page_source,\r\n \"html.parser\")\r\n\r\n groups = soup.find_all(\r\n \"a\", href=re.compile(r\"groups/\\d\"))\r\n\r\n # return all group URLs\r\n if groups:\r\n toaster.show_toast(\r\n \"Menudo.Space: FBAuto\",\r\n f\"{len([x['href'] for x in groups[:limit]])}. Grups\",\r\n duration=3\r\n )\r\n return [x['href'] for x in groups[:limit]]\r\n\r\n def post(self, groups, description, interval, debug=False):\r\n \"\"\"Post to groups in facebook. Use at your own risk.\r\n\r\n Args:\r\n groups (List): A list of group URLs\r\n description (String): Words to post in group\r\n interval (Int): Time interval to post\r\n \"\"\"\r\n for idx, group in enumerate(groups):\r\n self.browser.get(self.URL + group)\r\n\r\n # Wait for text area to appear\r\n try:\r\n WebDriverWait(self.browser, 15).until(\r\n EC.presence_of_element_located((\r\n By.XPATH,\r\n self.group_elem['post_textarea'])\r\n ))\r\n except TimeoutException:\r\n continue # Skip if not found\r\n\r\n post = self.browser.find_element_by_xpath(\r\n self.group_elem['post_textarea']\r\n )\r\n\r\n btn = self.browser.find_element_by_xpath(\r\n self.group_elem['post_btn']\r\n )\r\n\r\n post.send_keys(description)\r\n toaster.show_toast(\r\n \"Menudo.Space: FBAuto\",\r\n f\"Posted in group {idx+1} of {len(groups)+1}\",\r\n duration=3\r\n )\r\n\r\n time.sleep(interval)\r\n\r\n if not debug:\r\n btn.click()\r\n", "sub_path": "FACEBOT/facebook.py", "file_name": "facebook.py", "file_ext": "py", "file_size_in_byte": 5358, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "win10toast.ToastNotifier", "line_number": 12, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 34, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 34, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 80, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 81, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 81, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 82, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 82, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 92, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 109, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 110, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 110, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 111, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 111, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 114, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 125, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 129, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 153, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 154, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 154, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 155, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 155, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 158, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 176, "usage_type": "call"}]} +{"seq_id": "516401919", "text": "import requests\n\nurl = \"http://api.openweathermap.org/data/2.5/forecast/daily\"\n\nquerystring = {\"q\":\"London\",\"mode\":\"json\",\"units\":\"metric\",\"cnt\":\"7\",\"APPID\":\"8467a853ab76a8e415b8e7d11f6694a0\"}\n\n\nresponse = requests.request(\"GET\", url, params=querystring)\n\nprint(response.text)", "sub_path": "Code/16day_daily.py", "file_name": "16day_daily.py", "file_ext": "py", "file_size_in_byte": 276, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.request", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "83294598", "text": "from sys import stdout\nfrom datetime import datetime\nfrom time import sleep\nimport pandas as pd\nfrom math import floor\n_map = map\n\nSECONDS_IN_A_DAY = 60.0 * 60.0 * 24.0\n\n\ndef elapsed(start_time, end_time):\n\tdelta = end_time - start_time\n\treturn delta.days * SECONDS_IN_A_DAY + delta.seconds + delta.microseconds / 1E6\n\n\ntry:\n\tfrom slytherin.colour import colour\nexcept ModuleNotFoundError:\n\tfrom .colour import colour\n\n\nclass ProgressBar:\n\tdef __init__(\n\t\t\tself, total, bar_length=20, animation='clock',\n\t\t\tfull_colour='blue', empty_colour='grey', text_colour='grey', next_line=True,\n\t\t\techo=1, parent=None, disappear=False, display_wait=0.5,\n\t\t\tbar_characters=None\n\t):\n\t\t\"\"\"\n\t\t:type total: int or float or NoneType\n\t\t:type bar_length: int\n\t\t:type bar_full: str\n\t\t:type bar_empty: str\n\t\t:type animation: str\n\t\t:type full_colour: str\n\t\t:type empty_colour: str\n\t\t:type text_colour: str\n\t\t:type next_line: bool\n\t\t:type echo: int or bool\n\t\t:type parent: ProgressBar or NoneType\n\t\t:type display_wait: float or int\n\t\t\"\"\"\n\t\tself._total = total\n\t\tself._amount = None\n\t\tself._safe_total = total\n\t\tself._bar_characters = bar_characters or self.FILLING_SQUARE\n\t\tself._shown = 0\n\t\tself.amount = 0\n\n\t\tself._bar_length = bar_length\n\t\tself._start_time = datetime.now()\n\t\tself._animation_counter = -1\n\t\tif animation == 'vertical_bar':\n\t\t\tanimation_clips = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']\n\t\t\tanimation_clips = animation_clips + animation_clips[::-1]\n\t\telif animation == 'ball':\n\t\t\tanimation_clips = ['⠁', '⠂', '⠄', '⡀', '⢀', '⠠', '⠐', '⠈']\n\t\telif animation == 'clock':\n\t\t\tanimation_clips = ['🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕛']\n\t\telif animation == 'big_ball':\n\t\t\tanimation_clips = ['● ', '● ', ' ● ', ' ● ', ' ● ', ' ● ', ' ● ', ' ●', ' ●']\n\t\t\tanimation_clips = animation_clips + animation_clips[::-1]\n\t\telif animation == 'line':\n\t\t\tanimation_clips = ['\\\\', '|', '/', '-']\n\t\telse:\n\t\t\tanimation_clips = None\n\t\tself._animation_clips = animation_clips\n\t\tself._full_colour = full_colour\n\t\tself._empty_colour = empty_colour\n\t\tself._text_colour = text_colour\n\t\tself._next_line = next_line\n\t\tself._disappear = disappear\n\t\tself._completed = False\n\t\tself._display_wait = display_wait\n\t\tself._display_time = datetime.now()\n\n\t\tif isinstance(echo, self.__class__):\n\t\t\tself._echo = echo._echo\n\t\t\tself._parent = echo\n\t\t\tself._next_line = False\n\t\telse:\n\t\t\tself._echo = max(echo, 0)\n\t\t\tself._parent = None\n\n\t\tif parent is not None:\n\t\t\tself._parent = parent\n\t\t\tself._next_line = False\n\n\t\tself._last_text = ''\n\t\tself._last_formatted_bar = ''\n\n\t\tif self._parent:\n\t\t\tself._max_lengths = self._parent._max_lengths\n\t\telse:\n\t\t\tself._max_lengths = {\n\t\t\t\t'animation': 0, 'elapsed': 0, 'remaining': 0, 'text': 0, 'percent': 0, 'with_colour': 0\n\t\t\t}\n\n\tdef __sub__(self, other):\n\t\tif isinstance(other, int):\n\t\t\tresult = self.__class__(total=self._total, full_colour='green', echo=self._echo - other, parent=self, next_line=False)\n\t\t\tresult._amount = self._amount\n\t\t\treturn result\n\t\telse:\n\t\t\traise TypeError('subtract only works with integers')\n\n\tdef set_total(self, total):\n\t\tself._total = total\n\t\treturn self\n\n\t@property\n\tdef animation(self):\n\t\tif self._animation_clips is None:\n\t\t\treturn ''\n\t\telse:\n\t\t\tself._animation_counter += 1\n\t\t\treturn self._animation_clips[self._animation_counter % len(self._animation_clips)] + ' '\n\n\tdef complete(self):\n\t\tself._completed = True\n\n\t@property\n\tdef completed(self):\n\t\treturn self._completed\n\n\t@property\n\tdef total(self):\n\t\treturn self._safe_total\n\n\t@property\n\tdef amount(self):\n\t\treturn self._amount\n\n\t@amount.setter\n\tdef amount(self, amount):\n\t\ttry:\n\t\t\tself._amount = min(amount, self._total)\n\t\texcept TypeError:\n\t\t\tself._amount = amount\n\t\tself._safe_total = self._total or (amount + 10)\n\n\t@property\n\tdef percent(self):\n\t\tif self._parent:\n\t\t\treturn self._parent.percent\n\n\t\ttry:\n\t\t\treturn self.amount / self.total * 100\n\t\texcept ZeroDivisionError:\n\t\t\tif self._parent:\n\t\t\t\treturn self._parent.percent\n\t\t\telse:\n\t\t\t\treturn 0\n\t\texcept TypeError:\n\t\t\tif self._parent:\n\t\t\t\treturn self._parent.percent\n\t\t\telse:\n\t\t\t\treturn 0\n\n\t@property\n\tdef percent_formatted(self):\n\t\tformatted_percent = '{0: >#06.2f}'.format(float(self.percent)) + '%'\n\t\treturn formatted_percent\n\n\t@property\n\tdef elapsed_seconds(self):\n\t\tif self._parent:\n\t\t\treturn self._parent.elapsed_seconds\n\t\tdelta = datetime.now() - self._start_time\n\t\tdelta_seconds = delta.seconds + delta.microseconds / 1E6\n\t\treturn delta_seconds\n\n\t@property\n\tdef remaining_seconds(self):\n\t\tif self._parent:\n\t\t\treturn self._parent.remaining_seconds\n\n\t\tdelta_seconds = self.elapsed_seconds\n\n\t\ttry:\n\t\t\tspeed = self.amount / delta_seconds\n\n\t\t\tif self.amount >= self.total:\n\t\t\t\treturn 0\n\n\t\t\telse:\n\t\t\t\tif speed == 0 or speed is None:\n\t\t\t\t\treturn None\n\t\t\t\telse:\n\t\t\t\t\treturn (self.total - self.amount) / speed\n\n\t\texcept ZeroDivisionError:\n\t\t\treturn None\n\t\texcept TypeError:\n\t\t\treturn None\n\n\t@staticmethod\n\tdef format_time(time):\n\t\t\"\"\"\n\t\t:type time: float or int\n\t\t:rtype: str\n\t\t\"\"\"\n\t\t# convert to the right unit\n\t\tif time is None:\n\t\t\treturn ''\n\t\telse:\n\t\t\tif time > 3600:\n\t\t\t\tunit = 'h'\n\t\t\t\ttime = time / 3600\n\t\t\telif time > 60:\n\t\t\t\tunit = 'm'\n\t\t\t\ttime = time / 60\n\t\t\telse:\n\t\t\t\tunit = 's'\n\t\t\t\ttime = time\n\n\t\t\treturn '{0: >#04.1f}'.format(float(time)) + unit\n\n\tFADE_CHARACTERS = [' ', '░', '▒', '▓', '█']\n\tLEFT_TO_RIGHT_GROWTH = [\" \", \"▏\", \"▎\", \"▍\", \"▋\", \"▊\", \"▉\"]\n\tFOUR_SQUARES = [' ', '▖', '▞', '▛', '▉']\n\tFILLING_SQUARE = ['◻', '▢', '▧', '▨', '▦', '▩', '◼']\n\n\t@property\n\tdef bar(self):\n\t\t\"\"\"\n\t\t:rtype: str\n\t\t\"\"\"\n\n\t\tif self.total == 0 or self.amount is None or self.total is None:\n\t\t\tfull_part_len = 0\n\t\t\tpartial_character = ''\n\t\telse:\n\t\t\tbar_length = self.amount*self._bar_length / self.total\n\t\t\tfull_part_len = floor(bar_length)\n\t\t\tpartial_part = bar_length - full_part_len\n\t\t\tif full_part_len < bar_length:\n\t\t\t\tpartial_character = self._bar_characters[round(partial_part*(len(self._bar_characters)-1))]\n\t\t\telse:\n\t\t\t\tpartial_character = ''\n\n\t\tempty_part_len = self._bar_length - full_part_len - len(partial_character)\n\n\n\t\tfull_part_text = self._bar_characters[-1] * full_part_len + partial_character\n\t\tempty_part_text = self._bar_characters[0] * empty_part_len\n\n\t\tif self._full_colour is not None:\n\t\t\tcharacter = '▅' # character = self._bar_empty\n\t\t\tfull_part = colour(text=full_part_text, text_colour=self._full_colour)\n\t\t\tempty_part = colour(text=empty_part_text, text_colour=self._empty_colour)\n\t\telse:\n\t\t\tfull_part = full_part_text\n\t\t\tempty_part = empty_part_text\n\n\t\treturn full_part + empty_part\n\n\t@staticmethod\n\tdef write(string, flush=True):\n\t\t\"\"\"\n\t\t:type string: str\n\t\t\"\"\"\n\t\tstdout.write('\\r'+string)\n\t\tif flush:\n\t\t\tstdout.flush()\n\n\t@property\n\tdef _animation_string(self):\n\t\tanimation = self.animation\n\t\tself._max_lengths['animation'] = max(self._max_lengths['animation'], len(animation))\n\t\treturn colour(text=animation.ljust(self._max_lengths['animation']), text_colour=self._empty_colour)\n\n\t@property\n\tdef _elapsed_time_string(self):\n\t\telapsed_text = f'e:{self.format_time(self.elapsed_seconds)} '\n\t\tself._max_lengths['elapsed'] = max(self._max_lengths['elapsed'], len(elapsed_text))\n\t\telapsed_text = elapsed_text.ljust(self._max_lengths['elapsed'])\n\t\treturn colour(text=elapsed_text, text_colour=self._full_colour)\n\n\t@property\n\tdef _remaining_time_string(self):\n\t\tremaining_text = f'r:{self.format_time(self.remaining_seconds)} '\n\t\tself._max_lengths['remaining'] = max(self._max_lengths['remaining'], len(remaining_text))\n\t\tremaining_text = remaining_text.ljust(self._max_lengths['remaining'])\n\t\treturn colour(text=remaining_text, text_colour=self._empty_colour)\n\n\t@property\n\tdef _percent_string(self):\n\t\tpercent_text = f' {self.percent_formatted}'\n\t\tself._max_lengths['percent'] = max(self._max_lengths['percent'], len(percent_text))\n\t\tpercent_text = percent_text.rjust(self._max_lengths['percent'])\n\t\treturn colour(text=percent_text, text_colour=self._full_colour)\n\n\tdef _get_text_string(self, text):\n\t\ttext_text = f' {text}'\n\t\tself._max_lengths['text'] = max(self._max_lengths['text'], len(text_text))\n\t\ttext_text = text_text.ljust(self._max_lengths['text'])\n\t\treturn colour(text=text_text, text_colour=self._text_colour)\n\n\t@property\n\tdef _main_bar(self):\n\t\tif self._parent:\n\t\t\treturn self._parent\n\t\telse:\n\t\t\treturn self\n\n\tdef show(self, amount, total=None, extra_amount=0, percent=True, bar=True, time=True, text=''):\n\t\t\"\"\"\n\t\t:type amount: int or float or NoneType\n\t\t:type total: NoneType or float\n\t\t:type extra_amount: int or float or NoneType\n\t\t:type percent: bool\n\t\t:type bar: bool\n\t\t:type time: bool\n\t\t:type text: str\n\t\t\"\"\"\n\t\tif total is not None:\n\t\t\tself.set_total(total=total)\n\n\t\tif amount is not None:\n\t\t\tself.amount = amount + extra_amount\n\t\telse:\n\t\t\tself.amount = amount\n\n\t\tif self._echo:\n\t\t\ttime_now = datetime.now()\n\t\t\tif self._shown < 1 or elapsed(start_time=self._display_time, end_time=time_now) > self._display_wait or self.amount >= self.total:\n\t\t\t\tself._shown += 1\n\t\t\t\tself._display_time = time_now\n\n\t\t\t\tstring = ''\n\t\t\t\ttry:\n\t\t\t\t\tstring += self._animation_string\n\n\t\t\t\t\tif time:\n\t\t\t\t\t\tstring += self._main_bar._elapsed_time_string\n\t\t\t\t\t\tstring += self._main_bar._remaining_time_string\n\n\t\t\t\t\tif bar:\n\t\t\t\t\t\tself._last_formatted_bar = self.bar\n\t\t\t\t\t\tstring += self._last_formatted_bar\n\n\t\t\t\t\tif percent:\n\t\t\t\t\t\tstring += self._main_bar._percent_string\n\n\t\t\t\t\tif self._parent is None:\n\t\t\t\t\t\tself._last_text = text\n\t\t\t\t\telse:\n\t\t\t\t\t\tif len(self._parent._last_text) > 0:\n\t\t\t\t\t\t\tself._last_text = self._parent._last_text + ' / ' + text\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself._last_text = text\n\n\t\t\t\t\tstring += self._get_text_string(text=self._last_text)\n\n\t\t\t\t\tself._max_lengths['with_colour'] = max(self._max_lengths['with_colour'], len(string))\n\t\t\t\t\tstring = string.ljust(self._max_lengths['with_colour'])\n\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tself.write(string=f'progress bar error: {e}')\n\t\t\t\t\traise e\n\n\t\t\t\tif self.amount >= self.total:\n\t\t\t\t\tself.complete()\n\n\t\t\t\tif self._completed:\n\t\t\t\t\tif self._disappear:\n\t\t\t\t\t\tself.write(string=' ' * self._max_lengths['with_colour'] + ' ')\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.write(string=string)\n\n\t\t\t\t\tif self._next_line:\n\t\t\t\t\t\tprint('')\n\t\t\t\telse:\n\t\t\t\t\tself.write(string=string, flush=True)\n\n\t@classmethod\n\tdef map(\n\t\t\tcls, function, iterable, percent=True, bar=True, time=True, text='', echo=1,\n\t\t\tnext_line=True, iterable_text=None,\n\t\t\t**kwargs\n\t):\n\t\techo = max(0, echo)\n\n\t\tdef _func(x, _progress, _progress_bar, _text=''):\n\t\t\tif progress['amount'] == 0:\n\t\t\t\tprogress_bar.show(\n\t\t\t\t\tamount=progress['amount'], percent=percent, bar=bar, time=time, text=text + _text\n\t\t\t\t)\n\n\t\t\tfunction_result = function(x)\n\n\t\t\t_progress['amount'] += 1\n\t\t\tif elapsed(start_time=progress['update_time'], end_time=datetime.now()) > 0.5 or _progress['amount'] >= total:\n\t\t\t\t_progress_bar.show(amount=_progress['amount'], percent=percent, bar=bar, time=time, text=text + _text)\n\t\t\t\t_progress['update_time'] = datetime.now()\n\n\t\t\treturn function_result\n\n\t\ttotal = len(iterable)\n\n\t\tprogress = {'amount': 0, 'update_time': datetime.now()}\n\t\tprogress_bar = cls(total=total, next_line=next_line, **kwargs)\n\n\t\tif echo:\n\t\t\tif iterable_text is None:\n\t\t\t\tresult = _map(\n\t\t\t\t\tlambda x: _func(x=x, _progress=progress, _progress_bar=progress_bar),\n\t\t\t\t\titerable\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tresult = _map(\n\t\t\t\t\tlambda x: _func(x=x[0], _text=x[1], _progress=progress, _progress_bar=progress_bar),\n\t\t\t\t\tzip(iterable, iterable_text)\n\t\t\t\t)\n\n\t\t\treturn result\n\t\telse:\n\t\t\treturn _map(function, iterable)\n\n\t@classmethod\n\tdef apply(\n\t\t\tcls, function, data=None, series=None, percent=True, bar=True, time=True, text='',\n\t\t\taxis=1, echo=1, next_line=True, **kwargs\n\t):\n\t\t\"\"\"\n\t\t:type function: function\n\t\t:type data: pd.DataFrame\n\t\t:type series: pd.Series\n\t\t:type percent: bool\n\t\t:type bar: bool\n\t\t:type time: bool\n\t\t:type text: str\n\t\t:type axis: int\n\t\t:type echo: bool or int\n\t\t:type next_line: bool\n\t\t:rtype: pd.DataFrame or pd.Series\n\t\t\"\"\"\n\t\techo = max(0, echo)\n\t\t# either data or series should be provided:\n\t\tif data is None and series is None:\n\t\t\traise ValueError('either data or series should be provided')\n\n\t\tif data is not None and series is not None:\n\t\t\traise ValueError('both data and series cannot be provided')\n\n\t\tdef _func(x, _progress, _progress_bar):\n\t\t\tfunction_result = function(x)\n\t\t\t_progress['amount'] += 1\n\n\t\t\tif elapsed(start_time=_progress['update_time'], end_time=datetime.now()) > 0.5 or _progress['amount'] >= total:\n\t\t\t\t_progress_bar.show(amount=_progress['amount'], percent=percent, bar=bar, time=time, text=text)\n\t\t\t\t_progress['update_time'] = datetime.now()\n\n\t\t\treturn function_result\n\n\t\tif data is not None:\n\t\t\tif axis == 1:\n\t\t\t\ttotal = data.shape[0]\n\t\t\telse:\n\t\t\t\ttotal = data.shape[1]\n\t\telse:\n\t\t\ttotal = series.shape[0]\n\n\t\tif total == 0:\n\t\t\treturn None\n\n\t\tprogress = {'amount': 0, 'update_time': datetime.now()}\n\t\tprogress_bar = cls(total=total, next_line=next_line, **kwargs)\n\t\tif echo:\n\t\t\tprogress_bar.show(amount=0, percent=percent, bar=bar, time=time, text=text)\n\t\t\tif data is not None:\n\t\t\t\tresult = data.apply(func=lambda x: _func(x=x, _progress=progress, _progress_bar=progress_bar), axis=axis)\n\t\t\telse:\n\t\t\t\tresult = series.apply(func=lambda x: _func(x=x, _progress=progress, _progress_bar=progress_bar))\n\n\t\telse:\n\t\t\tif data is not None:\n\t\t\t\tresult = data.apply(func=function, axis=axis)\n\t\t\telse:\n\t\t\t\tresult = series.apply(func=function)\n\n\t\treturn result\n\n\tdef __gt__(self, other):\n\t\tif isinstance(other, self.__class__):\n\t\t\treturn self._echo > other._echo\n\t\telse:\n\t\t\ttry:\n\t\t\t\treturn self._echo > other\n\t\t\texcept TypeError:\n\t\t\t\treturn True\n\n\tdef __lt__(self, other):\n\t\tif isinstance(other, self.__class__):\n\t\t\treturn self._echo < other._echo\n\t\telse:\n\t\t\ttry:\n\t\t\t\treturn self._echo < other\n\t\t\texcept TypeError:\n\t\t\t\treturn False\n\n\tdef __ge__(self, other):\n\t\treturn not (self < other)\n\n\tdef __le__(self, other):\n\t\treturn not (self > other)\n\n\tdef __eq__(self, other):\n\t\tif isinstance(other, self.__class__):\n\t\t\treturn self._echo == other._echo\n\t\telse:\n\t\t\treturn False\n\n\tdef __ne__(self, other):\n\t\treturn not (self == other)\n\n\t@classmethod\n\tdef test(cls, time=1, n=10000, bar_characters=None):\n\t\tbar = cls(total=n, display_wait=0.1, bar_characters=bar_characters)\n\t\tfor i in range(n):\n\t\t\tbar.show(amount=i, text='testing ...')\n\t\t\tsleep(time / n / 2)\n\t\tbar.show(amount=n, text='test done!')\n", "sub_path": "chronometry/progress/ProgressBar.py", "file_name": "ProgressBar.py", "file_ext": "py", "file_size_in_byte": 14305, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 169, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 169, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 235, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 250, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 251, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 263, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 263, "usage_type": "name"}, {"api_name": "sys.stdout.flush", "line_number": 265, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 265, "usage_type": "name"}, {"api_name": "colour.colour", "line_number": 271, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 278, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 285, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 292, "usage_type": "call"}, {"api_name": "colour.colour", "line_number": 298, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 326, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 326, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 395, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 395, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 397, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 397, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 403, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 403, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 452, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 452, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 454, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 454, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 469, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 469, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 524, "usage_type": "call"}]} +{"seq_id": "427477780", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport Indication as indi\nimport logging\n# for user in users:\n# \tprint(user)\n\ndef createDirectoyTasks():\n\tif not os.path.isdir('./tasks'):\n\t\tos.mkdir('./tasks')\n\n\nif __name__ == \"__main__\":\n\tlogging.basicConfig(filename='medrating.log', level=logging.INFO)\n\tcreateDirectoyTasks()\n\tindicator = indi.Indication()\n\tindicator.creatUsers()\n\tindicator.CreateIndicators()\n\n\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 421, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.isdir", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 13, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 17, "usage_type": "attribute"}, {"api_name": "Indication.Indication", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "247884609", "text": "from pymongo import MongoClient\n\n\nclient = MongoClient('mongodb://localhost:27017/', connect=False)\ncrawl_db = client.gc\nproduction_db = client.tweetsocial\n\n\n# new_user = {\n# \t\"username\" : user['name'],\n# \t\"description\" : user['description']\n# \t\"friends_count\" : user['friends_count'],\n# \t\"link\" : 'https://twitter.com/' + user['screen_name'],\n# \t\"id\" : user['_id'],\n# \t\"lang\" : user['lang'],\n# \t\"screen_name\" : user['screen_name'],\n# \t\"label\" : \"Local\",\n# \t\"followers_count\" : user['followers_count'],\n# \t\"location\" : user['location'],\n# \t\"listed_count\" : user['listed_count'],\n# \t\"lat\" : -37.8136276,\n# \t\"long\" : 144.9630576\n# }\n\n\n", "sub_path": "db.py", "file_name": "db.py", "file_ext": "py", "file_size_in_byte": 633, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymongo.MongoClient", "line_number": 4, "usage_type": "call"}]} +{"seq_id": "180773483", "text": "# =========================== [ setting ] =====================\n## [ data read ] ===========\nimport pandas as pd\nimport os\n\nos.chdir(\"/Users/kimjiseong/Downloads/[ Project ] Kaggle/Bag of Words Meets Bags of Popcorn/data\")\n\ntrain = pd.read_csv(\"./labeledTrainData.tsv\",\n header=0,\n delimiter=\"\\t\",\n quoting=3)\n\ntest = pd.read_csv(\"./testData.tsv\",\n header=0,\n delimiter=\"\\t\",\n quoting=3)\n\nunlabeled_train = pd.read_csv(\"./unlabeledTrainData.tsv\",\n header=0,\n delimiter=\"\\t\",\n quoting=3)\n\n## [ tidying sentences ] =====\n# from KaggleWord2VecUtility import KaggleWord2VecUtility\nsentences = []\nfor review in train[\"review\"]:\n sentences += KaggleWord2VecUtility.review_to_sentences(review, remove_stopwords=False)\n\nfor reivew in unlabeled_train[\"review\"]:\n sentences += KaggleWord2VecUtility.review_to_sentences(review, remove_stopwords=False)\n\n## [ train model with Gensim ] ==\n### [ modeling ] ================\n\nnum_features = 300 # 문자 벡터 차원수 \nmin_word_count = 40 # 최소 문자 수 \nnum_workers = 4 # 병렬 처리 스레드 수 \ncontext = 10 # 문자열 윈도우 크기 \ndownsampling = 1e-3 # 문자 빈도 수 \n\nfrom gensim.models import word2vec\n\nmodel = word2vec.Word2Vec(sentences,\n workers=num_workers,\n size=num_features,\n min_count=min_word_count,\n window=context,\n sample=downsampling)\n\nmodel_name = '300features_40minwords_10text'\nmodel.save(model_name)\n\nmodel\n\n## [ word plotting ] =========\n\nfrom sklearn.manifold import TSNE\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport gensim\nimport gensim.models as g\n\nmpl.rcParams[\"axes.unicode_minus\"] = False # 폰트 깨짐 방지\n\nmodel_name = \"300features_40minwords_10text\"\nmodel = g.Doc2Vec.load(model_name)\n\nvocab = list(model.wv.vocab)\nX = model[vocab]\n\ntsne = TSNE(n_components=2)\nX_tsne = tsne.fit_transform(X[:100, :])\ndf = pd.DataFrame(X_tsne, index=vocab[:100], columns=[\"x\", \"y\"])\n\nfig = plt.figure()\nfig.set_size_inches(40, 20)\nax = fig.add_subplot(1, 1, 1)\nax.scatter(df[\"x\"], df[\"y\"])\n\nfor word, pos in df.iterrows():\n ax.annotate(word, pos, fontsize=30)\nplt.show()\n\n\n## [ making method ] =======\ndef makeFeatureVec(word, model, num_features):\n featureVec = np.zeros((num_features,), dtype=\"float32\")\n nwords = 0.\n index2word_set = set(model.wv.index2word)\n\n for word in words:\n if word in index2word_set:\n nwords = nwords + 1.\n featureVec = np.add(featureVec, model[word])\n\n featureVec = np.divide(featureVec, nwords)\n return featureVec\n\n\ndef getAvgFeatureVecs(reviews, model, num_features):\n counter = 0.\n reviewFeatureVecs = np.zeros((len(reviews), num_features), dtype=\"float32\")\n\n for review in reviews:\n if counter % 1000. == 0.:\n print(\"Review %d of %d\" % (counter, len(reviews)))\n\n reviewFeatureVecs[int(counter)] = makeFeatureVec(review, model, num_features)\n counter = counter + 1.\n return reviewFeatureVecs\n\n\ndef getCleanReviews(reviews):\n clean_reviews = []\n clean_reviews = clean_reviews = KaggleWord2VecUtility.apply_by_multiprocessing(reviews[\"review\"],\n KaggleWord2VecUtility.review_to_wordlist,\n workers=4)\n return clean_reviews\n\n\ntrainDataVecs = getAvgFeatureVecs(getCleanReviews(train), model, num_features)\n\n## [ model 검정 ] ==========\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\n\nforest = RandomForestClassifier(n_estimators=100,\n n_jobs=-1,\n random_state=2018)\nforest.fit(trainDataVecs, train[\"sentiment\"])\n\nscore = np.mean(cross_val_score(forest,\n trainDataVecs,\n train[\"sentiment\"],\n cv=10,\n scoring=\"roc_auc\"))\nprint(score)\n\noutput = pd.DataFrame(data={\"id\": test[\"id\"],\n \"sentiment\": result})\noutput.to_csv(\"./Word2vec_AverageVectors.csv\",\n index=False,\n quoting=3)", "sub_path": "Bag of Words Meets Bags of Popcorn/CODE/Bag of Words Meets Bags of Popcorn Word2Vec CODE.py", "file_name": "Bag of Words Meets Bags of Popcorn Word2Vec CODE.py", "file_ext": "py", "file_size_in_byte": 4497, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.chdir", "line_number": 6, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "gensim.models.word2vec.Word2Vec", "line_number": 43, "usage_type": "call"}, {"api_name": "gensim.models.word2vec", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.rcParams", "line_number": 63, "usage_type": "attribute"}, {"api_name": "gensim.models.Doc2Vec.load", "line_number": 66, "usage_type": "call"}, {"api_name": "gensim.models.Doc2Vec", "line_number": 66, "usage_type": "attribute"}, {"api_name": "gensim.models", "line_number": 66, "usage_type": "name"}, {"api_name": "sklearn.manifold.TSNE", "line_number": 71, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 127, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 132, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 139, "usage_type": "call"}]} +{"seq_id": "49869656", "text": "#!/usr/bin/env python\n# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\nfrom __future__ import print_function\n\nfrom twisted.internet import task\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet.protocol import Protocol, ClientFactory\nfrom twisted.protocols.basic import LineReceiver\n\nfrom ProtobufProtocol import ProtobufProtocol\nimport User_pb2\nimport sys\n\n\nclass EchoClient(LineReceiver):\n end = \"Bye-bye!\"\n def connectionMade(self):\n #self.sendLine(\"Hello, world!\")\n # self.sendLine(\"What a fine day it is.\")\n self.setRawMode()\n\n\n user = User_pb2.User()\n user.user_name = \"jackson\"\n user.user_id = 1\n user.email = \"songtzu@mail.com\"\n print( user.SerializeToString() )\n\n self.sendLine(user.SerializeToString())\n #self.sendLine(self.end)\n\n def lineReceived(self, line):\n print(\"receive:\", line)\n if line == self.end:\n self.transport.loseConnection()\n\n\n\nclass DispacthRoute(ProtobufProtocol):\n\n def OnDispatchControler(self):\n print (\"OnDispath\")\n\n def connectionMade(self):\n user = User_pb2.User()\n user.user_name = \"jackson\"\n user.user_id = 1\n user.email = \"songtzu@mail.com\"\n print(user.SerializeToString())\n self.SendProtobuf(1,1,user)\n\n\nclass EchoClientFactory(ClientFactory):\n protocol = DispacthRoute\n\n def __init__(self):\n self.done = Deferred()\n\n\n def clientConnectionFailed(self, connector, reason):\n print('connection failed:', reason.getErrorMessage())\n self.done.errback(reason)\n\n\n def clientConnectionLost(self, connector, reason):\n print('connection lost:', reason.getErrorMessage())\n self.done.callback(None)\n\n\n\ndef main(reactor):\n factory = EchoClientFactory()\n reactor.connectTCP('localhost', 8002, factory)\n return factory.done\n\n\n\nif __name__ == '__main__':\n task.react(main)", "sub_path": "twistedproto/client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 1952, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "twisted.protocols.basic.LineReceiver", "line_number": 17, "usage_type": "name"}, {"api_name": "User_pb2.User", "line_number": 25, "usage_type": "call"}, {"api_name": "ProtobufProtocol.ProtobufProtocol", "line_number": 41, "usage_type": "name"}, {"api_name": "User_pb2.User", "line_number": 47, "usage_type": "call"}, {"api_name": "twisted.internet.protocol.ClientFactory", "line_number": 55, "usage_type": "name"}, {"api_name": "twisted.internet.defer.Deferred", "line_number": 59, "usage_type": "call"}, {"api_name": "twisted.internet.task.react", "line_number": 81, "usage_type": "call"}, {"api_name": "twisted.internet.task", "line_number": 81, "usage_type": "name"}]} +{"seq_id": "546672581", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n\nimport time\nimport os\nimport itertools\nfrom collections import defaultdict\nimport pickle\nimport glob\nimport numpy as np\nfrom redbaron import RedBaron\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import random_split\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\n\n# import tokenization\n# import bug_db\n# import normalize\nfrom . import tokenization\nfrom . import bug_db\nfrom . import normalize\n\n\n# from normalize import normalize_format_string\n# from tokenization import ast_tokenize_str\n\n\n# In[2]:\n\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ncriterion = torch.nn.NLLLoss(reduction='mean')\nencoder_n_layers = 1\ndecoder_n_layers = 1\nbatch_size = 20480\np_dropout = 0.1\nmodel_size = 64\nn_epoch = 100\nvocab_size = 10000\nlr = 0.001\nmodel_folder = \"/home/smartscript/smartscript_web/py_checker/model_type_fulldata/\"\nMAX_SEQ_LEN = 512\n\n\n# In[3]:\n\n\n\ntrainWriter = open(\"./TrainLog.txt\",\"w\",encoding='utf-8')\nvalidWriter = open(\"./ValidLog.txt\",\"w\",encoding='utf-8')\ntestWriter = open(\"./TestLog.txt\",\"w\",encoding='utf-8')\n\n\n# In[4]:\n\n\nwith open ('/home/smartscript/smartscript_web/py_checker/model_type_fulldata/Types500.pkl', 'rb') as fp:\n Types500 = pickle.load(fp)\n\n\n# In[5]:\n\n\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):\n super(EncoderRNN, self).__init__()\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.embedding = embedding\n\n # Initialize GRU; the input_size and hidden_size params are both set to 'hidden_size'\n # because our input size is a word embedding with number of features == hidden_size\n self.gru = nn.GRU(\n hidden_size,\n hidden_size,\n n_layers,\n dropout=(0 if n_layers == 1 else dropout),\n bidirectional=True)\n self.n_directions = 2\n\n def forward(self, input_seq, input_lengths, hidden=None):\n # Convert word indexes to embeddings\n embedded = self.embedding(input_seq)\n # Pack padded batch of sequences for RNN module\n packed = torch.nn.utils.rnn.pack_padded_sequence(\n embedded, input_lengths, batch_first=False)\n # Forward pass through GRU\n outputs, hidden = self.gru(packed, hidden)\n # Unpack padding\n outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs, batch_first=False)\n # Sum bidirectional GRU outputs\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, :, self.hidden_size:]\n hidden = hidden.view(self.n_layers, self.n_directions, -1, self.hidden_size)\n hidden = hidden[-1, 0, :, :] + hidden[-1, 1, :, :]\n # Return output and final hidden state\n return outputs, hidden.unsqueeze(0)\n\n\n# In[6]:\n\n\n\nclass Attn(torch.nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n self.method = method\n if self.method not in ['dot', 'general', 'concat']:\n raise ValueError(self.method,\n \"is not an appropriate attention method.\")\n self.hidden_size = hidden_size\n if self.method == 'general':\n self.attn = torch.nn.Linear(self.hidden_size, hidden_size)\n elif self.method == 'concat':\n self.attn = torch.nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size))\n\n def dot_score(self, hidden, encoder_output):\n return torch.sum(hidden * encoder_output, dim=2)\n\n def general_score(self, hidden, encoder_output):\n energy = self.attn(encoder_output)\n return torch.sum(hidden * energy, dim=2)\n\n def concat_score(self, hidden, encoder_output):\n energy = self.attn(\n torch.cat((hidden.expand(encoder_output.size(0), -1, -1),\n encoder_output), 2)).tanh()\n return torch.sum(self.v * energy, dim=2)\n\n def forward(self, hidden, encoder_outputs, attn_mask=None):\n # Calculate the attention weights (energies) based on the given method\n if self.method == 'general':\n attn_energies = self.general_score(hidden, encoder_outputs)\n elif self.method == 'concat':\n attn_energies = self.concat_score(hidden, encoder_outputs)\n elif self.method == 'dot':\n attn_energies = self.dot_score(hidden, encoder_outputs)\n\n # Transpose max_length and batch_size dimensions\n attn_energies = attn_energies.t()\n\n if attn_mask is not None:\n attn_energies.masked_fill_(attn_mask, -1e20)\n\n # Return the softmax normalized probability scores (with added dimension)\n return F.softmax(attn_energies, dim=1).unsqueeze(1)\n\n\n# In[7]:\n\n\n\nclass AttnClassifier(nn.Module):\n def __init__(self,\n attn_model,\n embedding,\n hidden_size,\n output_size,\n n_layers=1,\n dropout=0.1):\n super(AttnClassifier, self).__init__()\n\n # Keep for reference\n self.attn_model = attn_model\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n # Define layers\n self.embedding = embedding\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n\n self.attn = Attn(attn_model, hidden_size)\n\n def forward(self, encoder_hidden, encoder_outputs, attn_mask):\n # Calculate attention weights from the current GRU output\n # attn_weights = self.attn(encoder_hidden, encoder_outputs, attn_mask)\n # Multiply attention weights to encoder outputs to get new \"weighted sum\" context vector\n\n # context = attn_weights.bmm(encoder_outputs.transpose(0, 1))\n # Concatenate weighted context vector and GRU output using Luong eq. 5\n output = encoder_hidden.squeeze(0)\n # context = context.squeeze(1)\n # concat_input = torch.cat((output, context), 1)\n # concat_output = torch.tanh(self.concat(concat_input))\n # Predict next word using Luong eq. 6\n output = self.out(output)\n output = F.log_softmax(output, dim=1)\n # Return output and final hidden state\n return output\n\n\n# In[8]:\n\n\n\n\nclass BugDetector(nn.Module):\n def __init__(self,\n vocab_size,\n max_seq_len,\n model_size=32,\n p_dropout=0.1):\n super(BugDetector, self).__init__()\n self.embedding = nn.Embedding(vocab_size, model_size, padding_idx=0)\n self.max_seq_len = max_seq_len\n self.encoder = EncoderRNN(model_size, self.embedding, encoder_n_layers, p_dropout)\n self.cls = AttnClassifier('dot', self.embedding, model_size, 500, decoder_n_layers, p_dropout)\n # self.apply(self.init_weights)\n\n def init_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=0.02)\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def forward(self, seqs, seqs_lens):\n # Ignore the last EOS token\n encoder_outputs, encoder_hidden = self.encoder(seqs, seqs_lens)\n attn_mask = padding_mask(seqs_lens, self.max_seq_len)\n output = self.cls(encoder_hidden, encoder_outputs, attn_mask)\n return output\n\n\n# In[9]:\n\n\n# allName = np.load(\"../allName.npy\")\n# allType = np.load(\"../allType.npy\")\n\n\n# In[10]:\n\n\n# i=1\n# for Name,Type in tqdm(zip(allName,allType)):\n# print(Name,Type)\n# if i>10:\n# break\n# i=i+1\n\n\n# In[11]:\n\n\n# allName[:10]\n\n\n# In[20]:\n\n\n\ndef load_data():\n sp = tokenization.load_model('../SPM500/spm.model')\n with open ('../moreThan500Name.pkl', 'rb') as fp:\n allName = pickle.load(fp)\n with open ('../moreThan500Type.pkl', 'rb') as fp:\n allType = pickle.load(fp)\n# allName = np.load(\"../allName.npy\")\n# allType = np.load(\"../allType.npy\")\n max_tensor_length = 0\n \n samples = []\n labels = []\n print(\"Loading data...\")\n for Name,Type in tqdm(zip(allName,allType),total=len(allName)):\n token_ids = tokenization.encode(sp, Name)\n if len(token_ids) == 0 or len(token_ids) > MAX_SEQ_LEN:\n continue\n samples.append(token_ids)\n labels.append(Types500.index(Type))\n max_tensor_length = max(max_tensor_length, len(token_ids))\n return list(zip(samples, labels)), max_tensor_length\n \n\n\n# In[13]:\n\n\n\n\ndef padding_mask(seqs_lens, max_len):\n mask = torch.zeros((seqs_lens.size(0), seqs_lens.max().item()), dtype=torch.uint8)\n for i, seq_len in enumerate(seqs_lens):\n mask[i][seq_len:] = 1\n return mask.to(device)\n\n\ndef get_token_ids(stmt: str, word2index, index2word, word_counts, word_idx):\n tokens = tokenization.ast_tokenize_str(stmt)\n for token in tokens:\n if token not in word2index:\n word2index[token] = word_idx\n index2word[word_idx] = token\n word_idx += 1\n word_counts[token] += 1\n return tokens, word_idx\n\n\ndef get_tokens(stmt: str, word2index, index2word, word_counts, word_idx):\n tokens = tokenization.ast_tokenize_str(stmt)\n for token in tokens:\n if token not in word2index:\n word2index[token] = word_idx\n index2word[word_idx] = token\n word_idx += 1\n word_counts[token] += 1\n return tokens, word_idx\n\ndef calc_vocab_min_freq(word_counts, vocab_size):\n # sorted_word_counts = sorted(word_counts.items(), lambda kv: kv[1])\n values = list(word_counts.values())\n sorted_values = sorted(values, reverse=True)\n return sorted_values[vocab_size]\n\n\ndef save_vocab(word2index, index2word, word_counts, min_freq):\n keep_word2index = {}\n keep_index2word = {}\n for k in word2index.keys():\n if word_counts[k] >= min_freq:\n keep_word2index[k] = word2index[k]\n keep_index2word[word2index[k]] = k\n vocab = {'word2index': word2index, 'index2word': index2word}\n vocab_path = os.path.join(model_folder, \"vocab.dat\")\n pickle.dump(vocab, open(vocab_path, 'wb'))\n\n\ndef load_vocab():\n vocab_path = os.path.join(model_folder, \"vocab.dat\")\n vocab = pickle.load(open(vocab_path, 'rb'))\n return vocab['word2index'], vocab['index2word']\n\n\ndef zero_padding(batch, fillvalue=0):\n batch.sort(key=lambda sample: len(sample[0]), reverse=True)\n batch_samples, batch_labels = zip(*batch)\n lengths = torch.tensor([len(indexes) for indexes in batch_samples])\n # return list(zip(*itertools.zip_longest(*batch_samples, fillvalue=fillvalue))), lengths, batch_labels\n # samples shape becomes: [max_len, batch_size]\n return list(itertools.zip_longest(*batch_samples, fillvalue=fillvalue)), lengths, batch_labels\n\n\ndef collate_fn(batch):\n padded_samples, lengths, batch_labels = zero_padding(batch, 0)\n return torch.LongTensor(padded_samples), torch.LongTensor(lengths), torch.LongTensor(batch_labels)\n\n\ndef compute_loss(pred, tgt):\n loss = criterion(pred, tgt)\n pred = pred.max(dim=1)[1] # result of 'max' is tuple, dimension 1 is the indices, dimension 0 is the values\n n_correct = pred.eq(tgt).sum().item()\n return loss, n_correct\n\n\ndef max_norm(model: nn.Module, max_val=3):\n for name, param in model.named_parameters():\n if 'bias' not in name and len(param.shape) > 1:\n param.renorm(2, 0, max_val)\n\n\n# In[14]:\n\n\n\n\ndef train_epoch(model, training_data, optimizer):\n model.train()\n total_correct = 0\n total = 0\n for batch in tqdm(\n training_data, mininterval=2, desc=' ---Training--- ',\n leave=False):\n seqs, seqs_lens, labels = map(lambda x: x.to(device), batch)\n # optim.optimizer.zero_grad()\n optimizer.zero_grad()\n pred = model(seqs, seqs_lens)\n \n \n loss, n_correct = compute_loss(pred, labels)\n # loss.register_hook(lambda grad: print(grad))\n loss.backward()\n optimizer.step()\n # max_norm(model, 3)\n total += labels.size(0)\n total_correct += n_correct\n accr = total_correct / total\n return accr\n\n\n# In[15]:\n\n\n\ndef eval_epoch(model, validation_data):\n model.eval() # disable dropout, batchnorm, etc.\n total_correct = 0\n total = 0\n with torch.no_grad():\n for batch in tqdm(validation_data, mininterval=2,\n desc=' ---Validation--- ',\n leave=False):\n seqs, seqs_lens, labels = map(lambda x: x.to(device),\n batch)\n pred = model(seqs, seqs_lens)\n _, n_correct = compute_loss(pred, labels)\n total += labels.size(0)\n total_correct += n_correct\n accr = total_correct / total\n return accr\n\n\n# In[16]:\n\n\n\ndef test_epoch(model, test_data):\n model.eval() # disable dropout, batchnorm, etc.\n total_correct = 0\n total = 0\n with torch.no_grad():\n for batch in tqdm(test_data, mininterval=2,\n desc=' ---Test--- ',\n leave=False):\n seqs, seqs_lens, labels = map(lambda x: x.to(device),\n batch)\n pred = model(seqs, seqs_lens)\n _, n_correct = compute_loss(pred, labels)\n total += labels.size(0)\n total_correct += n_correct\n accr = total_correct / total\n return accr\n\n\n# In[17]:\n\n\n\ndef train(model, training_data, validation_data, test_data, optim, vocab_size, max_tensor_length):\n val_accrs = []\n test_accrs = []\n for i in range(n_epoch):\n start = time.time()\n train_accr = train_epoch(model, training_data, optim)\n trainWriter.write(str(train_accr)+\"\\n\")\n # trainWriter.write(\"\\n\")\n trainWriter.flush()\n print('\\n - (Training) accuracy: {accu:3.3f} %, '\n 'elapse: {elapse:3.3f} min'.format(\n accu=100 * train_accr,\n elapse=(time.time() - start) / 60))\n \n \n start = time.time()\n val_accr = eval_epoch(model, validation_data)\n validWriter.write(str(val_accr)+\"\\n\")\n # validWriter.write(\"\\n\")\n validWriter.flush()\n print('\\n - (Validation) accuracy: {accu:3.3f} %, '\n 'elapse: {elapse:3.3f} min'.format(\n accu=100 * val_accr,\n elapse=(time.time() - start) / 60))\n val_accrs.append(val_accr)\n # print(\"Accuracies so far: \", val_accrs)\n \n \n start = time.time()\n test_accr = test_epoch(model, test_data)\n testWriter.write(str(test_accr)+\"\\n\")\n # validWriter.write(\"\\n\")\n testWriter.flush()\n print('\\n - (Test) accuracy: {accu:3.3f} %, '\n 'elapse: {elapse:3.3f} min'.format(\n accu=100 * test_accr,\n elapse=(time.time() - start) / 60))\n test_accrs.append(test_accr)\n # print(\"Accuracies so far: \", val_accrs)\n \n \n \n model_state_dict = model.state_dict()\n config = {'max_src_seq_len': max_tensor_length,\n 'vocab_size': vocab_size,\n 'dropout': p_dropout}\n checkpoint = {'model': model_state_dict, 'epoch': i,\n 'config': config}\n model_name = os.path.join(model_folder, \"TypeModel.ckpt\")\n if val_accr >= max(val_accrs):\n print(\"Save model at epoch \", i)\n torch.save(checkpoint, model_name)\n\n\n# In[18]:\n\n\ndef main():\n samples, max_tensor_length = load_data()\n training_samples, validation_samples, test_samples = random_split(\n samples, [int(len(samples) * 0.6), int(len(samples) * 0.2),len(samples) - int(len(samples) * 0.6)-int(len(samples) * 0.2)])\n train_loader = torch.utils.data.DataLoader(\n training_samples,\n num_workers=0,\n batch_size=batch_size,\n collate_fn=collate_fn,\n shuffle=True)\n valid_loader = torch.utils.data.DataLoader(\n validation_samples,\n num_workers=0,\n batch_size=batch_size,\n collate_fn=collate_fn,\n )\n test_loader = torch.utils.data.DataLoader(\n test_samples,\n num_workers=0,\n batch_size=batch_size,\n collate_fn=collate_fn,\n )\n # vocab size should be len(word2index)+1 since 0 is not used\n detector = BugDetector(vocab_size, max_tensor_length, model_size, p_dropout)\n optimizer = optim.Adam(detector.parameters(), lr=lr)\n detector.to(device)\n train(detector, train_loader, valid_loader,test_loader, optimizer, vocab_size, max_tensor_length)\n\n\n# In[21]:\nimport ast\n\n\n\ndef predict(wanted):\n model_path = os.path.join(model_folder, \"TypeModel.ckpt\")\n checkpoint = torch.load(model_path,map_location=torch.device('cpu')) ##################\n sp = tokenization.load_model('/home/smartscript/smartscript_web/py_checker/model_type_fulldata/spm.model')\n# word2index, index2word = load_vocab()\n # wanted = input(\"Please input var name:\")\n test_samples = []\n fake_lables = []\n tokens = tokenization.encode(sp, wanted)\n# token_ids = []\n# for token in tokens:\n# token_ids.append(word2index.get(token, word2index['__UNK_TOKEN__']))\n test_samples.append(tokens)\n fake_lables.append(0)\n test_samples = list(zip(test_samples, fake_lables))\n data_loader = torch.utils.data.DataLoader(\n test_samples,\n num_workers=0,\n batch_size=1,#len(test_samples),\n collate_fn=collate_fn,\n shuffle=False)\n for batch in tqdm(\n data_loader, mininterval=2, desc=' ---Predicting--- ',\n leave=False):\n seqs, seqs_lens, indices = map(lambda x: x.to(device), batch)\n detector = BugDetector(checkpoint['config']['vocab_size'], checkpoint['config']['max_src_seq_len'], model_size,\n checkpoint['config']['dropout'])\n detector.load_state_dict(checkpoint['model'])\n detector.to(device)\n detector.eval()\n pred = detector(seqs, seqs_lens)\n pred2 = F.softmax(pred,dim=1)\n # print(pred2.max(dim=0))\n poss = str(pred2.max().data)[7:-1]\n pred = pred.max(dim=1)[1]\n return str(Types500[pred])+\" - \"+poss\n \n\n\ndef getResult(code):\n # code = open(\"/home/smartscript/smartscript_web/static/py_checker/misc/type/1.py\",\"r\").readlines()\n # code = \"\\n\".join(code)\n # print(code)\n\n root = \"\"\n try:\n root = ast.parse(code)\n except Exception as e:\n return \"AST ERROR: \"+str(e)\n names = sorted({(node.id,node.lineno) for node in ast.walk(root) if isinstance(node, ast.Name)})\n # names = sorted({node.id for node in ast.walk(root) if isinstance(node, ast.Name)})\n names2 = sorted({(node.attr,node.lineno) for node in ast.walk(root) if isinstance(node, ast.Attribute)})\n names3 = sorted({(node.name,node.lineno) for node in ast.walk(root) if isinstance(node, ast.FunctionDef)})\n namesAll = list(set(names+names3))\n\n # red = RedBaron(code)\n # method_reds = red.find_all('def')\n # methods = []\n # funcNames = []\n\n # for method_red in method_reds:\n # funcName = method_red.name\n # # print(funcName)\n # methods.append(method_red.dumps())\n # funcNames.append(funcName)\n # print(funcNames)\n # funcNames.append(\"getint\")\n results = []\n for func,lineno in namesAll:\n results.append((predict(func),lineno))\n ret = {}\n for func,res in zip(namesAll,results):\n if str(res[1]) not in ret:\n ret[str(res[1])] = []\n ret[str(res[1])].append([func[0],str(res[0])])\n return ret\ndef test(name):\n namesAll = []\n namesAll.append([name,1])\n namesAll.append([\"test\",1])\n namesAll.append([\"var\",2])\n results = []\n for func,lineno in namesAll:\n results.append((predict(func),lineno))\n ret = {}\n for func,res in zip(namesAll,results):\n if str(res[1]) not in ret:\n ret[str(res[1])] = []\n ret[str(res[1])].append([func[0],str(res[0])])\n return ret\n\n# main()\nif __name__ == \"__main__\":\n print(test(\"PY2\"))\n", "sub_path": "smartscript_web/py_checker/newTypeModel.py", "file_name": "newTypeModel.py", "file_ext": "py", "file_size_in_byte": 20422, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.device", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn.NLLLoss", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 75, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.utils.rnn.pack_padded_sequence", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.nn.utils.rnn.pad_packed_sequence", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 101, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 114, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 123, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 125, "usage_type": "attribute"}, {"api_name": "torch.nn.Parameter", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 126, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 164, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 164, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 183, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 183, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 184, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 211, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 211, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 218, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 225, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 225, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 225, "usage_type": "attribute"}, {"api_name": "torch.nn.LayerNorm", "line_number": 227, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 227, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 230, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 230, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 272, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 274, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 282, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 299, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 299, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 341, "usage_type": "call"}, {"api_name": "os.path", "line_number": 341, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 342, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 346, "usage_type": "call"}, {"api_name": "os.path", "line_number": 346, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 347, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 354, "usage_type": "call"}, {"api_name": "itertools.zip_longest", "line_number": 357, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 362, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 372, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 372, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 387, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 415, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 416, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 437, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 438, "usage_type": "call"}, {"api_name": "time.time", "line_number": 459, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 460, "usage_type": "argument"}, {"api_name": "time.time", "line_number": 467, "usage_type": "call"}, {"api_name": "time.time", "line_number": 470, "usage_type": "call"}, {"api_name": "time.time", "line_number": 478, "usage_type": "call"}, {"api_name": "time.time", "line_number": 483, "usage_type": "call"}, {"api_name": "time.time", "line_number": 491, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 503, "usage_type": "call"}, {"api_name": "os.path", "line_number": 503, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 506, "usage_type": "call"}, {"api_name": "torch.utils.data.random_split", "line_number": 514, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 516, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 516, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 522, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 522, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 528, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 528, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 536, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 536, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 547, "usage_type": "call"}, {"api_name": "os.path", "line_number": 547, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 548, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 548, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 561, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 561, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 567, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 577, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 577, "usage_type": "name"}, {"api_name": "ast.parse", "line_number": 592, "usage_type": "call"}, {"api_name": "ast.walk", "line_number": 595, "usage_type": "call"}, {"api_name": "ast.Name", "line_number": 595, "usage_type": "attribute"}, {"api_name": "ast.walk", "line_number": 597, "usage_type": "call"}, {"api_name": "ast.Attribute", "line_number": 597, "usage_type": "attribute"}, {"api_name": "ast.walk", "line_number": 598, "usage_type": "call"}, {"api_name": "ast.FunctionDef", "line_number": 598, "usage_type": "attribute"}]} +{"seq_id": "368378076", "text": "from typing import List, Tuple, NoReturn\nimport os\n\nVALID_INSTRUCTIONS = {\n \"acc\": lambda x, y: (x + y, 1),\n \"jmp\": lambda x, y: (x, y),\n \"nop\": lambda x, y: (x, 1),\n}\n\n\ndef process_input(file_name):\n with open(file_name) as report:\n result = []\n for idx, line in enumerate(report):\n instr, arg = line.strip().split(\" \")\n result.append((instr, int(arg), idx))\n return result\n\n\ndef find_accumulator_part_1(instructions: List) -> Tuple[int, bool]:\n accumulator = 0\n visited_instructions = set()\n instr_ptr = 0\n for _ in instructions:\n instr = instructions[instr_ptr]\n cmd, arg, _ = instr\n if (cmd, arg, instr_ptr) in visited_instructions:\n return accumulator, False\n visited_instructions.add((cmd, arg, instr_ptr))\n if not cmd in VALID_INSTRUCTIONS:\n raise Exception(f\"Invalid Instruction {cmd} in a list\")\n accumulator, ip_value = VALID_INSTRUCTIONS[cmd](accumulator, arg)\n instr_ptr += ip_value\n if instr_ptr == len(instructions):\n print(\"Last instruction executed!\")\n return accumulator, True\n return accumulator, True\n\n\ndef swap_nop_and_jmp(instructions: List, instr_to_replace: Tuple):\n cmd = \"nop\" if instr_to_replace[0] == \"jmp\" else \"jmp\"\n new_instr = (cmd, instr_to_replace[1], instr_to_replace[2])\n instructions.remove(instr_to_replace)\n pos = instr_to_replace[2]\n instructions.insert(pos, new_instr)\n\n\ndef find_accumulator_without_loop(instruction: List):\n status = False\n for i in range(len(instructions)):\n elem = instructions[i]\n if elem[0] == \"jmp\" and elem[1] < 0:\n swap_nop_and_jmp(instructions, elem)\n res, status = find_accumulator_part_1(instructions)\n elem = instructions[i]\n swap_nop_and_jmp(instructions, elem)\n if elem[0] == \"nop\" and elem[1] > 0:\n swap_nop_and_jmp(instructions, elem)\n res, status = find_accumulator_part_1(instructions)\n elem = instructions[i]\n swap_nop_and_jmp(instructions, elem)\n if status:\n print(f\"Accumulator value: {res}\")\n break\n\n\nif __name__ == \"__main__\":\n instructions = process_input(os.path.join(\"src\", \"day_8\", \"input.in\"))\n print(find_accumulator_part_1(instructions))\n find_accumulator_without_loop(instructions)\n", "sub_path": "src/day_8/handheld_halting.py", "file_name": "handheld_halting.py", "file_ext": "py", "file_size_in_byte": 2408, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.List", "line_number": 20, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 20, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 48, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}]} +{"seq_id": "34654651", "text": "\"\"\"empty message\n\nRevision ID: 6a5565cc6771\nRevises: 412e35624de9\nCreate Date: 2018-09-20 07:11:49.453329\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6a5565cc6771'\ndown_revision = '412e35624de9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user_token',\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('token_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['token_id'], ['token.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('user_id', 'token_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_token')\n # ### end Alembic commands ###\n", "sub_path": "restapi/migrations/versions/6a5565cc6771_.py", "file_name": "6a5565cc6771_.py", "file_ext": "py", "file_size_in_byte": 887, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "alembic.op.create_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 26, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 33, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 33, "usage_type": "name"}]} +{"seq_id": "510293002", "text": "# python3\n# pylint: disable=g-bad-file-header\n# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"Convenient factory methods to help build generative models.\"\"\"\n\nimport chex\nimport haiku as hk\nimport jax\nimport jax.numpy as jnp\nfrom neural_testbed.generative import classification_envlikelihood\n\n\ndef make_2layer_mlp_generative_model(\n input_dim: int,\n num_train: int,\n key: chex.PRNGKey,\n temperature: float,\n tau: int,\n hidden: int,\n num_classes: int,\n) -> classification_envlikelihood.ClassificationEnvLikelihood:\n \"\"\"Factory method to create a generative model around a 2-layer MLP.\"\"\"\n rng = hk.PRNGSequence(key)\n\n # Generating the logit function\n def net_fn(x: chex.Array) -> chex.Array:\n \"\"\"Defining the generative model MLP.\"\"\"\n y = hk.Linear(\n output_size=hidden,\n b_init=hk.initializers.RandomNormal(1./jnp.sqrt(input_dim)),\n )(x)\n y = jax.nn.relu(y)\n y = hk.Linear(hidden)(y)\n y = jax.nn.relu(y)\n return hk.Linear(num_classes)(y)\n\n transformed = hk.without_apply_rng(hk.transform(net_fn))\n dummy_input = jnp.zeros([1, input_dim])\n params = transformed.init(next(rng), dummy_input)\n def forward(x: chex.Array) -> chex.Array:\n return transformed.apply(params, x) / temperature\n\n # Generating the Gaussian data generator\n def x_generator(k: chex.PRNGKey, num_samples: int) -> chex.Array:\n return jax.random.normal(k, [num_samples, input_dim])\n\n return classification_envlikelihood.ClassificationEnvLikelihood(\n logit_fn=jax.jit(forward),\n x_generator=x_generator,\n num_train=num_train,\n key=next(rng),\n tau=tau,\n )\n", "sub_path": "neural_testbed/generative/factories.py", "file_name": "factories.py", "file_ext": "py", "file_size_in_byte": 2268, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "chex.PRNGKey", "line_number": 30, "usage_type": "attribute"}, {"api_name": "haiku.PRNGSequence", "line_number": 37, "usage_type": "call"}, {"api_name": "chex.Array", "line_number": 40, "usage_type": "attribute"}, {"api_name": "haiku.Linear", "line_number": 42, "usage_type": "call"}, {"api_name": "haiku.initializers.RandomNormal", "line_number": 44, "usage_type": "call"}, {"api_name": "haiku.initializers", "line_number": 44, "usage_type": "attribute"}, {"api_name": "jax.numpy.sqrt", "line_number": 44, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 44, "usage_type": "name"}, {"api_name": "jax.nn.relu", "line_number": 46, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 46, "usage_type": "attribute"}, {"api_name": "haiku.Linear", "line_number": 47, "usage_type": "call"}, {"api_name": "jax.nn.relu", "line_number": 48, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 48, "usage_type": "attribute"}, {"api_name": "haiku.Linear", "line_number": 49, "usage_type": "call"}, {"api_name": "haiku.without_apply_rng", "line_number": 51, "usage_type": "call"}, {"api_name": "haiku.transform", "line_number": 51, "usage_type": "call"}, {"api_name": "jax.numpy.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 52, "usage_type": "name"}, {"api_name": "chex.Array", "line_number": 54, "usage_type": "attribute"}, {"api_name": "chex.PRNGKey", "line_number": 58, "usage_type": "attribute"}, {"api_name": "jax.random.normal", "line_number": 59, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 59, "usage_type": "attribute"}, {"api_name": "chex.Array", "line_number": 58, "usage_type": "attribute"}, {"api_name": "neural_testbed.generative.classification_envlikelihood.ClassificationEnvLikelihood", "line_number": 61, "usage_type": "call"}, {"api_name": "neural_testbed.generative.classification_envlikelihood", "line_number": 61, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 62, "usage_type": "call"}, {"api_name": "neural_testbed.generative.classification_envlikelihood.ClassificationEnvLikelihood", "line_number": 35, "usage_type": "attribute"}, {"api_name": "neural_testbed.generative.classification_envlikelihood", "line_number": 35, "usage_type": "name"}]} +{"seq_id": "440549657", "text": "from __future__ import absolute_import\nfrom contextlib import contextmanager\nimport zlib\nimport io\nimport logging\nfrom socket import timeout as SocketTimeout\nfrom socket import error as SocketError\n\nimport h11\n\nfrom .._collections import HTTPHeaderDict\nfrom ..exceptions import (\n ProtocolError, DecodeError, ReadTimeoutError\n)\nfrom urllib3.packages.six import string_types as basestring, binary_type\nfrom ..util.ssl_ import BaseSSLError\nfrom ..util import is_fp_closed\n\nlog = logging.getLogger(__name__)\n\n\nclass DeflateDecoder(object):\n\n def __init__(self):\n self._first_try = True\n self._data = binary_type()\n self._obj = zlib.decompressobj()\n\n def __getattr__(self, name):\n return getattr(self._obj, name)\n\n def decompress(self, data):\n if not data:\n return data\n\n if not self._first_try:\n return self._obj.decompress(data)\n\n self._data += data\n try:\n decompressed = self._obj.decompress(data)\n if decompressed:\n self._first_try = False\n self._data = None\n return decompressed\n except zlib.error:\n self._first_try = False\n self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n try:\n return self.decompress(self._data)\n finally:\n self._data = None\n\n\nclass GzipDecoderState(object):\n\n FIRST_MEMBER = 0\n OTHER_MEMBERS = 1\n SWALLOW_DATA = 2\n\n\nclass GzipDecoder(object):\n\n def __init__(self):\n self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n self._state = GzipDecoderState.FIRST_MEMBER\n\n def __getattr__(self, name):\n return getattr(self._obj, name)\n\n def decompress(self, data):\n ret = binary_type()\n if self._state == GzipDecoderState.SWALLOW_DATA or not data:\n return ret\n while True:\n try:\n ret += self._obj.decompress(data)\n except zlib.error:\n previous_state = self._state\n # Ignore data after the first error\n self._state = GzipDecoderState.SWALLOW_DATA\n if previous_state == GzipDecoderState.OTHER_MEMBERS:\n # Allow trailing garbage acceptable in other gzip clients\n return ret\n raise\n data = self._obj.unused_data\n if not data:\n return ret\n self._state = GzipDecoderState.OTHER_MEMBERS\n self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n\ndef _get_decoder(mode):\n if mode == 'gzip':\n return GzipDecoder()\n\n return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n \"\"\"\n HTTP Response container.\n\n Backwards-compatible to httplib's HTTPResponse but the response ``body`` is\n loaded and decoded on-demand when the ``data`` property is accessed. This\n class is also compatible with the Python standard library's :mod:`io`\n module, and can hence be treated as a readable object in the context of that\n framework.\n\n Extra parameters for behaviour not present in httplib.HTTPResponse:\n\n :param preload_content:\n If True, the response's body will be preloaded during construction.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n\n :param retries:\n The retries contains the last :class:`~urllib3.util.retry.Retry` that\n was used during the request.\n \"\"\"\n\n CONTENT_DECODERS = ['gzip', 'deflate']\n REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n def __init__(self, body='', headers=None, status=0, version=0, reason=None,\n strict=0, preload_content=True, decode_content=True,\n original_response=None, pool=None, connection=None, msg=None,\n retries=None, enforce_content_length=False,\n request_method=None, request_url=None):\n\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers)\n self.status = status\n self.version = version\n self.reason = reason\n self.strict = strict\n self.decode_content = decode_content\n self.retries = retries\n\n self._decoder = None\n self._body = None\n self._fp = None\n self._original_response = original_response\n self._fp_bytes_read = 0\n self.msg = msg\n self._request_url = request_url\n self._buffer = b''\n\n if body and isinstance(body, (basestring, binary_type)):\n self._body = body\n else:\n self._fp = body\n\n self._pool = pool\n self._connection = connection\n\n # If requested, preload the body.\n if preload_content and not self._body:\n self._body = self.read(decode_content=decode_content)\n\n def get_redirect_location(self):\n \"\"\"\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n \"\"\"\n if self.status in self.REDIRECT_STATUSES:\n return self.headers.get('location')\n\n return False\n\n async def release_conn(self):\n if not self._pool or not self._connection:\n return\n\n await self._pool._put_conn(self._connection)\n self._connection = None\n\n @property\n def data(self):\n # For backwords-compat with earlier urllib3 0.4 and earlier.\n if self._body is not None:\n return self._body\n\n if self._fp:\n return self.read(cache_content=True)\n\n @property\n def connection(self):\n return self._connection\n\n def isclosed(self):\n return is_fp_closed(self._fp)\n\n def tell(self):\n \"\"\"\n Obtain the number of bytes pulled over the wire so far. May differ from\n the amount of content returned by :meth:``HTTPResponse.read`` if bytes\n are encoded on the wire (e.g, compressed).\n \"\"\"\n return self._fp_bytes_read\n\n def _init_decoder(self):\n \"\"\"\n Set-up the _decoder attribute if necessary.\n \"\"\"\n # Note: content-encoding value should be case-insensitive, per RFC 7230\n # Section 3.2\n content_encoding = self.headers.get('content-encoding', '').lower()\n if self._decoder is None and content_encoding in self.CONTENT_DECODERS:\n self._decoder = _get_decoder(content_encoding)\n\n def _decode(self, data, decode_content, flush_decoder):\n \"\"\"\n Decode the data passed in and potentially flush the decoder.\n \"\"\"\n try:\n if decode_content and self._decoder:\n data = self._decoder.decompress(data)\n except (IOError, zlib.error) as e:\n content_encoding = self.headers.get('content-encoding', '').lower()\n raise DecodeError(\n \"Received response with content-encoding: %s, but \"\n \"failed to decode it.\" % content_encoding, e)\n\n if flush_decoder and decode_content:\n data += self._flush_decoder()\n\n return data\n\n def _flush_decoder(self):\n \"\"\"\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n \"\"\"\n if self._decoder:\n buf = self._decoder.decompress(b'')\n return buf + self._decoder.flush()\n\n return b''\n\n @contextmanager\n def _error_catcher(self):\n \"\"\"\n Catch low-level python exceptions, instead re-raising urllib3\n variants, so that low-level exceptions are not leaked in the\n high-level api.\n\n On exit, release the connection back to the pool.\n \"\"\"\n clean_exit = False\n\n try:\n try:\n yield\n\n except SocketTimeout:\n # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n # there is yet no clean way to get at it from this context.\n raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n\n except BaseSSLError as e:\n # FIXME: Is there a better way to differentiate between SSLErrors?\n if 'read operation timed out' not in str(e): # Defensive:\n # This shouldn't happen but just in case we're missing an edge\n # case, let's avoid swallowing SSL errors.\n raise\n\n raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n\n except (h11.ProtocolError, SocketError) as e:\n # This includes IncompleteRead.\n raise ProtocolError('Connection broken: %r' % e, e)\n\n except GeneratorExit:\n # We swallow GeneratorExit when it is emitted: this allows the\n # use of the error checker inside stream()\n pass\n\n # If no exception is thrown, we should avoid cleaning up\n # unnecessarily.\n clean_exit = True\n finally:\n # If we didn't terminate cleanly, we need to throw away our\n # connection.\n if not clean_exit:\n self.close()\n\n # If we hold the original response but it's finished now, we should\n # return the connection back to the pool.\n if self._original_response and self._original_response.complete:\n self.release_conn()\n\n async def read(self, amt=None, decode_content=None, cache_content=False):\n \"\"\"\n Similar to :meth:`httplib.HTTPResponse.read`, but with two additional\n parameters: ``decode_content`` and ``cache_content``.\n\n :param amt:\n How much of the content to read. If specified, caching is skipped\n because it doesn't make sense to cache partial content as the full\n response.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n\n :param cache_content:\n If True, will save the returned data such that the same result is\n returned despite of the state of the underlying file object. This\n is useful if you want the ``.data`` property to continue working\n after having ``.read()`` the file object. (Overridden if ``amt`` is\n set.)\n \"\"\"\n # TODO: refactor this method to better handle buffered output.\n # This method is a weird one. We treat this read() like a buffered\n # read, meaning that it never reads \"short\" unless there is an EOF\n # condition at work. However, we have a decompressor in play here,\n # which means our read() returns decompressed data.\n #\n # This means the buffer can only meaningfully buffer decompressed data.\n # This makes this method prone to over-reading, and forcing too much\n # data into the buffer. That's unfortunate, but right now I'm not smart\n # enough to come up with a way to solve that problem.\n if self._fp is None and not self._buffer:\n return b''\n\n data = self._buffer\n\n with self._error_catcher():\n if amt is None:\n chunks = []\n async for chunk in self.stream(decode_content):\n chunks.append(chunk)\n data += b''.join(chunks)\n self._buffer = b''\n\n # We only cache the body data for simple read calls.\n self._body = data\n else:\n data_len = len(data)\n chunks = [data]\n streamer = self.stream(decode_content)\n\n while data_len < amt:\n try:\n chunk = next(streamer)\n except StopIteration:\n break\n else:\n chunks.append(chunk)\n data_len += len(chunk)\n\n data = b''.join(chunks)\n self._buffer = data[amt:]\n data = data[:amt]\n\n return data\n\n async def stream(self, decode_content=None):\n \"\"\"\n A generator wrapper for the read() method.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n \"\"\"\n # Short-circuit evaluation for exhausted responses.\n if self._fp is None:\n return\n\n self._init_decoder()\n if decode_content is None:\n decode_content = self.decode_content\n\n with self._error_catcher():\n async for raw_chunk in self._fp:\n self._fp_bytes_read += len(raw_chunk)\n decoded_chunk = self._decode(\n raw_chunk, decode_content, flush_decoder=False\n )\n if decoded_chunk:\n yield decoded_chunk\n\n # This branch is speculative: most decoders do not need to flush,\n # and so this produces no output. However, it's here because\n # anecdotally some platforms on which we do not test (like Jython)\n # do require the flush. For this reason, we exclude this from code\n # coverage. Happily, the code here is so simple that testing the\n # branch we don't enter is basically entirely unnecessary (it's\n # just a yield statement).\n final_chunk = self._decode(\n b'', decode_content, flush_decoder=True\n )\n if final_chunk: # Platform-specific: Jython\n yield final_chunk\n\n self._fp = None\n\n @classmethod\n def from_base(ResponseCls, r, **response_kw):\n \"\"\"\n Given an :class:`urllib3.base.Response` instance ``r``, return a\n corresponding :class:`urllib3.response.HTTPResponse` object.\n\n Remaining parameters are passed to the HTTPResponse constructor, along\n with ``original_response=r``.\n \"\"\"\n resp = ResponseCls(body=r.body,\n headers=r.headers,\n status=r.status_code,\n version=r.version,\n original_response=r,\n connection=r.body,\n **response_kw)\n return resp\n\n # Backwards-compatibility methods for httplib.HTTPResponse\n def getheaders(self):\n return self.headers\n\n def getheader(self, name, default=None):\n return self.headers.get(name, default)\n\n # Backwards compatibility for http.cookiejar\n def info(self):\n return self.headers\n\n # Overrides from io.IOBase\n def close(self):\n if not self.closed:\n self._fp.close()\n self._buffer = b''\n self._fp = None\n\n if self._connection:\n self._connection.close()\n\n @property\n def closed(self):\n # This method is required for `io` module compatibility.\n if self._fp is None and not self._buffer:\n return True\n elif hasattr(self._fp, 'complete'):\n return self._fp.complete\n else:\n return False\n\n def fileno(self):\n # This method is required for `io` module compatibility.\n if self._fp is None:\n raise IOError(\"HTTPResponse has no file to get a fileno from\")\n elif hasattr(self._fp, \"fileno\"):\n return self._fp.fileno()\n else:\n raise IOError(\"The file-like object this HTTPResponse is wrapped \"\n \"around has no file descriptor\")\n\n def readable(self):\n # This method is required for `io` module compatibility.\n return True\n\n def readinto(self, b):\n # This method is required for `io` module compatibility.\n temp = self.read(len(b))\n if len(temp) == 0:\n return 0\n else:\n b[:len(temp)] = temp\n return len(temp)\n\n def geturl(self):\n \"\"\"\n Returns the URL that was the source of this response.\n If the request that generated this response redirected, this method\n will return the final redirect location.\n \"\"\"\n if self.retries is not None and len(self.retries.history):\n return self.retries.history[-1].redirect_location\n else:\n return self._request_url\n", "sub_path": "src/urllib3/_async/response.py", "file_name": "response.py", "file_ext": "py", "file_size_in_byte": 16559, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib3.packages.six.binary_type", "line_number": 26, "usage_type": "call"}, {"api_name": "zlib.decompressobj", "line_number": 27, "usage_type": "call"}, {"api_name": "zlib.error", "line_number": 46, "usage_type": "attribute"}, {"api_name": "zlib.decompressobj", "line_number": 48, "usage_type": "call"}, {"api_name": "zlib.MAX_WBITS", "line_number": 48, "usage_type": "attribute"}, {"api_name": "zlib.decompressobj", "line_number": 65, "usage_type": "call"}, {"api_name": "zlib.MAX_WBITS", "line_number": 65, "usage_type": "attribute"}, {"api_name": "urllib3.packages.six.binary_type", "line_number": 72, "usage_type": "call"}, {"api_name": "zlib.error", "line_number": 78, "usage_type": "attribute"}, {"api_name": "zlib.decompressobj", "line_number": 90, "usage_type": "call"}, {"api_name": "zlib.MAX_WBITS", "line_number": 90, "usage_type": "attribute"}, {"api_name": "io.IOBase", "line_number": 100, "usage_type": "attribute"}, {"api_name": "_collections.HTTPHeaderDict", "line_number": 133, "usage_type": "argument"}, {"api_name": "_collections.HTTPHeaderDict", "line_number": 136, "usage_type": "call"}, {"api_name": "urllib3.packages.six.string_types", "line_number": 153, "usage_type": "name"}, {"api_name": "urllib3.packages.six.binary_type", "line_number": 153, "usage_type": "name"}, {"api_name": "util.is_fp_closed", "line_number": 199, "usage_type": "call"}, {"api_name": "zlib.error", "line_number": 226, "usage_type": "attribute"}, {"api_name": "exceptions.DecodeError", "line_number": 228, "usage_type": "call"}, {"api_name": "socket.timeout", "line_number": 263, "usage_type": "name"}, {"api_name": "exceptions.ReadTimeoutError", "line_number": 266, "usage_type": "call"}, {"api_name": "util.ssl_.BaseSSLError", "line_number": 268, "usage_type": "name"}, {"api_name": "exceptions.ReadTimeoutError", "line_number": 275, "usage_type": "call"}, {"api_name": "h11.ProtocolError", "line_number": 277, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 277, "usage_type": "name"}, {"api_name": "exceptions.ProtocolError", "line_number": 279, "usage_type": "call"}, {"api_name": "contextlib.contextmanager", "line_number": 248, "usage_type": "name"}]} +{"seq_id": "2263007", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom telegram.ext import Updater, CommandHandler\nfrom dotenv import load_dotenv, find_dotenv\nfrom os import getenv\nimport logging\nimport requests\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\nload_dotenv(find_dotenv())\n\ndef start(update, context):\n\tupdate.message.reply_text(\"I will send you HighDefinition DP from Instagram! Usage: /get username\")\n\ndef get_profile(update, context):\n\tno_account=\"Sorry, this page isn't available\"\n\tif len(update.message.text.split())!=2:\n\t\tupdate.message.reply_text(\"Usage: /get username\")\n\telse:\n\t\tusername=update.message.text.split()[-1]\n\t\turl = \"https://www.instagram.com/\"+username\n\n\t\tsource = requests.get(url).text\n\t\tif source.find(no_account)==-1:\n\t\t\tl = source.find(\"pic_url_hd\")+13\n\t\t\tr = source.find(\"requested_by_viewer\")-3\n\n\t\t\timg_url = source[l:r]\n\t\t\tupdate.message.reply_photo(photo=img_url)\n\t\telse:\n\t\t\tupdate.message.reply_text(\"This account could not be found, try again.\")\n\ndef main():\n\tupdater = Updater(getenv('token'), use_context=True)\n\tdp=updater.dispatcher\n\tdp.add_handler(CommandHandler('start', start))\n\tdp.add_handler(CommandHandler('get', get_profile))\n\tupdater.start_polling()\n\tupdater.idle()\n\nif __name__ == '__main__':\n\tmain()", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 1355, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.basicConfig", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 10, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 14, "usage_type": "call"}, {"api_name": "dotenv.find_dotenv", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 27, "usage_type": "call"}, {"api_name": "telegram.ext.Updater", "line_number": 38, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 38, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 40, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "223662278", "text": "import os\nimport jwt\nfrom flask import jsonify, request\n\nfrom candidacytracker import app, db, bcrypt\nfrom candidacytracker.models import User\n\n@app.route('/api/register', methods=['POST'])\ndef register():\n payload = request.get_json()\n try:\n data = jwt.decode(payload[\"token\"], app.config.get('SECRET_KEY'), algorithms=['HS256'])\n except KeyError:\n return jsonify({\n 'status': 'fail',\n 'message': 'No token provided.'\n })\n user = User.query.filter_by(email=data['email'])\n if not user.first():\n try:\n user = User(\n username=data['username'],\n email=data['email'],\n first_name=data['first_name'],\n last_name=data['last_name'],\n password=data['password']\n )\n\n db.session.add(user)\n db.session.commit()\n\n auth_token = user.encode_auth_token(user.id, user.first_name, user.last_name)\n responseObject = {\n 'status': 'success',\n 'message': 'Successfully registered.',\n 'auth_token': auth_token.decode()\n }\n return jsonify(responseObject)\n except Exception as e:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return jsonify(responseObject)\n else:\n responseObject = {\n 'status': 'fail',\n 'message': 'User already exists. Please Log in.',\n }\n return jsonify(responseObject)\n\n@app.route('/api/login', methods=['POST'])\ndef login():\n payload = request.get_json()\n try:\n data = jwt.decode(payload[\"token\"], app.config.get('SECRET_KEY'), algorithms=['HS256'])\n except KeyError:\n return jsonify({\n 'status': 'fail',\n 'message': 'No token provided.'\n })\n try:\n # fetch the user data\n user = User.query.filter_by(email=data['email']).first()\n is_password = bcrypt.check_password_hash(user.password, data['password'])\n if user and bcrypt.check_password_hash(user.password, data['password']):\n auth_token = user.encode_auth_token(str(user.id), user.first_name, user.last_name).decode('utf-8')\n return jsonify({\n 'status': 'success',\n 'message': 'Successfully logged in.',\n 'auth_token': auth_token\n })\n else:\n return jsonify({\n 'status': 'fail',\n 'message': 'User does not exist.'\n })\n except Exception as e:\n return jsonify({\n 'status': 'fail',\n 'message': 'Try again'\n })\n", "sub_path": "candidacytracker/apis/auth_api.py", "file_name": "auth_api.py", "file_ext": "py", "file_size_in_byte": 2759, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.request.get_json", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 10, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 12, "usage_type": "call"}, {"api_name": "candidacytracker.app.config.get", "line_number": 12, "usage_type": "call"}, {"api_name": "candidacytracker.app.config", "line_number": 12, "usage_type": "attribute"}, {"api_name": "candidacytracker.app", "line_number": 12, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 14, "usage_type": "call"}, {"api_name": "candidacytracker.models.User.query.filter_by", "line_number": 18, "usage_type": "call"}, {"api_name": "candidacytracker.models.User.query", "line_number": 18, "usage_type": "attribute"}, {"api_name": "candidacytracker.models.User", "line_number": 18, "usage_type": "name"}, {"api_name": "candidacytracker.models.User", "line_number": 21, "usage_type": "call"}, {"api_name": "candidacytracker.db.session.add", "line_number": 29, "usage_type": "call"}, {"api_name": "candidacytracker.db.session", "line_number": 29, "usage_type": "attribute"}, {"api_name": "candidacytracker.db", "line_number": 29, "usage_type": "name"}, {"api_name": "candidacytracker.db.session.commit", "line_number": 30, "usage_type": "call"}, {"api_name": "candidacytracker.db.session", "line_number": 30, "usage_type": "attribute"}, {"api_name": "candidacytracker.db", "line_number": 30, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 50, "usage_type": "call"}, {"api_name": "candidacytracker.app.route", "line_number": 8, "usage_type": "call"}, {"api_name": "candidacytracker.app", "line_number": 8, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 54, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 56, "usage_type": "call"}, {"api_name": "candidacytracker.app.config.get", "line_number": 56, "usage_type": "call"}, {"api_name": "candidacytracker.app.config", "line_number": 56, "usage_type": "attribute"}, {"api_name": "candidacytracker.app", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 58, "usage_type": "call"}, {"api_name": "candidacytracker.models.User.query.filter_by", "line_number": 64, "usage_type": "call"}, {"api_name": "candidacytracker.models.User.query", "line_number": 64, "usage_type": "attribute"}, {"api_name": "candidacytracker.models.User", "line_number": 64, "usage_type": "name"}, {"api_name": "candidacytracker.bcrypt.check_password_hash", "line_number": 65, "usage_type": "call"}, {"api_name": "candidacytracker.bcrypt", "line_number": 65, "usage_type": "name"}, {"api_name": "candidacytracker.bcrypt.check_password_hash", "line_number": 66, "usage_type": "call"}, {"api_name": "candidacytracker.bcrypt", "line_number": 66, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 68, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 79, "usage_type": "call"}, {"api_name": "candidacytracker.app.route", "line_number": 52, "usage_type": "call"}, {"api_name": "candidacytracker.app", "line_number": 52, "usage_type": "name"}]} +{"seq_id": "428004538", "text": "from rest_framework import status\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom django_start.apps.shop.serializers import ShopSerializer\n\n\nclass ShopView(APIView):\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n serializer = ShopSerializer(data=request.data)\n if serializer.is_valid():\n try:\n token = serializer.update(request.user.profile.shop, serializer.validated_data)\n return Response(status=status.HTTP_201_CREATED)\n except Exception as e:\n raise APIException(e)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n user = request.user\n data = {\n 'name': user.profile.shop.name,\n 'email': user.profile.shop.email,\n 'phone': user.profile.shop.phone,\n 'website': user.profile.shop.website,\n 'address': user.profile.shop.address,\n 'description': user.profile.shop.description,\n }\n return Response(data, status=status.HTTP_200_OK)", "sub_path": "django_start/django_start/apps/shop/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1242, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 11, "usage_type": "name"}, {"api_name": "django_start.apps.shop.serializers.ShopSerializer", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 18, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 18, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.APIException", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 22, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 34, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 34, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 34, "usage_type": "name"}]} +{"seq_id": "361727828", "text": "import os\nfrom io import BytesIO\nimport shutil\nfrom .CGIRunner import CGIRunner\nimport re\nfrom lxml import etree, objectify\nimport urllib.request\n\nADAGUC_PATH = os.getenv('ADAGUC_PATH', \" \")\n\n\nclass AdagucTestTools:\n def getLogFile(self):\n ADAGUC_LOGFILE = os.environ['ADAGUC_LOGFILE']\n try:\n f = open(ADAGUC_LOGFILE, encoding=\"utf-8\")\n data = f.read()\n f.close()\n return data\n except Exception:\n pass\n return \"\"\n \n def getLogFileSize(self):\n ADAGUC_LOGFILE = os.environ['ADAGUC_LOGFILE']\n file_stats = os.stat(ADAGUC_LOGFILE)\n return file_stats.st_size\n\n def printLogFile(self):\n print(\"\\n=== START ADAGUC LOGS ===\")\n print(self.getLogFile())\n print(\"=== END ADAGUC LOGS ===\")\n\n def runRemoteADAGUCServer(self, url=None):\n req = urllib.request.Request(url)\n content = urllib.request.urlopen(req)\n return [content.getcode(), content.read(), content.getheaders()]\n\n def runADAGUCServer(self, url=None, env=None, path=None, args=None, isCGI=True, showLogOnError=True, showLog=False, maxLogFileSize = 8192):\n\n if env is None:\n env = []\n\n adagucenv = os.environ.copy()\n adagucenv.update(env)\n\n ADAGUC_LOGFILE = os.environ['ADAGUC_LOGFILE']\n\n try:\n os.remove(ADAGUC_LOGFILE)\n except Exception:\n pass\n\n adagucexecutable = ADAGUC_PATH+\"/bin/adagucserver\"\n\n adagucargs = [adagucexecutable]\n\n if args is not None:\n adagucargs = adagucargs + args\n\n os.chdir(ADAGUC_PATH+\"/tests\")\n\n filetogenerate = BytesIO()\n status, headers, processErr = CGIRunner().run(adagucargs, url=url, output=filetogenerate,\n env=adagucenv, path=path, isCGI=isCGI)\n\n if (status != 0 and showLogOnError == True) or showLog == True:\n print(\"\\n\\n--- START ADAGUC DEBUG INFO ---\")\n print(\"Adaguc-server has non zero exit status %d \" % status)\n if isCGI == False:\n print(filetogenerate.getvalue().decode())\n else:\n self.printLogFile()\n if status == -9:\n print(\"Process: Killed\")\n if status == -11:\n print(\"Process: Segmentation Fault \")\n\n if len(headers) != 0:\n print(\"=== START ADAGUC HTTP HEADER ===\")\n print(headers)\n print(\"=== END ADAGUC HTTP HEADER ===\")\n else:\n print(\"Process: No HTTP Headers written\")\n\n print(\"--- END ADAGUC DEBUG INFO ---\\n\")\n return [status, filetogenerate, headers]\n\n else:\n # The executable wrote to stderr, which is unwanted behaviour. Stderr should be empty when running adaguc-server.\n if processErr:\n #print(processErr.decode()) \n print(\"[WARNING]: the process should not write to stderr\") \n # Check if the code did not write a too big logfile\n logfileSize = self.getLogFileSize()\n if logfileSize > maxLogFileSize:\n self.printLogFile()\n print(\"[WARNING]: Adaguc-server writes too many lines to the logfile, size = %d kilobytes\" % (logfileSize/1024))\n return [status, filetogenerate, headers]\n\n def writetofile(self, filename, data):\n with open(filename, 'wb') as f:\n f.write(data)\n\n def readfromfile(self, filename):\n adagucpath = os.getenv('ADAGUC_PATH')\n if adagucpath:\n filename = filename.replace(\"{ADAGUC_PATH}/\", adagucpath)\n with open(filename, 'rb') as f:\n return f.read()\n\n def cleanTempDir(self):\n ADAGUC_TMP = os.getenv('ADAGUC_TMP', 'adaguctmp')\n try:\n shutil.rmtree(ADAGUC_TMP)\n except Exception:\n pass\n self.mkdir_p(ADAGUC_TMP)\n return\n\n def mkdir_p(self, directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n def compareGetCapabilitiesXML(self, testresultFileLocation, expectedOutputFileLocation):\n expectedxml = self.readfromfile(expectedOutputFileLocation)\n testxml = self.readfromfile(testresultFileLocation)\n\n obj1 = objectify.fromstring(\n re.sub(b' xmlns=\"[^\"]+\"', b'', expectedxml, count=1))\n obj2 = objectify.fromstring(\n re.sub(b' xmlns=\"[^\"]+\"', b'', testxml, count=1))\n\n # Remove ADAGUC build date and version from keywordlists\n try:\n for child in obj1.findall(\"Service/KeywordList\")[0]:\n child.getparent().remove(child)\n for child in obj2.findall(\"Service/KeywordList\")[0]:\n child.getparent().remove(child)\n except Exception:\n pass\n try:\n for child in obj1.findall(\"Service/ServerInfo\")[0]:\n child.getparent().remove(child)\n for child in obj2.findall(\"Service/ServerInfo\")[0]:\n child.getparent().remove(child)\n except Exception:\n pass\n\n # Boundingbox extent values are too varying by different Proj libraries\n def removeBBOX(root):\n if root.tag.title() == \"Boundingbox\":\n # root.getparent().remove(root)\n try:\n del root.attrib[\"minx\"]\n del root.attrib[\"miny\"]\n del root.attrib[\"maxx\"]\n del root.attrib[\"maxy\"]\n except Exception:\n pass\n for elem in root.getchildren():\n removeBBOX(elem)\n\n removeBBOX(obj1)\n removeBBOX(obj2)\n\n result = etree.tostring(obj1)\n expect = etree.tostring(obj2)\n\n if (result == expect) is False:\n print(\"\\nExpected XML is different, file \\n\\\"%s\\\"\\n should be equal to \\n\\\"%s\\\"\" % (\n testresultFileLocation, expectedOutputFileLocation))\n\n return result == expect\n", "sub_path": "python/lib/adaguc/AdagucTestTools.py", "file_name": "AdagucTestTools.py", "file_ext": "py", "file_size_in_byte": 6054, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.getenv", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 26, "usage_type": "call"}, {"api_name": "urllib.request.request.Request", "line_number": 35, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 35, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 35, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 36, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 36, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 36, "usage_type": "name"}, {"api_name": "os.environ.copy", "line_number": 44, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 50, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 61, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 63, "usage_type": "call"}, {"api_name": "CGIRunner.CGIRunner", "line_number": 64, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 106, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 113, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 115, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 123, "usage_type": "call"}, {"api_name": "lxml.objectify.fromstring", "line_number": 129, "usage_type": "call"}, {"api_name": "lxml.objectify", "line_number": 129, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 130, "usage_type": "call"}, {"api_name": "lxml.objectify.fromstring", "line_number": 131, "usage_type": "call"}, {"api_name": "lxml.objectify", "line_number": 131, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 132, "usage_type": "call"}, {"api_name": "lxml.etree.tostring", "line_number": 167, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 167, "usage_type": "name"}, {"api_name": "lxml.etree.tostring", "line_number": 168, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 168, "usage_type": "name"}]} +{"seq_id": "628560205", "text": "import os\nimport numpy\nimport pydicom\nimport matplotlib.pylab as plt\n\nDECISION_THRESHOLD = 2\nDISTANCE_THRESHOLD = 32\nFIGURE_SCOPE = 32\n\nif __name__ == '__main__':\n LIDCPath = 'E:/LIDC/LIDC-IDRI/'\n NoduleRecordsPath = 'E:/LIDC/TreatmentTrace/Step2-MediaPosition/'\n NoduleMediaPath = 'E:/LIDC/TreatmentTrace/Step3-NoduleMedia/'\n FinalDecisionPath = 'E:/LIDC/TreatmentTrace/Step4-FinalDecision/'\n SavePath = 'E:/LIDC/TreatmentTrace/Step5-NodulesCsv-Seperate/'\n for InstanceName in os.listdir(FinalDecisionPath):\n if os.path.exists(os.path.join(SavePath, InstanceName)): continue\n os.makedirs(os.path.join(SavePath, InstanceName))\n\n ######################################################################################\n\n filenameDictionary = {}\n indexA = os.listdir(os.path.join(LIDCPath, InstanceName[0:InstanceName.find('.')]))[0]\n indexB = os.listdir(os.path.join(LIDCPath, InstanceName[0:InstanceName.find('.')], indexA))[0]\n for indexC in os.listdir(os.path.join(LIDCPath, InstanceName[0:InstanceName.find('.')], indexA, indexB)):\n if indexC[-3:] != 'dcm': continue\n # print(indexC)\n DCMFile = pydicom.read_file(\n os.path.join(LIDCPath, InstanceName[0:InstanceName.find('.')], indexA, indexB, indexC))\n filenameDictionary[DCMFile.SOPInstanceUID] = indexC\n\n # print(InstanceName, filenameDictionary)\n ######################################################################################\n\n with open(os.path.join(FinalDecisionPath, InstanceName), 'r') as file:\n data = file.readlines()\n\n decisionNodulesDetails = []\n\n for sample in data:\n decisionNodulesDetails.append(sample[0:-1].split(','))\n for index in range(1, len(decisionNodulesDetails[-1])):\n decisionNodulesDetails[-1][index] = float(decisionNodulesDetails[-1][index])\n\n noduleRecords = set()\n for treatNodule in decisionNodulesDetails:\n if treatNodule[-1] < DECISION_THRESHOLD: continue\n print(InstanceName, treatNodule)\n\n noduleMediaData = numpy.genfromtxt(fname=os.path.join(NoduleMediaPath, InstanceName), dtype=str,\n delimiter=',')\n for sample in noduleMediaData:\n currentPosition = []\n for index in range(1, len(sample)):\n currentPosition.append(float(sample[index]))\n\n distance = numpy.sum(numpy.abs(numpy.subtract(currentPosition, treatNodule[1:-1])))\n if distance < DISTANCE_THRESHOLD:\n noduleRecords.add(sample[0])\n # print(noduleRecords)\n\n for chooseNodule in noduleRecords:\n if os.path.exists(os.path.join(SavePath, InstanceName, chooseNodule)): continue\n os.makedirs(os.path.join(SavePath, InstanceName, chooseNodule))\n # print(chooseNodule)\n\n nodulePosition = numpy.genfromtxt(\n fname=os.path.join(NoduleRecordsPath, InstanceName[0:InstanceName.find('.')], chooseNodule,\n 'Position.csv'), dtype=str, delimiter=',')\n # print(nodulePosition)\n chooseNoduleDictionary = set()\n for sample in nodulePosition:\n chooseNoduleDictionary.add(sample[0])\n # print(chooseNoduleDictionary)\n\n for UID in chooseNoduleDictionary:\n dcmPosition = []\n for sample in nodulePosition:\n if sample[0] == UID:\n dcmPosition.append([float(sample[1]), float(sample[2])])\n [yPosition, xPosition] = numpy.median(dcmPosition, axis=0)\n\n xPosition = int(xPosition)\n yPosition = int(yPosition)\n\n if xPosition < FIGURE_SCOPE: xPosition = FIGURE_SCOPE\n if xPosition > 512 - FIGURE_SCOPE: xPosition = 512 - FIGURE_SCOPE\n if yPosition < FIGURE_SCOPE: yPosition = FIGURE_SCOPE\n if yPosition > 512 - FIGURE_SCOPE: yPosition = 512 - FIGURE_SCOPE\n xPosition -= FIGURE_SCOPE\n yPosition -= FIGURE_SCOPE\n\n if UID not in filenameDictionary.keys(): continue\n DCMFile = pydicom.read_file(\n os.path.join(LIDCPath, InstanceName[0:InstanceName.find('.')], indexA, indexB,\n filenameDictionary[UID]))\n # print(xPosition, yPosition)\n\n # plt.imshow(\n # DCMFile.pixel_array[xPosition:xPosition + 2 * FIGURE_SCOPE, yPosition:yPosition + 2 * FIGURE_SCOPE])\n # plt.show()\n\n fileCounter = 0\n while True:\n fileCounter += 1\n if not os.path.exists(\n os.path.join(SavePath, InstanceName, chooseNodule, 'Part%04d.csv' % fileCounter)):\n break\n\n with open(\n os.path.join(SavePath, InstanceName, chooseNodule, 'Part%04d.csv' % fileCounter),\n 'w') as file:\n for indexX in range(2 * FIGURE_SCOPE):\n for indexY in range(2 * FIGURE_SCOPE):\n if indexY != 0: file.write(',')\n file.write(str(DCMFile.pixel_array[indexX + xPosition, indexY + yPosition]))\n file.write('\\n')\n # exit()\n\n # exit()\n", "sub_path": "LIDC_Project/Records/Trace/Pretreatment/Step5_FinalExtraction_Seperate.py", "file_name": "Step5_FinalExtraction_Seperate.py", "file_ext": "py", "file_size_in_byte": 5547, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pydicom.read_file", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "numpy.genfromtxt", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.subtract", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.genfromtxt", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.median", "line_number": 81, "usage_type": "call"}, {"api_name": "pydicom.read_file", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path", "line_number": 107, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}]} +{"seq_id": "432321300", "text": "import numpy as np\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport datetime as dt\n\nnum_updates = 500 # Total number of Policy updates\nepisodes_batch = 5 # Chose a higher value for stabler G^{-1} estimates --- LOWER to 5 once stable\nmax_time_steps = 200 # Maximum number of timesteps into the environment\npolicy_lr = 7e-4 #0.025 # Learning rate for updating the policy parameters\nhidden_1 = 10\n\nseed_value = 0\ntorch.manual_seed(seed_value)\nnp.random.seed(seed_value)\n\n\nclass Policy(nn.Module):\n def __init__(self, state_dim, action_dim, action_lim): # The policy network we use is slightly different from ORIGINAL paper\n super(Policy, self).__init__() # state_dim (2) ---> hidden dim (10) ---> action_dim (1)\n self.fc1 = nn.Linear(state_dim, hidden_1).double()\n self.fc1.weight.data.normal_(0, 0.4) # 0.4 is chosen to comply with Glorot initialization. TRY 0.01 if 0.4 does not work !!!\n self.lin_out = nn.Linear(hidden_1, action_dim).double()\n self.lin_out.weight.data.normal_(0, 0.4) # 0.4 is chosen to comply with Glorot initialization\n\n def forward(self, x):\n x = self.fc1(x)\n x = nn.Tanh()(x)\n x = self.lin_out(x)\n action = nn.Tanh()(x)\n return action\n\nenv = gym.make('MountainCarContinuous-v0')\n#env = gym.make('Pendulum-v0')\nenv.seed(seed_value)\n\nstate_dim = env.observation_space.shape[0] # state_dim = 2\naction_dim = env.action_space.shape[0] # action_dim = 1\naction_lim = env.action_space.high[0] # action_lim = 1.0\n\nnum_network_params = state_dim*hidden_1+hidden_1+hidden_1*action_dim+action_dim\n\npolicy = Policy(state_dim, action_dim, action_lim)\npolicy_optimizer = optim.Adam(policy.parameters(), lr=policy_lr)\n#policy_optimizer = optim.SGD(policy.parameters(), lr=policy_lr)\n\nfor update_id in range(num_updates):\n\tstart_time = dt.datetime.now()\n\tstate_action_buffer = [] # Resulting shape of this list = [episodes_batch, episode_time_steps (varies with episode), 4]\n\tavg_cumulative_reward = 0 # Average total reward of an episode\n\tfor _ in range(episodes_batch):\n\t\tepisode_reward = 0\t\t\t\t\t\t\t\t\t\t # Individual total reward for the current episode\n\t\ttime_steps = 0\t\t\t\t\t\t\t\t\t\t\t # To terminate an episode of time_steps exceeds max_time_steps\n\t\tepisode_buffer = []\t\t\t\t\t\t\t\t\t\t # Resulting shape of this list = [episode_time_steps (varies with episode), 4]\n\t\tobservation = env.reset()\n\t\tdone = False\n\t\twhile not done and time_steps < max_time_steps:\n\t\t\t# env.render()\n\t\t\taction_mean = policy(torch.from_numpy(np.float64(observation)))\n\t\t\taction_std = nn.Parameter(torch.ones(action_dim, dtype = torch.float64))\n\t\t\taction_sample = torch.normal(action_mean, action_std).detach()\n\t\t\tnew_observation, reward, done, info = env.step(action_sample)\n\t\t\tepisode_reward += reward # reward.numpy()\n\t\t\tepisode_buffer.append([np.array(observation), action_mean, action_sample, reward]) # both action_mean and action_sample are stored so as\n\t\t\tobservation = new_observation\t\t\t\t\t\t\t\t\t\t\t\t\t\t # to compute the log_prob and U and Fisher information matrix\n\t\t\ttime_steps += 1\n\t\tstate_action_buffer.append(np.array(episode_buffer))\n\t\tavg_cumulative_reward += episode_reward\n\tavg_cumulative_reward /= episodes_batch\n\n\tparams = list(policy.parameters()) # a list of all the parameters in our policy network\n\tfisher_matrix_estimate = np.eye((num_network_params), dtype = np.float64)\n\tinv_fisher_matrix_estimate = np.eye((num_network_params), dtype = np.float64)\n\tU_theta_matrices = [] # Resulting list has a shape = [episodes_batch, episode_time_steps (varies with episode), 41 (gradient of log_prob w.r.t all policy parameters)]\n\tcount = 1 # Used to compute the average fisher_matrix_estimate, we start with 1 to account for the identity matrix initialization of FIM\n\tfor i in range(episodes_batch):\n\t\tU_theta_matrix = [] # # Resulting list has a shape = [episode_time_steps (varies with episode), 41 (gradient of log_prob w.r.t all policy parameters)]\n\t\tfor s_a_r in state_action_buffer[i]: # For each token from the sampled trajectories, we compute action log_prob and u_theta = grad_{policy_params}(log_prob)\n\t\t\tcount += 1\n\t\t\tstate = s_a_r[0]\n\t\t\taction_mean = s_a_r[1]\n\t\t\taction = s_a_r[2]\n\t\t\treward = s_a_r[3]\n\t\t\tlog_prob = -(action-action_mean).pow(2)/2 # STD and constant terms are omitted on purpose as their grad would be 0\n\t\t\tpolicy.zero_grad()\n\t\t\tlog_prob.backward()\n\t\t\tu_theta = np.concatenate((params[0].grad.numpy().flatten(), params[1].grad.numpy(), params[2].grad.numpy().flatten(), params[3].grad.numpy()))\n\t\t\tU_theta_matrix.append(u_theta) # In case we run into memory issues later, we can only store the u_theta of dictionary elements instead\n\n\t\t\tinv_count = 1/count\n\t\t\tfisher_matrix_estimate = (1-inv_count)*fisher_matrix_estimate + inv_count*np.matmul(u_theta.reshape(num_network_params,1), u_theta.reshape(1,num_network_params))\n\t\t\ttemp_comp = np.matmul(inv_fisher_matrix_estimate, u_theta).reshape(num_network_params,1)\n\t\t\tinv_fisher_matrix_estimate = inv_fisher_matrix_estimate - inv_count*np.matmul(temp_comp, temp_comp.T)/(1-inv_count+inv_count*np.matmul(u_theta,temp_comp))\n\t\t\tinv_fisher_matrix_estimate /= (1-inv_count)\n\n\t\tU_theta_matrices.append(np.transpose(np.array(U_theta_matrix)))\n\n\t# fisher_matrix_estimate /= np.linalg.det(fisher_matrix_estimate)\t\t\t# Normalization of FIM does not seem possible as the FIM is singular, i.e. DET(FIM) = 0 even\\\n\t# inv_fisher_matrix_estimate *= np.linalg.det(fisher_matrix_estimate) # though we started with identity matrix initialization. This is concerning as the product of \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# the computed FIM and inverse FIM is Approximately IDENTITY MATRIX !!!\n\n\t# inv_fisher_matrix_estimate = np.linalg.inv(fisher_matrix_estimate)\n\t# np.linalg.inv() is unstable and inaccurate for nearly singualar matrices. Its inverse of inverse is way off from the original matrix. \n\t# Must be replaced with NP.EYE(41) and computed using Sherman-Morrison matrix inversion lemma for all the u_theta's\n\t# This approach is unstable as well\n\t###########################################################################################################################################################\n\t#GPTD ALGORITHM\n\n\tGAMMA = 0.99\n\tsigma = 0.2\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Hyperparams chosen as suggested in the original BAC paper\n\tv_threshold = 0.1\n\tsigma_k = np.array([1.3,0.25]) # For mountain car <==> np.array([1.3,0.25])\n\n\tdef state_kernel(ind1, ind2, episode_batch_num):\n\t\ts1 = state_action_buffer[episode_batch_num][ind1][0]\n\t\ts2 = state_action_buffer[episode_batch_num][ind2][0]\n\t\treturn np.exp(np.sum(-(s1-s2)*(s1-s2)/(2*sigma_k*sigma_k)))\n\n\tdef state_action_kernel(ind1, ind2, episode_batch_num):\n\t\tu1 = U_theta_matrices[episode_batch_num][:,ind1]\n\t\tu2 = U_theta_matrices[episode_batch_num][:,ind2]\n\t\treturn np.matmul(np.matmul(u1.T,inv_fisher_matrix_estimate),u2) # k(z1,z2) = u(z1).T * G^{-1} * u(z2)\n\tdef kernel(ind1, ind2, episode_batch_num):\n\t\treturn state_kernel(ind1, ind2, episode_batch_num) + state_action_kernel(ind1, ind2, episode_batch_num)\n\tdef k_meth(ind2, dictionary, episode_batch_num):\n\t\tk_list = []\n\t\tfor ind1 in dictionary:\n\t\t\tk_list.append(kernel(ind1, ind2, episode_batch_num))\n\t\treturn np.asarray(k_list) # Shape = (dictionary_size,)\n\tdef K_meth(dictionary, episode_batch_num):\n\t\tK_list = []\n\t\tfor ind2 in dictionary:\n\t\t\tK_list.append(k_meth(ind2, dictionary, episode_batch_num))\n\t\treturn np.asarray(K_list) # Shape = (dictionary_size, dictionary_size)\n\n\tpolicy_gradient = np.zeros(num_network_params, dtype = np.float64)\n\tavg_episode_time = 0\n\tfor i in range(episodes_batch):\n\t\tdictionary = []\t\t\t\t\t\t\t\t\t\t\t\t\t # Stores the indices of elements, i.e. their time_step in the episode\n\t\tU_dict = []\t\t\t\t\t\t\t\t\t\t\t\t\t\t # Stores the u_theta for all the elements in the dictionary\n\t\tfor current_time_step, s_a_r in enumerate(state_action_buffer[i]):\n\t\t\tif current_time_step == 0: # Setting the initial values at the start of each episode\n\t\t\t\tdictionary.append(0)\n\t\t\t\t# prev_x_t = np.concatenate([state_action_buffer[i][0],state_action_buffer[i][2]])\n\t\t\t\tprev_a_t = np.ones(1, dtype = np.float64)\n\t\t\t\tprev_alpha_t = np.zeros(1, dtype = np.float64)\n\t\t\t\tprev_C_t = np.zeros((1,1), dtype = np.float64)\n\t\t\t\tprev_c_t = np.zeros(1, dtype = np.float64)\n\t\t\t\tprev_d_t = 0\n\t\t\t\tprev_inv_s_t = 0\n\t\t\t\tprev_K_inv = np.asarray([[1/kernel(0,0,i)]], dtype = np.float64)\n\t\t\t\tprev_k_meth_x_t = k_meth(current_time_step,dictionary,i) # Follows the Online Monte Carlo GPTD algorithm in \\\n\t\t\t\tU_dict.append(U_theta_matrices[i][:,0]) # (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.75.5939&rep=rep1&type=pdf)\n\t\t\t\tcontinue\n\n\t\t\t# x_t = np.concatenate([state_action_buffer[i][0],state_action_buffer[i][2]])\n\t\t\tprev_r_t = s_a_r[3]\n\t\t\tk_meth_x_t = k_meth(current_time_step,dictionary,i)\n\t\t\tprev_k_meth_x_t = k_meth(current_time_step-1,dictionary,i) # inspect half asleep\n\t\t\ta_t = np.matmul(prev_K_inv, k_meth_x_t)\n\t\t\tdelta_t = kernel(current_time_step,current_time_step,i) - np.matmul(k_meth_x_t,a_t)\n\t\t\tdelta_k_t = prev_k_meth_x_t - GAMMA*k_meth_x_t\n\t\t\tif delta_t > v_threshold:\n\t\t\t\ttemp_00 = delta_t*prev_K_inv+np.matmul(np.expand_dims(a_t,0).T,np.expand_dims(a_t,0))\n\t\t\t\ttemp_v = np.vstack([temp_00,-a_t])\n\t\t\t\ttemp_h = np.concatenate([-a_t,np.array([1])])\n\t\t\t\tK_inv = np.hstack([temp_v,np.expand_dims(temp_h,1)])/delta_t\n\n\t\t\t\ta_t = np.zeros(K_inv.shape[0], dtype = np.float64)\n\t\t\t\ta_t[-1] = 1\n\t\t\t\th_t = np.concatenate((prev_a_t,[-GAMMA]))\n\n\t\t\t\tdelta_k_tt = np.matmul(prev_a_t,(prev_k_meth_x_t - 2*GAMMA*k_meth_x_t)) + GAMMA*GAMMA*kernel(current_time_step,current_time_step,i)\n\t\t\t\tc_t = GAMMA*sigma*sigma*prev_inv_s_t*np.concatenate([prev_c_t,[0]])+h_t-np.concatenate([np.matmul(prev_C_t,delta_k_t),[0]])\n\t\t\t\td_t = GAMMA*sigma*sigma*prev_inv_s_t*prev_d_t + prev_r_t - np.matmul(delta_k_t,prev_alpha_t)\n\n\t\t\t\ttemp_0 = (1+GAMMA*GAMMA)*sigma*sigma + delta_k_tt - np.matmul(np.matmul(delta_k_t,prev_C_t),delta_k_t)\n\t\t\t\ttemp_1 = 2*GAMMA*sigma*sigma*prev_inv_s_t*np.matmul(prev_c_t,delta_k_t) - GAMMA*GAMMA*sigma*sigma*sigma*sigma*prev_inv_s_t\n\t\t\t\tinv_s_t = 1/(temp_0+temp_1)\n\n\t\t\t\tprev_alpha_t = np.concatenate([prev_alpha_t,[0]])\n\t\t\t\tprev_C_t = np.vstack([np.hstack([prev_C_t,np.zeros((len(prev_C_t),1), dtype = np.float64)]),np.zeros(len(prev_C_t)+1, dtype = np.float64)])\n\n\t\t\t\tdictionary.append(current_time_step)\n\t\t\t\tU_dict.append(U_theta_matrices[i][:,current_time_step])\n\n\t\t\telse:\n\t\t\t\th_t = prev_a_t - GAMMA*a_t\n\t\t\t\tdelta_k_tt = np.matmul(h_t,delta_k_t)\n\t\t\t\tc_t = GAMMA*sigma*sigma*prev_inv_s_t*prev_c_t+h_t-np.matmul(prev_C_t,delta_k_t)\n\n\t\t\t\ttemp_0 = (1+GAMMA*GAMMA)*sigma*sigma - GAMMA*GAMMA*sigma*sigma*sigma*sigma*prev_inv_s_t\n\t\t\t\ttemp_1 = np.matmul(delta_k_t, c_t+GAMMA*sigma*sigma*prev_inv_s_t*prev_c_t)\n\t\t\t\tinv_s_t = 1/(temp_0+temp_1)\n\n\t\t\t\td_t = prev_d_t\n\t\t\t\tK_inv = prev_K_inv.copy()\n\n\t\t\talpha_t = prev_alpha_t + c_t*inv_s_t*d_t\n\t\t\tC_t = prev_C_t+np.matmul(np.expand_dims(c_t,1),np.expand_dims(c_t,1).T)*inv_s_t\n\n\t\t\tprev_alpha_t = alpha_t.copy()\n\t\t\tprev_C_t = C_t.copy()\n\t\t\t# prev_x_t = x_t.copy()\n\t\t\tprev_a_t = a_t.copy()\n\t\t\tprev_c_t = c_t.copy()\n\t\t\tprev_inv_s_t = inv_s_t\n\t\t\tprev_d_t = d_t\n\t\t\tprev_k_meth_x_t = k_meth_x_t.copy()\n\t\t\tprev_K_inv = K_inv.copy()\n\n\t\t\t# print(\"###########################################################################################################\")\n\t\t\t# print(\"k_meth_x_t ------------------------------------------------------\")\n\t\t\t# print(prev_k_meth_x_t)\n\t\t\t# print(\"a_t -------------------------------------------------------------\")\n\t\t\t# print(a_t)\n\t\t\t# print(\"delta_t ---------------------------------------------------------\")\n\t\t\t# print(delta_t)\n\t\t\t# print(\"delta_k_t -------------------------------------------------------\")\n\t\t\t# print(delta_k_t)\n\t\t\t# print(\"K_inv -----------------------------------------------------------\")\n\t\t\t# print(prev_K_inv)\n\t\t\t# print(\"h_t -------------------------------------------------------------\")\n\t\t\t# print(h_t)\n\t\t\t# print(\"delta_k_tt ------------------------------------------------------\")\n\t\t\t# print(delta_k_tt)\n\t\t\t# print(\"c_t -------------------------------------------------------------\")\n\t\t\t# print(prev_c_t)\n\t\t\t# print(\"d_t -------------------------------------------------------------\")\n\t\t\t# print(prev_d_t)\n\t\t\t# print(\"inv_s_t --------------------------------------------------------\")\n\t\t\t# print(prev_inv_s_t)\n\t\t\t# print(\"alpha_t ---------------------------------------------------------\")\n\t\t\t# print(prev_alpha_t)\n\t\t\t# print(\"C_t -------------------------------------------------------------\")\n\t\t\t# print(prev_C_t)\n\t\t\t# print(\"dictionary_me ------------------------------------------------------\")\n\t\t\t# print(dictionary)\n\t\t\t# print(\"###########################################################################################################\")\n\t\t\t# input(\"halt\")\n\n\t\t#policy_gradient += np.matmul(inv_fisher_matrix_estimate,np.matmul(np.array(U_dict).T,alpha_t)) # Natural Policy Gradient\n\t\tpolicy_gradient += np.matmul(np.array(U_dict).T,alpha_t) # Ordinary Policy Gradient\n\t\tavg_episode_time += len(state_action_buffer[i])\n\tpolicy_gradient /= episodes_batch # Averaged over episodes_batch\n\tavg_episode_time /= episodes_batch\n\tmax_grad_val = policy_gradient.max()\n\n\tupdate_0 = policy_gradient[:state_dim*hidden_1].reshape((hidden_1,state_dim))\n\tupdate_1 = policy_gradient[state_dim*hidden_1:state_dim*hidden_1+hidden_1].reshape((hidden_1,)) # Grouping the params into weights and biases\n\tupdate_2 = policy_gradient[state_dim*hidden_1+hidden_1:state_dim*hidden_1+hidden_1+hidden_1*action_dim].reshape((action_dim,hidden_1))\n\tupdate_3 = policy_gradient[state_dim*hidden_1+hidden_1+hidden_1*action_dim:state_dim*hidden_1+hidden_1+hidden_1*action_dim+action_dim]\n\n\tpolicy_optimizer.zero_grad()\n\n\tparams = list(policy.parameters())\n\tparams[0].grad = torch.DoubleTensor(update_0)\n\tparams[1].grad = torch.DoubleTensor(update_1)\n\tparams[2].grad = torch.DoubleTensor(update_2) # Manually feed the param.grad for each parameter\n\tparams[3].grad = torch.DoubleTensor(update_3)\n\n\tpolicy_optimizer.step()\t\t\t\t\t\t\t\t\t\t\t\t\t# Adam Optimizer is used to update the params\n\t# print(update_3)\n\tprint(\"{:4d}th update completed - Reward: {:7.2f} - Avg timesteps: {:4d} - Time elapsed: {:3d}sec - max grad value: {:7.4f} - Dict size: {:3d}\".format(\n\t\t(update_id+1),avg_cumulative_reward,int(avg_episode_time),(dt.datetime.now()-start_time).seconds, max_grad_val, len((dictionary))))\n\t#input(\"halt\")", "sub_path": "BAC.py", "file_name": "BAC.py", "file_ext": "py", "file_size_in_byte": 15174, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.manual_seed", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 18, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Tanh", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Tanh", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "gym.make", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 47, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.float64", "line_number": 63, "usage_type": "attribute"}, {"api_name": "torch.normal", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.eye", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 76, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 148, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 150, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 151, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 154, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 172, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 185, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 246, "usage_type": "call"}, {"api_name": "torch.DoubleTensor", "line_number": 260, "usage_type": "call"}, {"api_name": "torch.DoubleTensor", "line_number": 261, "usage_type": "call"}, {"api_name": "torch.DoubleTensor", "line_number": 262, "usage_type": "call"}, {"api_name": "torch.DoubleTensor", "line_number": 263, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 268, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 268, "usage_type": "attribute"}]} +{"seq_id": "556351603", "text": "# -*- coding:utf-8 -*-\n\nimport urllib.request as request\nimport http\nimport ssl\nimport requests\n\nrequests.get()\n\n#自定义opener \n# 之前我们使用的是urlopen()\n# request.urlopen()\n# https_handler = HTTPSHandler(context=context)\n# opener = build_opener(https_handler)\n\ncontext = ssl._create_unverified_context()\n# 构建一个HTTPSHandler 处理器对象,支持处理HTTP请求\nhttps_handler = request.HTTPSHandler(context=context,debuglevel=1)\nopener = request.build_opener(https_handler)\n# 构建一个HTTPHandler 处理器对象,支持处理HTTPS请求\n# http_handler = request.HTTPHandler()\n# 调用urllib.request.Request方法,创建支持处理HTTP请求的opener对象\n# opener = request.build_opener(http_handler)\nreq_header = {\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0',\n}\nurl = 'http://www.baidu.com'\nreq = request.Request(url)\nresponse = opener.open(url)\n# print(response.read().decode('utf-8'))\nprint(response.code)", "sub_path": "复习/pachong/教学代码/第三天/build_opener2.py", "file_name": "build_opener2.py", "file_ext": "py", "file_size_in_byte": 999, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "ssl._create_unverified_context", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request.HTTPSHandler", "line_number": 18, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 18, "usage_type": "name"}, {"api_name": "urllib.request.build_opener", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 19, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 28, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 28, "usage_type": "name"}]} +{"seq_id": "119394110", "text": "import jwt\nfrom django.conf import settings\nfrom rest_framework import mixins\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom common import tools\n\nclass CustomCreate(mixins.CreateModelMixin):\n \"\"\"\n Create a model instance.\n \"\"\"\n def create(self, request, *args, **kwargs):\n userId = request.user.id\n token = None\n if 'Authorization' in request.headers and request.headers['Authorization'] != '':\n token = request.headers['Authorization'].split(\" \")[1]\n if token:\n user = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256', do_time_check=True)\n userId = user['user_id']\n request.data.__setitem__('user', {\n 'type': 'User',\n 'id': userId\n })\n request = tools.save_base64_picture(request)\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n\nclass CustomUpdate(mixins.UpdateModelMixin):\n \"\"\"\n Update a model instance.\n \"\"\"\n def update(self, request, *args, **kwargs):\n partial = kwargs.pop('partial', False)\n instance = self.get_object()\n if 'user' in request.data:\n del request.data['user']\n request = tools.save_base64_picture(request)\n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n\n if getattr(instance, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n instance._prefetched_objects_cache = {}\n\n return Response(serializer.data)\n\n\nclass CountRetrieve(mixins.RetrieveModelMixin):\n \"\"\"\n Retrieve a model instance.\n \"\"\"\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n if 'views' in serializer.data:\n views = instance.views\n views += 1\n serializer = self.get_serializer(\n instance,\n data = {\n 'views': views \n },\n partial=True\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data)\n", "sub_path": "common/mixins.py", "file_name": "mixins.py", "file_ext": "py", "file_size_in_byte": 2520, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rest_framework.mixins.CreateModelMixin", "line_number": 8, "usage_type": "attribute"}, {"api_name": "rest_framework.mixins", "line_number": 8, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.settings.SECRET_KEY", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 18, "usage_type": "name"}, {"api_name": "common.tools.save_base64_picture", "line_number": 24, "usage_type": "call"}, {"api_name": "common.tools", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 29, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 29, "usage_type": "name"}, {"api_name": "rest_framework.mixins.UpdateModelMixin", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rest_framework.mixins", "line_number": 32, "usage_type": "name"}, {"api_name": "common.tools.save_base64_picture", "line_number": 41, "usage_type": "call"}, {"api_name": "common.tools", "line_number": 41, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.mixins.RetrieveModelMixin", "line_number": 54, "usage_type": "attribute"}, {"api_name": "rest_framework.mixins", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 73, "usage_type": "call"}]} +{"seq_id": "278400828", "text": "\"\"\"refactor group owners and managers to groups_users_association.\n\nRevision ID: 902fbdab393a\nRevises: d09db0106be9\nCreate Date: 2016-11-23 15:33:57.834197\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '902fbdab393a'\ndown_revision = 'd09db0106be9'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('groups_users_association',\n sa.Column('group_id', sa.String(length=32), nullable=False),\n sa.Column('user_id', sa.String(length=32), nullable=False),\n sa.Column('manager', sa.Boolean(), nullable=True),\n sa.Column('owner', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['group_id'], ['groups.id'], name=op.f('fk_groups_users_association_group_id_groups')),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('fk_groups_users_association_user_id_users')),\n sa.PrimaryKeyConstraint('group_id', 'user_id', name=op.f('pk_groups_users_association'))\n )\n op.drop_table('groups_managers')\n op.drop_table('groups_users')\n op.drop_constraint(u'fk_groups_owner_id_users', 'groups', type_='foreignkey')\n op.drop_column('groups', 'owner_id')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('groups', sa.Column('owner_id', sa.VARCHAR(length=32), autoincrement=False, nullable=True))\n op.create_foreign_key(u'fk_groups_owner_id_users', 'groups', 'users', ['owner_id'], ['id'])\n op.create_table('groups_users',\n sa.Column('group_id', sa.VARCHAR(length=32), autoincrement=False, nullable=False),\n sa.Column('user_id', sa.VARCHAR(length=32), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['group_id'], [u'groups.id'], name=u'fk_groups_users_group_id_groups'),\n sa.ForeignKeyConstraint(['user_id'], [u'users.id'], name=u'fk_groups_users_user_id_users'),\n sa.PrimaryKeyConstraint('group_id', 'user_id', name=u'pk_groups_users')\n )\n op.create_table('groups_managers',\n sa.Column('group_id', sa.VARCHAR(length=32), autoincrement=False, nullable=False),\n sa.Column('manager_id', sa.VARCHAR(length=32), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['group_id'], [u'groups.id'], name=u'fk_groups_managers_group_id_groups'),\n sa.ForeignKeyConstraint(['manager_id'], [u'users.id'], name=u'fk_groups_managers_manager_id_users'),\n sa.PrimaryKeyConstraint('group_id', 'manager_id', name=u'pk_groups_managers')\n )\n op.drop_table('groups_users_association')\n ### end Alembic commands ###\n", "sub_path": "migrations/versions/902fbdab393a_.py", "file_name": "902fbdab393a_.py", "file_ext": "py", "file_size_in_byte": 2594, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "alembic.op.create_table", "line_number": 19, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Boolean", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Boolean", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 24, "usage_type": "call"}, {"api_name": "alembic.op.f", "line_number": 24, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 24, "usage_type": "name"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 25, "usage_type": "call"}, {"api_name": "alembic.op.f", "line_number": 25, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 25, "usage_type": "name"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 26, "usage_type": "call"}, {"api_name": "alembic.op.f", "line_number": 26, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 26, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 28, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 28, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 29, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 29, "usage_type": "name"}, {"api_name": "alembic.op.drop_constraint", "line_number": 30, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 30, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 31, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 31, "usage_type": "name"}, {"api_name": "alembic.op.add_column", "line_number": 37, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 37, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 37, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 37, "usage_type": "call"}, {"api_name": "alembic.op.create_foreign_key", "line_number": 38, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 38, "usage_type": "name"}, {"api_name": "alembic.op.create_table", "line_number": 39, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 39, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 42, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 43, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 44, "usage_type": "call"}, {"api_name": "alembic.op.create_table", "line_number": 46, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 46, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 47, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 47, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 51, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 53, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 53, "usage_type": "name"}]} +{"seq_id": "192057964", "text": "from tempfile import TemporaryDirectory\nfrom pattools.pacs import Patient\nfrom pattools._timelinefilter import flair_filter\nfrom pattools.ants import n4_bias_correct, affine_registration\nfrom pattools.fsl import bet\nimport os\nimport subprocess\nimport numpy as np\n\ndef latest_flair_pair(patient_id, scp_settings):\n ''' Get the 2 most recent FLAIR studies for a patient. Returns None if we can't find 2 studies'''\n p = Patient(patient_id, scp_settings=scp_settings)\n studies = p.find_studies()\n studies.sort(key=lambda s: s.study_date, reverse=True)\n fil = flair_filter()\n latest_flairs = []\n for s in studies:\n flair = fil.filter(s)\n if flair != None:\n latest_flairs.append(flair)\n if len(latest_flairs) >= 2:\n break\n if len(latest_flairs) == 2:\n return latest_flairs\n else:\n return None\n\ndef preprocess_pair(floating, fixed, tmp_dir):\n \"\"\"Pre processes the nifti images using:\n ANTs N4BiasFieldCorrection -> FSL bet -> ANTs antsRegistration\n Parameters\n ----------\n floating : string\n Path to the floating nifti image\n fixed : string\n Path to the fixed nifti image\n Returns\n -------\n (floating, fixed) : tuple\n floating : string\n Path to the pre-processed floating image\n fixed : string\n Path to the pre-processed floating image\n \"\"\"\n with TemporaryDirectory() as local_temp:\n # ANTS N4 Bias correction\n outfloat = os.path.join(local_temp, 'n4float.nii.gz')\n outfixed = os.path.join(local_temp, 'n4fixed.nii.gz')\n p1 = n4_bias_correct(floating, outfloat)\n p2 = n4_bias_correct(fixed, outfixed)\n p1.wait()\n p2.wait()\n # FSL BET\n floating = outfloat\n fixed = outfixed\n outfloat = os.path.join(local_temp, 'betfloat.nii.gz')\n outfixed = os.path.join(tmp_dir, 'fixed-processed.nii.gz') # Registration won't change this\n p1 = bet(floating, outfloat)\n p2 = bet(fixed, outfixed)\n p1.wait()\n p2.wait()\n # Coregistration\n floating = outfloat\n fixed = outfixed\n outfloat = os.path.join(tmp_dir, 'floating-processed.nii.gz')\n affine_registration(floating, fixed, outfloat).wait()\n \n return outfloat, outfixed\n\ndef vistarsier_compare(c, p, min_val=-1., max_val=5., min_change=0.8, max_change=3.):\n \"\"\" VisTarsier's compare operation\n Parameters\n ----------\n c : ndarray\n The current volume\n p : ndarray\n The prior volume\n min_val : float\n The minimum value (measured in standard deviations) to consider\n max_val : float\n The maximum value (measured in standard deviations) to consider\n min_change : float\n The minimum change of value (measured in standard deviations) to consider\n max_change : float\n The maximum change of value (measured in standard deviations) to consider\n Returns\n -------\n change : ndarray\n The relevant change in signal.\n \"\"\"\n # Get standard deviations for current and prior\n pstd = p.std()\n cstd = c.std()\n # Align prior standard deviation to current\n p = ((p - p.mean()) / pstd) * cstd + c.mean()\n\n #Calculate change\n change = c - p\n # Ignore change outside of minimuim and maximum values\n change[c < min_val*cstd] = 0\n change[p < min_val*cstd] = 0\n change[c > max_val*cstd] = 0\n change[p > max_val*cstd] = 0\n change[np.abs(change) < min_change*cstd] = 0\n change[np.abs(change) > max_change*cstd] = 0\n return change", "sub_path": "pattools/ms.py", "file_name": "ms.py", "file_ext": "py", "file_size_in_byte": 3588, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pattools.pacs.Patient", "line_number": 12, "usage_type": "call"}, {"api_name": "pattools._timelinefilter.flair_filter", "line_number": 15, "usage_type": "call"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pattools.ants.n4_bias_correct", "line_number": 49, "usage_type": "call"}, {"api_name": "pattools.ants.n4_bias_correct", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pattools.fsl.bet", "line_number": 58, "usage_type": "call"}, {"api_name": "pattools.fsl.bet", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pattools.ants.affine_registration", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 105, "usage_type": "call"}]} +{"seq_id": "119911089", "text": "from datetime import date\nfrom functools import wraps\nimport os\nfrom flask import Flask, render_template, redirect, url_for, flash, request\nfrom flask import abort\nfrom flask_bootstrap import Bootstrap\nfrom flask_ckeditor import CKEditor\nfrom flask_gravatar import Gravatar\nfrom flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import relationship\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\nfrom forms import CreatePostForm, RegisterForm, LoginForm, CommentForm\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\nckeditor = CKEditor(app)\nBootstrap(app)\n\n##CONNECT TO DB\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(\"DATABASE_URL\")\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\nlogin_manager= LoginManager()\nlogin_manager.init_app(app)\n\n## GARAVATAR ##\n\ngravatar = Gravatar(app,size=100,\n rating=\"g\",\n force_default=True,\n force_lower=False,\n use_ssl=False,\n base_url=None)\n\n\n##CONFIGURE TABLES -------- DATABASE\n\n\nclass Users(UserMixin,db.Model):\n __tablename__ = \"users\"\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(250), nullable=False, unique=True)\n email = db.Column(db.String(250), nullable=False, unique=True)\n password = db.Column(db.String(250), nullable=False)\n posts = relationship(\"BlogPost\", back_populates=\"author\")\n comment = relationship (\"Comment\", back_populates=\"author\")\n\nclass BlogPost(db.Model):\n __tablename__ = \"blog_posts\"\n id = db.Column(db.Integer, primary_key=True)\n author_id = db.Column (db.Integer , db.ForeignKey('users.id'))\n author = relationship(\"Users\", back_populates=\"posts\")\n comments = relationship(\"Comment\", back_populates = \"post\")\n title = db.Column(db.String(250), unique=True, nullable=False)\n subtitle = db.Column(db.String(250), nullable=False)\n date = db.Column(db.String(250), nullable=False)\n body = db.Column(db.Text, nullable=False)\n img_url = db.Column(db.String(250), nullable=False)\n\nclass Comment(db.Model):\n __tablename__ = \"comments\"\n id = db.Column(db.Integer,primary_key=True)\n author_id = db.Column (db.Integer, db.ForeignKey ( \"users.id\"))\n post_id = db.Column (db.Integer, db.ForeignKey ('blog_posts.id'))\n post = relationship (\"BlogPost\" , back_populates = \"comments\")\n author = relationship(\"Users\", back_populates = \"comment\")\n comment = db.Column (db.String)\n\n\ndb.create_all()\n\n\n\n\n\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return Users.query.get(int(user_id))\n\n\n\n# def admin_only(func):\n# @app.errorhandler(403)\n# def admin():\n# if current_user.is_authenticated:\n# if current_user.id == 1:\n# func()\n# else:\n# \"You don't have access to this page.\", 403\n# return admin\n\ndef admin_only(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n #If id is not 1 then return abort with 403 error\n if current_user.id != 1:\n return abort(403)\n #Otherwise continue with the route function\n return f(*args, **kwargs)\n return decorated_function\n\n@app.route('/')\ndef get_all_posts():\n posts = BlogPost.query.all()\n return render_template(\"index.html\", all_posts=posts, logged_in = current_user)\n\n\n@app.route('/register',methods=[\"GET\", \"POST\"])\ndef register():\n register_form = RegisterForm()\n if register_form.validate_on_submit():\n try:\n new_user = Users(__tablename__ = \"Authentication\", username = request.form[\"username\"], email = request.form[\"register_email\"],\n password= generate_password_hash(request.form[\"password\"],\"pbkdf2:sha256\" , 8))\n db.session.add(new_user)\n db.session.commit()\n login_user(new_user)\n return redirect(url_for('get_all_posts'))\n except:\n flash(\"The email already exists in the data base\", \"info\")\n return redirect(url_for('login'))\n\n return render_template(\"register.html\",form=register_form, logged_in = current_user)\n\n\n@app.route('/login', methods = [\"GET\", \"POST\"])\ndef login():\n login_form = LoginForm()\n if login_form.validate_on_submit():\n login_email= db.session.query(Users).filter_by (email = request.form[\"login_email\"]).first()\n if login_email:\n if check_password_hash(login_email.password, request.form[\"password\"]):\n login_user(login_email)\n return redirect(url_for(\"get_all_posts\"))\n else:\n flash(\"Incorrect password. Please try again.\")\n return redirect(url_for(\"login\"))\n else:\n flash(\"Incorrect email, please try again.\",\"error\")\n return redirect(url_for(\"login\"))\n return render_template(\"login.html\",form=login_form, logged_in = current_user)\n\n@login_required\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('get_all_posts'))\n\n\n@app.route(\"/post/\", methods = [\"GET\", \"POST\"])\ndef show_post(post_id):\n requested_post = BlogPost.query.get(post_id)\n comment_form = CommentForm()\n all_comments = Comment.query.all()\n\n if comment_form.validate_on_submit():\n if not current_user.is_authenticated:\n flash(\"You need to be logged in to comment\",\"info\")\n return redirect(url_for('login'))\n comment = (request.form[\"body\"])\n new_comment = Comment(comment=comment, author_id = current_user.id ,post_id = requested_post.id )\n db.session.add(new_comment)\n db.session.commit()\n return redirect(url_for(\"get_all_posts\"))\n return render_template(\"post.html\", post=requested_post, logged_in = current_user,\n form = comment_form, comments=all_comments)\n\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\", logged_in = current_user)\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template(\"contact.html\", logged_in = current_user)\n\n\n@app.route(\"/new-post\", methods = [\"GET\", \"POST\"])\n@admin_only\ndef add_new_post():\n form = CreatePostForm()\n if form.validate_on_submit():\n new_post = BlogPost(\n title=form.title.data,\n subtitle=form.subtitle.data,\n body=form.body.data,\n img_url=form.img_url.data,\n author=current_user,\n date=date.today().strftime(\"%B %d, %Y\")\n )\n db.session.add(new_post)\n db.session.commit()\n return redirect(url_for(\"get_all_posts\"))\n return render_template(\"make-post.html\", form=form, logged_in = current_user)\n\n\n@app.route(\"/edit-post/\", methods = [\"GET\", \"POST\"])\n@admin_only\ndef edit_post(post_id):\n post = BlogPost.query.get(post_id)\n edit_form = CreatePostForm(\n title=post.title,\n subtitle=post.subtitle,\n img_url=post.img_url,\n author=post.author,\n body=post.body\n )\n if edit_form.validate_on_submit():\n post.title = edit_form.title.data\n post.subtitle = edit_form.subtitle.data\n post.img_url = edit_form.img_url.data\n post.author = edit_form.author.data\n post.body = edit_form.body.data\n db.session.commit()\n return redirect(url_for(\"show_post\", post_id=post.id))\n\n return render_template(\"make-post.html\", form=edit_form, logged_in = current_user)\n\n\n@app.route(\"/delete/\")\n@admin_only\ndef delete_post(post_id):\n post_to_delete = BlogPost.query.get(post_id)\n db.session.delete(post_to_delete)\n db.session.commit()\n return redirect(url_for('get_all_posts'))\n\n\nif __name__ == \"__main__\":\n app.run()\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 7872, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 16, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask_ckeditor.CKEditor", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_bootstrap.Bootstrap", "line_number": 19, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 22, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 24, "usage_type": "call"}, {"api_name": "flask_login.LoginManager", "line_number": 26, "usage_type": "call"}, {"api_name": "flask_gravatar.Gravatar", "line_number": 31, "usage_type": "call"}, {"api_name": "flask_login.UserMixin", "line_number": 42, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 55, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 59, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 68, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 69, "usage_type": "call"}, {"api_name": "flask_login.current_user.id", "line_number": 101, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 101, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 102, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 110, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 110, "usage_type": "name"}, {"api_name": "forms.RegisterForm", "line_number": 115, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "werkzeug.security.generate_password_hash", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 119, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 119, "usage_type": "name"}, {"api_name": "flask_login.login_user", "line_number": 122, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 125, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 128, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 128, "usage_type": "name"}, {"api_name": "forms.LoginForm", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 135, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 135, "usage_type": "name"}, {"api_name": "werkzeug.security.check_password_hash", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 137, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 137, "usage_type": "name"}, {"api_name": "flask_login.login_user", "line_number": 138, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 141, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 142, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 142, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 144, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 145, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 145, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 146, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 146, "usage_type": "name"}, {"api_name": "flask_login.logout_user", "line_number": 151, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 152, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 152, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 148, "usage_type": "name"}, {"api_name": "forms.CommentForm", "line_number": 158, "usage_type": "call"}, {"api_name": "flask_login.current_user.is_authenticated", "line_number": 162, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 162, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 163, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 164, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 164, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 165, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 165, "usage_type": "name"}, {"api_name": "flask_login.current_user.id", "line_number": 166, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 166, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 170, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 170, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 176, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 176, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 181, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 181, "usage_type": "name"}, {"api_name": "forms.CreatePostForm", "line_number": 187, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 194, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 195, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 195, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 199, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 199, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 200, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 200, "usage_type": "name"}, {"api_name": "forms.CreatePostForm", "line_number": 207, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 221, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 221, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 223, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 223, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 232, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 232, "usage_type": "call"}]} +{"seq_id": "139261386", "text": "# import the libraries\n\nimport wikipediaapi\n\nimport json\n\nimport pandas as pd\n\nwiki_wiki = wikipediaapi.Wikipedia(language='en', extract_format=wikipediaapi.ExtractFormat.WIKI)\n\nsect = []\n\n# utility function for sections tree\ndef arrange_sections(sections,level=0): \n \n for s in sections: \n \n sect.append({str((level + 1)) : s.title}) \n \n #print(\"%s: %s\" % (str((level + 1)), s.title)) \n arrange_sections(s.sections, level + 1)\n \n\n# Please update all the tags you want to scrap for \n\n#topics = ['Artificial intelligence','Machine learning']\n\n# alternative code - read from csv\nfilename = \"ML.csv\" # place the name of the CSV to be scrapped\ntags_df = pd.read_csv(filename)\ntopics = list(tags_df['title'])\n\n# Scrap all tags one by one and create JSON for each\n\n\nfor topic in topics:\n\n pg = wiki_wiki.page(topic)\n \n sect = []\n \n if pg.exists(): # if the page is found \n\n content = dict()\n \n # collect topic contents\n\n\n content['url'] = pg.fullurl\n\n content['tag'] = topic \n \n arrange_sections(pg.sections) \n \n content['sections'] = sect\n \n content['fulltext'] = pg.text\n \n # create a topic JSON\n \n \n filename = \"wiki_content_\" + topic + \".json\" \n \n # write the content of the topic in the JSON\n \n with open(filename, 'w') as fp:\n json.dump(content, fp)\n\n \n\n\n\n \n \n\n \n \n \n\n", "sub_path": "wiki_scrape/single_article_with_category_levels.py", "file_name": "single_article_with_category_levels.py", "file_ext": "py", "file_size_in_byte": 1462, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "wikipediaapi.Wikipedia", "line_number": 9, "usage_type": "call"}, {"api_name": "wikipediaapi.ExtractFormat", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 67, "usage_type": "call"}]} +{"seq_id": "314266898", "text": "import tensorflow as tf\r\nimport numpy as np\r\nimport numpy.random as rd\r\nfrom nn18_ex2_load import load_isolet\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.core.fromnumeric import transpose\r\n\r\n\r\n\r\nXa,C,X_test,C_test=load_isolet();\r\nprint(Xa.shape);\r\nprint(C.shape);\r\nprint(X_test.shape);\r\nprint(C_test.shape);\r\n\r\n\r\n#We create the C arrays with this function\r\ndef createC(array):\r\n res=np.zeros((len(array),26));\r\n \r\n for i in range(len(array)):\r\n res[i][array[i]-1]=1;\r\n return res;\r\n#normalize function\r\n\r\ndef normalizeDataNN(array):\r\n m=transpose(array);\r\n res=np.zeros((len(array[0]),len(array)),dtype=float);\r\n for i in range (len(m)):\r\n maximum=max(m[i]);\r\n minimum=min(m[i]);\r\n avg=np.average(m[i]);\r\n std=np.std(m[i]);\r\n for j in range(len(m[i])):\r\n res[i][j]=float(m[i][j]-avg)/std;\r\n return transpose(res);\r\nCa=createC(C);\r\nCa_Test=createC(C_test);\r\nXa=normalizeDataNN(Xa);\r\nX_test=normalizeDataNN(X_test);\r\n\r\n\r\n# Give the dimension of the data and chose the number of hidden layer\r\n\r\nn_in = 300\r\nn_hidden = 40\r\nn_hidden3 = 5\r\nn_out = 26\r\nx = tf.placeholder(shape=(None,300),dtype=tf.float64)\r\n# Set the variables\r\nW_hid = tf.Variable(rd.randn(n_in,n_hidden) / np.sqrt(n_in),trainable=True)\r\nb_hid = tf.Variable(np.zeros(n_hidden),trainable=True);\r\ny1=tf.nn.tanh(tf.matmul(x,W_hid) + b_hid);\r\n# Lets try adding another hidden layer (if we want it, decomment the line)\r\nW_hid2 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid2 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny2=tf.nn.tanh(tf.matmul(y1,W_hid2)+b_hid2);\r\n# And another one (if we want it, decomment the line)\r\nW_hid3 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid3 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny3=tf.nn.tanh(tf.matmul(y2,W_hid3)+b_hid3);\r\n\r\nW_hid4 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid4 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny4=tf.nn.tanh(tf.matmul(y3,W_hid4)+b_hid4);\r\n\r\nW_hid5 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid5 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny5=tf.nn.tanh(tf.matmul(y4,W_hid5)+b_hid5);\r\n\r\nW_hid6 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid6 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny6=tf.nn.tanh(tf.matmul(y5,W_hid6)+b_hid6);\r\n\r\nW_hid7 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid7 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny7=tf.nn.tanh(tf.matmul(y6,W_hid7)+b_hid7);\r\n\r\nW_hid8 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid8 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny8=tf.nn.tanh(tf.matmul(y7,W_hid8)+b_hid8);\r\n\r\nW_hid9 = tf.Variable(rd.randn(n_hidden,n_hidden) / np.sqrt(n_in),trainable=True);\r\nb_hid9 = tf.Variable(np.zeros(n_hidden),trainable=True)\r\ny9=tf.nn.tanh(tf.matmul(y8,W_hid9)+b_hid9);\r\n####################################### \r\n### For 1 hidden layer, decomment the 1st w_out, for 2 the 2nd and for 3 the 3rd (keep the other commented)\r\nw_out = tf.Variable(rd.randn(n_hidden,n_out) / np.sqrt(n_in),trainable=True)\r\n#w_out = tf.Variable(rd.randn(n_hidden,n_out) / np.sqrt(n_in),trainable=True)\r\nTw_out = tf.Variable(rd.randn(n_hidden3,n_out) / np.sqrt(n_in),trainable=True)\r\n#######################################\r\nb_out = tf.Variable(np.zeros(n_out),trainable=True)\r\n\r\n# Define the neuron operations\r\n\r\n####################################### \r\n### For 1 hidden layer, decomment the 1st y, for 2 the 2nd and for 3 the 3rd (keep the other commented)\r\n\r\ny = y9\r\n#y = tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(x,W_hid) + b_hid),W_hid2)+b_hid2),W_hid3)+b_hid3)\r\nz = tf.nn.softmax(tf.matmul(y,w_out) + b_out)\r\n\r\n\r\n\r\nz_ = tf.placeholder(shape=(None,26),dtype=tf.float64)\r\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(z_ * tf.log(tf.clip_by_value(z,1e-10,1.0)), reduction_indices=[1]))\r\n#cross_entropy = tf.reduce_mean(-tf.reduce_sum(z_ * tf.log(z), reduction_indices=[1]));\r\n\r\n\r\ntrain_step = tf.train.AdamOptimizer(learning_rate=0.005).minimize(cross_entropy);\r\n\r\ncorrect_prediction = tf.equal(tf.argmax(z,1), tf.argmax(z_,1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))\r\ninit = tf.global_variables_initializer() # Create an op that will\r\nsess = tf.Session()\r\nsess.run(init) # Set the value of the variables to their initialization value\r\n# Create some list to monitor how error decreases\r\n\r\n#Now we use the test set\r\ntest_loss_list2 = []\r\ntrain_loss_list2 = []\r\n\r\ntest_acc_list2 = []\r\ntrain_acc_list2 = []\r\nsaver = tf.train.Saver()\r\n\r\n\r\n\r\ncounter=0;\r\npatience=100;\r\nmaxacc=0;\r\nk_batch = 20\r\nX_batch_list = np.array_split(Xa,k_batch)\r\nlabels_batch_list = np.array_split(Ca,k_batch)\r\n#retraining of the network with the epoch that suits best\r\n#adamAlgroithm\r\ntrainMaxAcc=0.0\r\ntestMinLoss=500.0\r\nepochs=250;\r\nearlyStop=0;\r\nfor k in range(epochs):\r\n \r\n # Run gradient steps over each minibatch\r\n for x_minibatch,labels_minibatch in zip(X_batch_list,labels_batch_list):\r\n sess.run(train_step, feed_dict={x: x_minibatch, z_:labels_minibatch})\r\n \r\n \r\n # Compute the errors over the whole dataset\r\n train_loss = sess.run(cross_entropy, feed_dict={x:Xa, z_:Ca})\r\n test_loss = sess.run(cross_entropy, feed_dict={x:X_test,z_:Ca_Test});\r\n \r\n # Compute the acc over the whole dataset\r\n train_acc = sess.run(accuracy, feed_dict={x:Xa, z_:Ca})\r\n test_acc = sess.run(accuracy, feed_dict={x:X_test,z_:Ca_Test});\r\n if testMinLoss>test_loss and earlyStop==0:\r\n testMinLoss=test_loss;\r\n #computing ggradient\r\n if trainMaxAcc0 and (test_loss_list2[k]-trainMaxAcc)>0.02:\r\n counter+=1;\r\n else:\r\n counter=0;\r\n if counter>patience:\r\n print(\"early stopping\");\r\n earlyStop=1;\r\n \r\n if np.mod(k,100) == 0:\r\n print('iteration {} test accuracy: {:.3f}'.format(k+1,test_acc))\r\nfig,ax_list = plt.subplots(1,2)\r\nax_list[0].plot(train_loss_list2, color='blue', label='training', lw=2)\r\nax_list[0].plot(test_loss_list2, color='green', label='testing', lw=2)\r\nax_list[1].plot(train_acc_list2, color='blue', label='training', lw=2)\r\nax_list[1].plot(test_acc_list2, color='green', label='testing', lw=2)\r\n\r\nax_list[0].set_xlabel('training iterations')\r\nax_list[1].set_xlabel('training iterations')\r\nax_list[0].set_ylabel('Cross-entropy')\r\nax_list[1].set_ylabel('Accuracy')\r\nplt.legend(loc=2)\r\n\r\nplt.show();\r\nprint('best test set accuracy: {:.3f}'.format(maxacc));\r\nprint('best test set accuracy: {:.3f}'.format(trainMaxAcc));", "sub_path": "source/programHL2.py", "file_name": "programHL2.py", "file_ext": "py", "file_size_in_byte": 7059, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "nn18_ex2_load.load_isolet", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.core.fromnumeric.transpose", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.core.fromnumeric.transpose", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.float64", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 57, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 59, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 64, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 65, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 67, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 71, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 75, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 77, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 79, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 81, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 83, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 88, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 90, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 101, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 105, "usage_type": "call"}, {"api_name": "tensorflow.float64", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.log", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 110, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 110, "usage_type": "attribute"}, {"api_name": "tensorflow.equal", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.float64", "line_number": 113, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 114, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 125, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 125, "usage_type": "attribute"}, {"api_name": "numpy.array_split", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.array_split", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.mod", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}]} +{"seq_id": "549449095", "text": "#coding=utf-8\n#该脚本用来校正和裁剪照片中的人脸\n\nimport cv2\nimport dlib\nimport math\n\npath = \"img/IMG_4.jpg\"\nimg = cv2.imread(path)\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n#获取照片长宽\nheight,width = img.shape[:2]\n\n#人脸分类器\ndetector = dlib.get_frontal_face_detector()\n# 获取人脸检测器\npredictor = dlib.shape_predictor(r\"C:\\Users\\48162\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\site-packages\\dlib-data\\shape_predictor_68_face_landmarks.dat\")\n\n#获取人脸区域\ndets = detector(gray, 1)\nfor face in dets:\n shape = predictor(img, face) # 寻找人脸的68个标定点\n\n#计算人脸中心坐标\neyecenter = ((shape.part(36).x + shape.part(45).x) * 1. / 2, (shape.part(36).y + shape.part(45).y) * 1. / 2)\n\n#计算dx,dy\ndx = shape.part(45).x - shape.part(36).x\ndy = shape.part(45).y - shape.part(36).y\n\n\n#计算角度\nangle = math.atan2(dy, dx) * 180. / math.pi\n\n#计算仿射矩阵\nRotateMatrix = cv2.getRotationMatrix2D(eyecenter, angle, scale=1)\n\n#转换照片\nalign_face = cv2.warpAffine(img, RotateMatrix, (width, height))\n\n\n#重新计算人脸区域并剪裁\ngray = cv2.cvtColor(align_face, cv2.COLOR_BGR2GRAY)\ndets = detector(gray, 1)\nfor face in dets:\n shape = predictor(align_face, face)\n\n#cv2.line(align_face, (shape.part(36).x, shape.part(36).y), (shape.part(45).x, shape.part(45).y), (0, 255, 0), 2)\n#cv2.line(align_face, (shape.part(27).x, shape.part(27).y), (shape.part(8).x, shape.part(8).y), (0, 255, 0), 2)\n\nfacelength = shape.part(8).y - shape.part(24).y\nfacewidth = shape.part(16).x - shape.part(0).x\nfacecenter = ((shape.part(27).x + shape.part(8).x) * 1 / 2, (shape.part(27).y + shape.part(8).y) * 1 / 2)\nx1, x2, y1, y2 = int(facecenter[0] - facewidth), int(facecenter[0] + facewidth),\\\n int(facecenter[1] - 1.8 * facelength), int(facecenter[1] + 0.8 * facelength)\nimgout = align_face[y1:y2, x1:x2]\n\n#cv2.rectangle(align_face, (x1, y1), (x2, y2), (0, 255, 0), 2)\n#cv2.rectangle(align_face, (shape.part(0).x, shape.part(19).y), (shape.part(16).x, shape.part(8).y), (0 ,255, 0), 2)\n\ncv2.imwrite(\"F:/Github/Image-Processing/Code/Output2/img5.jpg\", imgout)\nheight,width = imgout.shape[:2] #获取原图像的水平方向尺寸和垂直方向尺寸。\nres = cv2.resize(imgout,(width//2,height//2),interpolation=cv2.INTER_CUBIC) #dsize=(2*width,2*height)\ncv2.imshow('res',res)\ncv2.waitKey(0)\ncv2.destroyAllWindows()", "sub_path": "Code/demo3.py", "file_name": "demo3.py", "file_ext": "py", "file_size_in_byte": 2390, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "cv2.imread", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 10, "usage_type": "attribute"}, {"api_name": "dlib.get_frontal_face_detector", "line_number": 16, "usage_type": "call"}, {"api_name": "dlib.shape_predictor", "line_number": 18, "usage_type": "call"}, {"api_name": "math.atan2", "line_number": 34, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 34, "usage_type": "attribute"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 44, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 64, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 65, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 66, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 67, "usage_type": "call"}]} +{"seq_id": "261088160", "text": "\"\"\"\nSimple Proxy Loader to prevent us from loading\nthe same bean_file multiple times for a single Import\n\"\"\"\nimport typing\nfrom beancount import loader\n\nCACHE = None\n\ndef load_file(*args, **kwds):\n global CACHE\n if CACHE is None:\n CACHE = loader.load_file(*args, **kwds)\n return CACHE\n\ndef Meta(**kwds) -> typing.Dict[str, typing.Any]:\n meta = {}\n meta.setdefault('lineno', 0)\n meta.setdefault('filename', None)\n meta.update(kwds)\n return meta\n\n", "sub_path": "src/coolbeans/tools/loader.py", "file_name": "loader.py", "file_ext": "py", "file_size_in_byte": 476, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "beancount.loader.load_file", "line_number": 13, "usage_type": "call"}, {"api_name": "beancount.loader", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 16, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 16, "usage_type": "attribute"}]} +{"seq_id": "232262684", "text": "from flask import Blueprint,render_template,redirect,url_for,flash,request,current_app\nfrom App.forms import UserInfo # 个人信息显示user模型类\nfrom flask_login import current_user,login_required\nfrom App.models import Posts\nfrom App.extensions import db,file\nfrom App.forms import SendPosts,Upload # 用户编辑博客,文件上传表单类\nimport os\nfrom PIL import Image\n\nowncenter = Blueprint('owncenter',__name__)\n\n# 查看与修改个人信息\n@owncenter.route('/user_info/',methods=['GET','POST'])\n@login_required\ndef user_info():\n form = UserInfo()\n if form.validate_on_submit():\n #\n current_user.age = form.age.data\n current_user.sex = int(form.sex.data)\n current_user.save()\n # 给表单设置默认值\n form.username.data = current_user.username\n form.age.data = current_user.age\n form.sex.data = str(int(current_user.sex))\n form.email.data = current_user.email\n form.lastlogin.data = current_user.lastLogin\n form.register.data = current_user.registerTime\n return render_template('owncenter/user_info.html',form=form)\n\n\n\n# 博客管理\n# 任务:因为正常来说删除处理不会真正的执行删除,只是逻辑上标记为删除,\n# 在posts的模型上添加一个字段,当执行了删除,那么更改字段状态 那么用户就查看不到\n@owncenter.route('/posts_manager/')\n@login_required\ndef posts_manager():\n # 查询当前用户发表的所有博客,pid为0证明是博客内容,而不是评论和回复,state=0是所有人可见,按照时间降序查询\n posts = current_user.posts.filter_by(pid=0,state=0).order_by(Posts.timestamp.desc())\n return render_template('owncenter/posts_manager.html',posts=posts)\n\n\n# 博客删除\n@owncenter.route('/del_posts//')\n@login_required\ndef del_posts(pid):\n # 查询博客\n p = Posts.query.get(pid)\n # 判断博客 是否存在\n if p:\n flash('删除成功')\n p.delete() # 删除博客内容\n comment = Posts.query.filter(Posts.path.contains(str(pid)))\n # 删除评论和回复\n for post in comment:\n post.delete()\n else:\n flash('您要删除的博客不存在')\n return redirect(url_for('owncenter.posts_manager'))\n\n\n# 博客编辑\n@owncenter.route('/edit_posts//',methods=['GET','POST'])\n@login_required\ndef edit_posts(pid):\n form = SendPosts() # 实例化表单\n p = Posts.query.get(pid) # 根据博客id查询博客\n if not p:\n flash('该博客不存在')\n return redirect(url_for('owncenter.posts_manager'))\n if form.validate_on_submit():\n # 更新��据的存储\n p.title = form.title.data\n p.article = form.article.data\n p.save()\n flash('博客更新成功')\n return redirect(url_for('owncenter.posts_manager'))\n form.title.data = p.title\n form.article.data = p.article\n return render_template('owncenter/edit_posts.html',form=form)\n\n\n# 生成唯一的图片名\ndef random_filename(suffix,length=32):\n import string,random\n Str = string.ascii_letters+string.digits\n return ''.join(random.choice(Str) for i in range(length))+'.'+suffix\n\n\n# 图片缩放处理\ndef image_zoom(path,prefix='s_',width=100,height=100):\n # 打开文件\n img = Image.open(path)\n # 重新设计尺寸\n img.thumbnail((width, height))\n # 拆分传递进来的图片的路径,拆分进行前缀的拼接\n pathSplit = os.path.split(path)\n path = os.path.join(pathSplit[0],prefix+pathSplit[1])\n # 保存缩放后的图片,保留原图片\n img.save(path)\n\n# 头像上传\n@owncenter.route('/upload/',methods=['GET','POST'])\n@login_required\ndef upload():\n form = Upload()\n if form.validate_on_submit():\n # 获取上传对象\n icon = request.files.get('icon')\n # 获取后缀\n suffix = icon.filename.split('.')[-1]\n newName = random_filename(suffix) # 获取新的图片名称\n\n # 保存图片\n file.save(icon,name=newName)\n delPath = current_app.config['UPLOADED_PHOTOS_DEST']\n # 删除之前上传过的图片\n if current_user.icon != 'default.jpg':\n os.remove(os.path.join(delPath, current_user.icon))\n os.remove(os.path.join(delPath, 'b_'+current_user.icon))\n os.remove(os.path.join(delPath, 'm_'+current_user.icon))\n os.remove(os.path.join(delPath, 's_'+current_user.icon))\n # 更改当前对象的图片名称,并更新到数据库中\n current_user.icon = newName\n db.session.add(current_user)\n db.session.commit()\n # 拼接图片路径\n path = os.path.join(delPath,newName)\n # 进行头像的多次缩放\n image_zoom(path)\n image_zoom(path,'m_',200,200)\n image_zoom(path,'b_',300,300)\n return render_template('owncenter/upload.html',form=form)\n\n\n\n# 收藏管理\n@owncenter.route('/my_favorite/')\n@login_required\ndef my_favorite():\n # 查出用户所有收藏的博客\n posts = current_user.favorites.all()\n return render_template('owncenter/my_favorite.html',posts=posts)\n\n# 取消收藏\n@owncenter.route('/del_favorite//')\n@login_required\ndef del_favorite(pid):\n # 判断是否收藏了\n if current_user.is_favorite(pid):\n # 调用取消收藏\n current_user.delete_favorite(pid)\n flash('取消收藏成功')\n return redirect(url_for('owncenter.my_favorite'))\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "sub_path": "python/示例代码/4.Flask 博客项目/blog/App/views/owncenter.py", "file_name": "owncenter.py", "file_ext": "py", "file_size_in_byte": 5455, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Blueprint", "line_number": 10, "usage_type": "call"}, {"api_name": "App.forms.UserInfo", "line_number": 16, "usage_type": "call"}, {"api_name": "flask_login.current_user.age", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 19, "usage_type": "name"}, {"api_name": "flask_login.current_user.sex", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 20, "usage_type": "name"}, {"api_name": "flask_login.current_user.save", "line_number": 21, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 21, "usage_type": "name"}, {"api_name": "flask_login.current_user.username", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 23, "usage_type": "name"}, {"api_name": "flask_login.current_user.age", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 24, "usage_type": "name"}, {"api_name": "flask_login.current_user.sex", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 25, "usage_type": "name"}, {"api_name": "flask_login.current_user.email", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 26, "usage_type": "name"}, {"api_name": "flask_login.current_user.lastLogin", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 27, "usage_type": "name"}, {"api_name": "flask_login.current_user.registerTime", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 29, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 14, "usage_type": "name"}, {"api_name": "flask_login.current_user.posts.filter_by", "line_number": 40, "usage_type": "call"}, {"api_name": "flask_login.current_user.posts", "line_number": 40, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 40, "usage_type": "name"}, {"api_name": "App.models.Posts.timestamp.desc", "line_number": 40, "usage_type": "call"}, {"api_name": "App.models.Posts.timestamp", "line_number": 40, "usage_type": "attribute"}, {"api_name": "App.models.Posts", "line_number": 40, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 41, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 37, "usage_type": "name"}, {"api_name": "App.models.Posts.query.get", "line_number": 49, "usage_type": "call"}, {"api_name": "App.models.Posts.query", "line_number": 49, "usage_type": "attribute"}, {"api_name": "App.models.Posts", "line_number": 49, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 52, "usage_type": "call"}, {"api_name": "App.models.Posts.query.filter", "line_number": 54, "usage_type": "call"}, {"api_name": "App.models.Posts.query", "line_number": 54, "usage_type": "attribute"}, {"api_name": "App.models.Posts", "line_number": 54, "usage_type": "name"}, {"api_name": "App.models.Posts.path.contains", "line_number": 54, "usage_type": "call"}, {"api_name": "App.models.Posts.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.flash", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 60, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 60, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 46, "usage_type": "name"}, {"api_name": "App.forms.SendPosts", "line_number": 67, "usage_type": "call"}, {"api_name": "App.models.Posts.query.get", "line_number": 68, "usage_type": "call"}, {"api_name": "App.models.Posts.query", "line_number": 68, "usage_type": "attribute"}, {"api_name": "App.models.Posts", "line_number": 68, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 70, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 65, "usage_type": "name"}, {"api_name": "string.ascii_letters", "line_number": 87, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 87, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 88, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 94, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 94, "usage_type": "name"}, {"api_name": "os.path.split", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path", "line_number": 99, "usage_type": "attribute"}, {"api_name": "App.forms.Upload", "line_number": 107, "usage_type": "call"}, {"api_name": "flask.request.files.get", "line_number": 110, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 110, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 110, "usage_type": "name"}, {"api_name": "App.extensions.file.save", "line_number": 116, "usage_type": "call"}, {"api_name": "App.extensions.file", "line_number": 116, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 117, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 117, "usage_type": "name"}, {"api_name": "flask_login.current_user.icon", "line_number": 119, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 119, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "attribute"}, {"api_name": "flask_login.current_user.icon", "line_number": 120, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 120, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path", "line_number": 121, "usage_type": "attribute"}, {"api_name": "flask_login.current_user.icon", "line_number": 121, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 121, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "flask_login.current_user.icon", "line_number": 122, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 122, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path", "line_number": 123, "usage_type": "attribute"}, {"api_name": "flask_login.current_user.icon", "line_number": 123, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 123, "usage_type": "name"}, {"api_name": "flask_login.current_user.icon", "line_number": 125, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 125, "usage_type": "name"}, {"api_name": "App.extensions.db.session.add", "line_number": 126, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 126, "usage_type": "argument"}, {"api_name": "App.extensions.db.session", "line_number": 126, "usage_type": "attribute"}, {"api_name": "App.extensions.db", "line_number": 126, "usage_type": "name"}, {"api_name": "App.extensions.db.session.commit", "line_number": 127, "usage_type": "call"}, {"api_name": "App.extensions.db.session", "line_number": 127, "usage_type": "attribute"}, {"api_name": "App.extensions.db", "line_number": 127, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path", "line_number": 129, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 134, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 105, "usage_type": "name"}, {"api_name": "flask_login.current_user.favorites.all", "line_number": 143, "usage_type": "call"}, {"api_name": "flask_login.current_user.favorites", "line_number": 143, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 143, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 144, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 140, "usage_type": "name"}, {"api_name": "flask_login.current_user.is_favorite", "line_number": 151, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 151, "usage_type": "name"}, {"api_name": "flask_login.current_user.delete_favorite", "line_number": 153, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 153, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 154, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 155, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 155, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 148, "usage_type": "name"}]} +{"seq_id": "502986311", "text": "#!/usr/bin/python3.5\nimport api\nimport json\nimport datetime\n\nprint (datetime.datetime.now())\n\nwith open('../access_token','r') as fd:\n access_token=fd.readline()\n\nc = api.Connection(access_token)\nv = c.vehicles[0]\nc.close()\n\nfor k in sorted(v.keys()):\n print (\"{}:-----> {}\".format(k,v[k]))\n", "sub_path": "vstat.py", "file_name": "vstat.py", "file_ext": "py", "file_size_in_byte": 297, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 6, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 6, "usage_type": "attribute"}, {"api_name": "api.Connection", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "260861784", "text": "import numpy as np\nimport matplotlib.pyplot as plt \nimport os, csv, matplotlib, math\n\nmatplotlib.rcParams.update({'font.size': 7})\ngraphTypes = { \"origAlpha\": 3, \"knnAlpha\": 6, \"knnAShift\": 7, \"nbAlpha\": 10, \"nbAShift\": 11, \"dtAlpha\": 14, \"dtAShift\": 15 }\ntransformations = [\"original\", \"root\", \"logarithm\", \"exponential\", \"inverse\"]\ndatasetTypes = [\"LS-DT\", \"LS-KNN\", \"LS-NB\", \"RT\"]\nsubplotIndex = 1\n\ndef FilterFilenamesStartWith(filenames, prefix):\n results = []\n for path in filenames:\n if os.path.basename(path).startswith(prefix):\n results.append(path)\n return results\n\ndef TransformValue(value, mode):\n if mode == \"original\":\n return value\n if mode == \"root\":\n return value ** 0.5\n if mode == \"logarithm\":\n return None if value == 0 else math.log(abs(value))\n if mode == \"exponential\":\n return math.exp(value)\n if mode == \"inverse\":\n return None if value == 0 else 1 / value\n\nfor graphType in graphTypes:\n for transformation in transformations:\n os.makedirs(f\"..\\\\Dataset\\\\artificial-new\\\\level1\\\\level1-summary\\\\CategorizedHistogram-unfixedbin\\\\{graphType}\\\\{transformation}\")\n plotIndex = 1\n # draw 800 histograms\n for datasetType in datasetTypes:\n for filename in os.listdir(f\"..\\\\Dataset\\\\artificial-new\\\\level1\\\\level1-summary\\\\{datasetType}\"):\n filename = f\"..\\\\Dataset\\\\artificial-new\\\\level1\\\\level1-summary\\\\{datasetType}\\\\\" + filename\n rows = []\n with open(filename) as file:\n rows = list(file)\n valueCollection = []\n for row in rows[1:]:\n value = float(row.split(',')[graphTypes[graphType]])\n valueTransformed = TransformValue(value, transformation)\n if valueTransformed is not None:\n valueCollection.append(valueTransformed)\n valueCollection = np.array(valueCollection).astype(np.float)\n plt.gca().axes.get_yaxis().set_ticks([])\n plt.subplot(5, 4, subplotIndex)\n subplotIndex += 1\n plt.hist(valueCollection, bins = 20)\n plt.title(os.path.basename(filename)[:-9], loc = \"left\", pad = -13)\n if subplotIndex > 20:\n graphName = f\"{graphType}-{transformation}-{plotIndex}\"\n plt.suptitle(graphName, y = 0.94, fontsize = 15)\n plt.gca().axes.get_yaxis().set_ticks([])\n plt.gcf().set_size_inches(9, 8.3)\n plt.savefig(f\"..\\\\Dataset\\\\artificial-new\\\\level1\\\\level1-summary\\\\CategorizedHistogram-unfixedbin\\\\{graphType}\\\\{transformation}\\\\{graphName}.png\", dpi = 300)\n print(f\"{graphName} saved. \")\n plt.clf()\n subplotIndex = 1\n plotIndex += 1\n", "sub_path": "PyEnvir/categorized_histogram.py", "file_name": "categorized_histogram.py", "file_ext": "py", "file_size_in_byte": 2919, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.rcParams.update", "line_number": 5, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 5, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "math.log", "line_number": 24, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 26, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 32, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 47, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}]} +{"seq_id": "580438002", "text": "import EncoderFactory\nfrom DatasetManager import DatasetManager\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.pipeline import FeatureUnion\n\nimport time\nimport os\nimport sys\nfrom sys import argv\nimport pickle\nimport csv\n\nfrom hyperopt import Trials, STATUS_OK, tpe, fmin, hp\nimport hyperopt\n\nPREDS_DIR = \"predictions\"\nPARAMS_DIR = \"optimal_alarm_thresholds_ccom\"\n\ndef calculate_cost(x, costs):\n return costs[int(x['prediction']), int(x['actual'])](x)\n\ndef evaluate_model_cost(args):\n conf_threshold = args['conf_threshold']\n \n # trigger alarms according to conf_threshold\n dt_final = pd.DataFrame()\n unprocessed_case_ids = set(dt_preds.case_id.unique())\n for nr_events in range(1, dt_preds.prefix_nr.max() + 1):\n tmp = dt_preds[(dt_preds.case_id.isin(unprocessed_case_ids)) & (dt_preds.prefix_nr == nr_events)]\n tmp = tmp[tmp.predicted_proba >= conf_threshold]\n tmp[\"prediction\"] = 1\n dt_final = pd.concat([dt_final, tmp], axis=0, sort=False)\n unprocessed_case_ids = unprocessed_case_ids.difference(tmp.case_id)\n tmp = dt_preds[(dt_preds.case_id.isin(unprocessed_case_ids)) & (dt_preds.prefix_nr == 1)]\n tmp[\"prediction\"] = 0\n dt_final = pd.concat([dt_final, tmp], axis=0, sort=False)\n\n case_lengths = dt_preds.groupby(\"case_id\").prefix_nr.max().reset_index()\n case_lengths.columns = [\"case_id\", \"case_length\"]\n dt_final = dt_final.merge(case_lengths)\n \n cost = dt_final.apply(calculate_cost, costs=costs, axis=1).sum()\n \n return {'loss': cost, 'status': STATUS_OK, 'model': dt_final}\n\n\nprint('Preparing data...')\nstart = time.time()\n\ndataset_name = argv[1]\nmethod_name = argv[2]\ncls_method = argv[3]\n\n# create output directory\nif not os.path.exists(os.path.join(PARAMS_DIR)):\n os.makedirs(os.path.join(PARAMS_DIR))\n \n# read the data\ndataset_manager = DatasetManager(dataset_name)\n \n# prepare the dataset\ndt_preds = pd.read_csv(os.path.join(PREDS_DIR, \"preds_val_%s_%s_%s.csv\" % (dataset_name, method_name, cls_method)), sep=\";\")\n\nprint('Optimizing parameters...')\ncost_weights = [(1,1), (2,1), (3,1), (5,1), (10,1), (20,1), (40, 1)]\nc_com_weights = [1/40.0, 1/20.0, 1/10.0, 1/5.0, 1/3.0, 1/2.0, 1, 2, 3, 5, 10, 20, 40, 0]\nc_postpone_weight = 0\nfor c_miss_weight, c_action_weight in cost_weights:\n for c_com_weight in c_com_weights:\n for early_type in [\"const\", \"linear\"]:\n \n c_miss = c_miss_weight / (c_miss_weight + c_action_weight + c_com_weight)\n c_action = c_action_weight / (c_miss_weight + c_action_weight + c_com_weight)\n c_com = c_com_weight / (c_miss_weight + c_action_weight + c_com_weight)\n\n if early_type == \"linear\":\n costs = np.matrix([[lambda x: 0,\n lambda x: c_miss],\n [lambda x: c_action * (x['prefix_nr']-1) / x['case_length'] + c_com,\n lambda x: c_action * (x['prefix_nr']-1) / x['case_length'] + (x['prefix_nr']-1) / x['case_length'] * c_miss\n ]])\n else:\n costs = np.matrix([[lambda x: 0,\n lambda x: c_miss],\n [lambda x: c_action + c_com,\n lambda x: c_action + (x['prefix_nr']-1) / x['case_length'] * c_miss\n ]])\n\n space = {'conf_threshold': hp.uniform(\"conf_threshold\", 0, 1)}\n trials = Trials()\n best = fmin(evaluate_model_cost, space, algo=tpe.suggest, max_evals=50, trials=trials)\n\n best_params = hyperopt.space_eval(space, best)\n\n outfile = os.path.join(PARAMS_DIR, \"optimal_confs_%s_%s_%s_%s_%s_%s_%s_%s.pickle\" % (dataset_name, method_name, \n cls_method, c_miss_weight, \n c_action_weight, c_postpone_weight, \n c_com_weight, early_type))\n # write to file\n with open(outfile, \"wb\") as fout:\n pickle.dump(best_params, fout)\n", "sub_path": "experiments_optimize_alarm_threshold_ccom.py", "file_name": "experiments_optimize_alarm_threshold_ccom.py", "file_ext": "py", "file_size_in_byte": 4349, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 36, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 40, "usage_type": "call"}, {"api_name": "hyperopt.STATUS_OK", "line_number": 48, "usage_type": "name"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 54, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 55, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 56, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "DatasetManager.DatasetManager", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.matrix", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 87, "usage_type": "call"}, {"api_name": "hyperopt.hp.uniform", "line_number": 93, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 93, "usage_type": "name"}, {"api_name": "hyperopt.Trials", "line_number": 94, "usage_type": "call"}, {"api_name": "hyperopt.fmin", "line_number": 95, "usage_type": "call"}, {"api_name": "hyperopt.tpe.suggest", "line_number": 95, "usage_type": "attribute"}, {"api_name": "hyperopt.tpe", "line_number": 95, "usage_type": "name"}, {"api_name": "hyperopt.space_eval", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 105, "usage_type": "call"}]} +{"seq_id": "382332616", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nfrom datetime import datetime\nimport asyncio\n\n# 동기식 모델\n# 장점: 설계가 매우 간단하고 직관적\n# 단점: 요청에 따른 결과가 반환되기 전까지 아무것도 못하고 대기\n\n# 비동기식 모델\n# 장점: 요청에 따른 결과가 반환되는 시간 동안 다른 작업을 수행할 수 있음\n# 단점: 동기식보다 설계가 복잡하고 논증적\n\n# DB 연결\nimport pymysql\n\nconn = pymysql.connect(\n user='stockbotAdmin',\n passwd='a40844084',\n host='stock-chatbot-rds.cgw5ybwbhaw9.ap-northeast-2.rds.amazonaws.com',\n db='stock_chatbot',\n charset='utf8'\n)\n\ncurs = conn.cursor()\n\n\n# 비동기로 실행\nasync def get_price(company_code):\n url = 'https://finance.naver.com/item/main.nhn?code=' + company_code\n\n # 현재의 이벤트 루프 가져오기\n loop = asyncio.get_event_loop()\n # 지정된 실행기에서 requests.get이 호출되도록 배치\n # async를 붙여 비동기 함수 선언, await로 비동기 작업을 대기\n req = await loop.run_in_executor(None, requests.get, url)\n html = req.text\n bs_obj = await loop.run_in_executor(None, BeautifulSoup,\n html, 'html.parser')\n\n no_today = bs_obj.find(\"p\", {\"class\": \"no_today\"})\n blind = no_today.find(\"span\", {\"class\": \"blind\"})\n now_price = blind.text\n return now_price\n\n\nasync def get_rate(company_code):\n url = 'https://finance.naver.com/item/sise.nhn?code=' + company_code\n\n loop = asyncio.get_event_loop()\n req = await loop.run_in_executor(None, requests.get, url)\n html = req.text\n bs_obj = await loop.run_in_executor(None, BeautifulSoup,\n html, 'lxml')\n\n no_exday = bs_obj.select_one('#_rate > span')\n now_rate = no_exday.text\n return now_rate.strip()\n\n\nasync def main():\n df = pd.DataFrame(columns=['stockcode', 'stockname', 'time', 'price', 'rate'])\n for stock in stock_to_code:\n # ('DRB동일', '004840'), ('DSR', '155660'),...stock[0] = stockName, stock[1] = stockCode\n now = datetime.now()\n\n now_price = await asyncio.gather(asyncio.ensure_future(get_price(stock[1])))\n now_rate = await asyncio.gather(asyncio.ensure_future(get_rate(stock[1])))\n\n df = df.append(pd.DataFrame([[stock[1], stock[0], now, now_price[0], now_rate[0]]],\n columns=['stockcode', 'stockname', 'time', 'price', 'rate']), ignore_index=True)\n print(stock[1], stock[0], now, now_price[0], now_rate[0])\n\n # 최초 실행시\n sql_insert = f\"INSERT INTO stock VALUES(\\\"{stock[1]}\\\",\\\"{stock[0]}\\\",\\\"{now}\\\",\\\"{now_price[0]}\\\",\\\"{now_rate[0]}\\\")\"\n # 이후 실행시\n sql_update = f\"UPDATE stock SET time=\\\"{now}\\\", price=\\\"{now_price[0]}\\\", rate=\\\"{now_rate[0]}\\\" WHERE stockcode=\\\"{stock[1]}\\\"\"\n curs.execute(sql_update)\n conn.commit()\n\n print(df)\n\n\nif __name__ == \"__main__\":\n df_stock = pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download',\n header=0)[0]\n # print(df_stock)\n # print(df_stock.info())\n # print(df_stock.isnull().sum())\n\n df_stock.종목코드 = df_stock.종목코드.map('{:06d}'.format)\n # print(df_stock)\n\n stock_to_code = tuple(zip(df_stock.회사명, df_stock.종목코드))\n # print(stock_to_code)\n\n # 새 이벤트 루프를 만들어 현재 이벤트 루프로 설정\n loop = asyncio.get_event_loop()\n # main()이 완료될 때까지 실행\n loop.run_until_complete(main())\n # 이벤트 루프 닫기\n loop.close()\n", "sub_path": "Stock_Data/crawling_stock.py", "file_name": "crawling_stock.py", "file_ext": "py", "file_size_in_byte": 3711, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymysql.connect", "line_number": 21, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 37, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 40, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 42, "usage_type": "argument"}, {"api_name": "asyncio.get_event_loop", "line_number": 54, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 55, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 57, "usage_type": "argument"}, {"api_name": "pandas.DataFrame", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 69, "usage_type": "name"}, {"api_name": "asyncio.gather", "line_number": 71, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 71, "usage_type": "call"}, {"api_name": "asyncio.gather", "line_number": 72, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 72, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 74, "usage_type": "call"}, {"api_name": "pandas.read_html", "line_number": 89, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "537626302", "text": "from django import http\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.core.mail import EmailMessage\nfrom django.utils import translation\nfrom django.utils.translation import LANGUAGE_SESSION_KEY\nfrom django.views.generic import ListView, DetailView, TemplateView\n\nfrom settings import LANGUAGES\nfrom website.models import Machine, Job, Subscription, Message, Gallery, HomeSlider, AuthorOpinion\n\n\ndef change_language(request):\n next = request.GET.get('next', None)\n if not next:\n next = request.META.get('HTTP_REFERER', None)\n if not next:\n next = '/'\n\n lang_code = request.GET.get('lan', None)\n for language in LANGUAGES:\n if language[0] in next:\n next = next.replace(language[0], lang_code, 3)\n response = http.HttpResponseRedirect(next)\n if hasattr(request, 'session'):\n request.session['django_language'] = lang_code\n request.session[LANGUAGE_SESSION_KEY] = lang_code\n else:\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)\n translation.activate(lang_code)\n return response\n\n\nclass MachineListView(ListView):\n model = Machine\n template_name = \"shop.html\"\n context_object_name = 'machines'\n\n def get_queryset(self):\n base_qs = super(MachineListView, self).get_queryset()\n return base_qs.filter(active=True)\n\n\nclass MachineDetailsView(DetailView):\n model = Machine\n template_name = \"machine-page.html\"\n context_object_name = 'machine'\n\n def get_queryset(self):\n base_qs = super(MachineDetailsView, self).get_queryset()\n return base_qs\n\n\nclass JobListView(ListView):\n model = Job\n template_name = \"career.html\"\n context_object_name = 'jobs'\n\n def get_queryset(self):\n base_qs = super(JobListView, self).get_queryset()\n return base_qs.filter(active=True)\n\n\ndef subscribe(request):\n from validate_email import validate_email\n\n email = request.GET.get('email') if request.GET else request.POST.get('email')\n is_valid = validate_email(email)\n if is_valid:\n Subscription.objects.create(email=email)\n return HttpResponse(status=200)\n else:\n return HttpResponse(status=400)\n\n\ndef unsubscribe(request, pk):\n Subscription.objects.get(pk=pk).delete()\n return HttpResponse('You have been unsubscribed from newsletter')\n\n\ndef send_emails(request):\n try:\n id = request.GET.get('id')\n msg = Message.objects.get(id=id)\n recipients = Subscription.objects.all().filter(is_active=True)\n for recipient in recipients:\n url = settings.BASE_URL + '/unsubscribe/'\n url += str(recipient.id)\n content = msg.content\n content += '\\n' + url\n message = EmailMessage(\n msg.title,\n content,\n settings.EMAIL_HOST_USER,\n [recipient.email],\n )\n message.send()\n return HttpResponse(status=200)\n except Exception as ex:\n return HttpResponse(status=400, content=ex)\n\n\nclass ContactView(TemplateView):\n template_name = \"contact.html\"\n\n def post(self, request, *args, **kwargs):\n title = ''\n email = request.POST.get('email')\n if request.POST.get('name'):\n title += request.POST.get('name') + ': '\n title += email\n content = request.POST.get('comments')\n message = EmailMessage(\n title,\n content,\n settings.EMAIL_HOST_USER,\n [settings.EMAIL_CONTACT],\n )\n message.send()\n return HttpResponse(status=200)\n\n\nclass HomeView(ListView):\n model = HomeSlider\n template_name = \"index.html\"\n context_object_name = 'sliders'\n\n def get_queryset(self):\n base_qs = super(HomeView, self).get_queryset()\n return base_qs[0]\n\n\nclass GalleryListView(ListView):\n model = Gallery\n template_name = \"gallery.html\"\n context_object_name = 'galleries'\n paginate_by = 9\n\n def get_queryset(self):\n request = self.request\n page = request.GET.get('page', 1)\n base_qs = super(GalleryListView, self).get_queryset().filter(active=True)\n return base_qs\n\n\nclass OpinionListView(ListView):\n model = AuthorOpinion\n template_name = \"opinion.html\"\n context_object_name = 'opinions'\n\n def get_queryset(self):\n base_qs = super(OpinionListView, self).get_queryset()\n return base_qs[0]\n", "sub_path": "website/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4521, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "settings.LANGUAGES", "line_number": 21, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 24, "usage_type": "call"}, {"api_name": "django.http", "line_number": 24, "usage_type": "name"}, {"api_name": "django.utils.translation.LANGUAGE_SESSION_KEY", "line_number": 27, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGE_COOKIE_NAME", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 29, "usage_type": "name"}, {"api_name": "django.utils.translation.activate", "line_number": 30, "usage_type": "call"}, {"api_name": "django.utils.translation", "line_number": 30, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 34, "usage_type": "name"}, {"api_name": "website.models.Machine", "line_number": 35, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 44, "usage_type": "name"}, {"api_name": "website.models.Machine", "line_number": 45, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 54, "usage_type": "name"}, {"api_name": "website.models.Job", "line_number": 55, "usage_type": "name"}, {"api_name": "validate_email.validate_email", "line_number": 68, "usage_type": "call"}, {"api_name": "website.models.Subscription.objects.create", "line_number": 70, "usage_type": "call"}, {"api_name": "website.models.Subscription.objects", "line_number": 70, "usage_type": "attribute"}, {"api_name": "website.models.Subscription", "line_number": 70, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 71, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 73, "usage_type": "call"}, {"api_name": "website.models.Subscription.objects.get", "line_number": 77, "usage_type": "call"}, {"api_name": "website.models.Subscription.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "website.models.Subscription", "line_number": 77, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 78, "usage_type": "call"}, {"api_name": "website.models.Message.objects.get", "line_number": 84, "usage_type": "call"}, {"api_name": "website.models.Message.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "website.models.Message", "line_number": 84, "usage_type": "name"}, {"api_name": "website.models.Subscription.objects.all", "line_number": 85, "usage_type": "call"}, {"api_name": "website.models.Subscription.objects", "line_number": 85, "usage_type": "attribute"}, {"api_name": "website.models.Subscription", "line_number": 85, "usage_type": "name"}, {"api_name": "django.conf.settings.BASE_URL", "line_number": 87, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 87, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 91, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_HOST_USER", "line_number": 94, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 94, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 98, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 100, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView", "line_number": 103, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 113, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_HOST_USER", "line_number": 116, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 116, "usage_type": "name"}, {"api_name": "django.conf.settings.EMAIL_CONTACT", "line_number": 117, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 117, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 120, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 123, "usage_type": "name"}, {"api_name": "website.models.HomeSlider", "line_number": 124, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 133, "usage_type": "name"}, {"api_name": "website.models.Gallery", "line_number": 134, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 146, "usage_type": "name"}, {"api_name": "website.models.AuthorOpinion", "line_number": 147, "usage_type": "name"}]} +{"seq_id": "231911676", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 9 12:45:16 2020\n\n@author: burt\nthis is to anaylze parameters of Null model, for this betap should be in stable range\n\"\"\"\n\nfrom tcell_parameters import d_null\n\nimport sys\nsys.path.append(\"/home/burt/Documents/projects/2019/tcell_model/code/\")\n#sys.path.append(\"C:/Users/Philipp/Documents/projects/tcell_model/code\")\nimport matplotlib.pyplot as plt\nfrom test_module import multi_param, array_from_dict\nimport module_models as models\nimport numpy as np\nimport matplotlib.ticker as ticker\nimport seaborn as sns\nsns.set(context = \"poster\", style = \"ticks\", rc = {\"lines.linewidth\": 4})\n\n#colors = [\"#3498db\", \"#95a5a6\", \"#e74c3c\", \"#34495e\"] \n#sns.set_palette(colors) \n\n# =============================================================================\n# define exp conditions\n# =============================================================================\n\ncond = [d_null]\n\ncond_names = [\"Null Model\"]\n\ntime = np.arange(0,20,0.01)\n\nmodel = models.th_cell_diff\n\nparam_names = [\"beta\", \n \"d_eff\", \n \"beta_p\"]\n\nnorm_list = [d_null[name] for name in param_names]\nparam_arrays = [array_from_dict(d_null, pname) for pname in param_names]\n\ndf_new = multi_param(param_arrays, param_names, time, cond,\n cond_names, norm_list, model = model, adjust_time = False)\n\n# =============================================================================\n# same plot but now facet for readouts\n# =============================================================================\nfigname = \"pscan_models\"\ng = sns.relplot(x = \"xnorm\", y = \"ylog\", kind = \"line\", data = df_new, hue = \"readout\", \n col = \"pname\", height = 4,\n facet_kws = {\"margin_titles\" : True, \"sharex\" : True, \"sharey\" : True},\n legend = \"full\")\n\nylim = (None, None)\ng.set(ylim = ylim, ylabel = \"log2FC\")\nfor ax in g.axes.flat:\n ax.set_xscale(\"log\")\n ax.xaxis.set_major_locator(ticker.LogLocator(base = 10.0, numticks = 100))\n \n[plt.setp(ax.texts, text=\"\") for ax in g.axes.flat]\ng.set_titles(row_template = '{row_name}', col_template = '{col_name}')\ng.savefig(\"../figures/pscan_null.pdf\")\n", "sub_path": "results/2020_w3/null_model/analysis_null_model.py", "file_name": "analysis_null_model.py", "file_ext": "py", "file_size_in_byte": 2199, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.path.append", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "seaborn.set", "line_number": 21, "usage_type": "call"}, {"api_name": "tcell_parameters.d_null", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 34, "usage_type": "call"}, {"api_name": "module_models.th_cell_diff", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tcell_parameters.d_null", "line_number": 42, "usage_type": "name"}, {"api_name": "test_module.array_from_dict", "line_number": 43, "usage_type": "call"}, {"api_name": "tcell_parameters.d_null", "line_number": 43, "usage_type": "argument"}, {"api_name": "test_module.multi_param", "line_number": 45, "usage_type": "call"}, {"api_name": "seaborn.relplot", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.ticker.LogLocator", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}]} +{"seq_id": "431981385", "text": "import os\n\nimport numpy as np\nimport torch\nfrom config import CFG\nfrom dotenv import load_dotenv\nfrom src.dataset import TrainDataset\nfrom src.model import get_network\nfrom src.utils import get_line_token, send_line_message\nfrom torch import nn\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.data import DataLoader\nfrom torchvision.utils import save_image\nfrom tqdm.auto import tqdm\n\ndotenv_path = os.path.join(os.path.dirname(__file__), \".env\")\nload_dotenv(dotenv_path)\n\nline_token = get_line_token(os.getenv(\"LINE_TOKEN_PATH\"))\n\n\ndef train(debug=False):\n max_epoch = CFG.epoch\n if debug:\n max_epoch = 1\n\n dataset_queries = {\n \"T91\": os.path.join(os.getenv(\"INPUT_DIR\"), \"T91/*.png\"),\n \"Set5\": os.path.join(os.getenv(\"INPUT_DIR\"), \"Set5/*.png\"),\n \"Set14\": os.path.join(os.getenv(\"INPUT_DIR\"), \"Set14/*.png\"),\n }\n\n # train dataloader\n train_query = dataset_queries.get(CFG.train_dataset)\n train_dataset = TrainDataset(\n train_query,\n max_size=CFG.max_size,\n shrink_scale=CFG.shrink_scale,\n total_samples=CFG.total_samples,\n input_upsample=CFG.input_upsample,\n )\n train_loader = DataLoader(\n train_dataset,\n batch_size=CFG.batch_size,\n shuffle=True,\n )\n\n # valid dataloader\n valid_query = dataset_queries.get(CFG.valid_dataset)\n valid_dataset = TrainDataset(\n valid_query,\n max_size=CFG.max_size,\n shrink_scale=CFG.shrink_scale,\n total_samples=CFG.total_samples,\n input_upsample=CFG.input_upsample,\n )\n valid_loader = DataLoader(\n valid_dataset,\n batch_size=CFG.batch_size,\n shuffle=True,\n )\n\n # model\n model = get_network(CFG.model)()\n model = model.to(device)\n\n # optimizer\n optimizer = torch.optim.Adam(\n model.parameters(), lr=CFG.lr, weight_decay=CFG.weight_decay\n )\n scheduler = StepLR(optimizer, step_size=CFG.lr_step, gamma=CFG.lr_gamma)\n if os.path.exists(f'os.getenv(\"OUTPUT_DIR\")/{CFG.model}'):\n states = torch.load(\n f'os.getenv(\"OUTPUT_DIR\")/model/{CFG.model}_010.pytorch'\n )\n model.load_state_dict(states)\n\n # 損失関数\n criterion = nn.MSELoss()\n\n # エラー推移\n metrics = {}\n metrics[\"train\"] = []\n metrics[\"valid\"] = []\n save_interval = 5\n\n # train loop\n for epoch in tqdm(range(max_epoch)):\n print(f\"epoch: {epoch+1}\")\n scheduler.step()\n model.train()\n\n epoch_loss = []\n\n for num, (img_input, img_target) in enumerate(train_loader):\n img_input, img_target = img_input.to(device), img_target.to(device)\n\n output = model(img_input)\n output_tensor = output.detach()\n\n loss = criterion(output, img_target)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n epoch_loss.append(loss.item())\n\n metrics[\"train\"].append(np.mean(epoch_loss))\n\n # モデルの保存\n output_model = f\"{os.getenv('OUTPUT_DIR')}/model\"\n if not os.path.exists(output_model):\n os.mkdir(output_model)\n if epoch % save_interval == 0 or epoch == max_epoch:\n torch.save(\n model.state_dict(),\n f\"{output_model}/{CFG.model}_{epoch:03}.pytorch\",\n )\n\n # 画像を保存\n\n # 低画質→高画質に変換した画像\n save_image(\n output_tensor[:10],\n os.path.join(output_model, f\"train_{epoch:02}_gen.png\"),\n )\n # 元画像\n save_image(\n img_target[:10],\n os.path.join(output_model, f\"train_{epoch:02}_target.png\"),\n )\n\n # valid\n model.eval()\n for img_input, img_target in valid_loader:\n valid_loss = []\n\n img_input, img_target = img_input.to(device), img_target.to(device)\n\n output = model(img_input)\n loss = criterion(output, img_target)\n output_tensor = output.detach()\n valid_loss.append(loss.item())\n metrics[\"valid\"].append(np.mean(valid_loss))\n\n print(f\"train: {metrics['train'][-1]}\")\n print(f\"valid: {metrics['valid'][-1]}\")\n\n # 生成画像を保存\n save_image(\n output_tensor[:10],\n os.path.join(output_model, f\"valid_{epoch:02}_gen.png\"),\n )\n save_image(\n img_target[:10],\n os.path.join(output_model, f\"valid_{epoch:02}_target.png\"),\n )\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n torch.backends.cudnn.benchmark = True # autotunerが高速化\n train()\n\n text = \"finish train!!\"\n send_line_message(line_token, text)\n", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 4805, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 16, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 17, "usage_type": "call"}, {"api_name": "src.utils.get_line_token", "line_number": 19, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 19, "usage_type": "call"}, {"api_name": "config.CFG.epoch", "line_number": 23, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 23, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 30, "usage_type": "call"}, {"api_name": "config.CFG.train_dataset", "line_number": 34, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 34, "usage_type": "name"}, {"api_name": "src.dataset.TrainDataset", "line_number": 35, "usage_type": "call"}, {"api_name": "config.CFG.max_size", "line_number": 37, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 37, "usage_type": "name"}, {"api_name": "config.CFG.shrink_scale", "line_number": 38, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 38, "usage_type": "name"}, {"api_name": "config.CFG.total_samples", "line_number": 39, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 39, "usage_type": "name"}, {"api_name": "config.CFG.input_upsample", "line_number": 40, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 42, "usage_type": "call"}, {"api_name": "config.CFG.batch_size", "line_number": 44, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 44, "usage_type": "name"}, {"api_name": "config.CFG.valid_dataset", "line_number": 49, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 49, "usage_type": "name"}, {"api_name": "src.dataset.TrainDataset", "line_number": 50, "usage_type": "call"}, {"api_name": "config.CFG.max_size", "line_number": 52, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 52, "usage_type": "name"}, {"api_name": "config.CFG.shrink_scale", "line_number": 53, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 53, "usage_type": "name"}, {"api_name": "config.CFG.total_samples", "line_number": 54, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 54, "usage_type": "name"}, {"api_name": "config.CFG.input_upsample", "line_number": 55, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 57, "usage_type": "call"}, {"api_name": "config.CFG.batch_size", "line_number": 59, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 59, "usage_type": "name"}, {"api_name": "src.model.get_network", "line_number": 64, "usage_type": "call"}, {"api_name": "config.CFG.model", "line_number": 64, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 64, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 68, "usage_type": "attribute"}, {"api_name": "config.CFG.lr", "line_number": 69, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 69, "usage_type": "name"}, {"api_name": "config.CFG.weight_decay", "line_number": 69, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 71, "usage_type": "call"}, {"api_name": "config.CFG.lr_step", "line_number": 71, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 71, "usage_type": "name"}, {"api_name": "config.CFG.lr_gamma", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "config.CFG.model", "line_number": 72, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 73, "usage_type": "call"}, {"api_name": "config.CFG.model", "line_number": 74, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.MSELoss", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 79, "usage_type": "name"}, {"api_name": "tqdm.auto.tqdm", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 109, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 113, "usage_type": "call"}, {"api_name": "os.path", "line_number": 113, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 116, "usage_type": "call"}, {"api_name": "config.CFG.model", "line_number": 118, "usage_type": "attribute"}, {"api_name": "config.CFG", "line_number": 118, "usage_type": "name"}, {"api_name": "torchvision.utils.save_image", "line_number": 124, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "torchvision.utils.save_image", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 145, "usage_type": "call"}, {"api_name": "torchvision.utils.save_image", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 153, "usage_type": "call"}, {"api_name": "os.path", "line_number": 153, "usage_type": "attribute"}, {"api_name": "torchvision.utils.save_image", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 157, "usage_type": "call"}, {"api_name": "os.path", "line_number": 157, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 162, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 164, "usage_type": "attribute"}, {"api_name": "src.utils.send_line_message", "line_number": 168, "usage_type": "call"}]} +{"seq_id": "431318993", "text": "# Test the cp_lib.cp_logging module\n\nimport json\nimport logging\nimport os.path\nimport shutil\nimport unittest\n\nimport cp_lib.cp_logging as cp_logging\n\n\nclass TestCpLogging(unittest.TestCase):\n\n TEST_FILE_NAME_INI = \"test/test.ini\"\n TEST_FILE_NAME_JSON = \"test/test.json\"\n\n def test_settings(self):\n \"\"\"\n Test the raw/simple handling of 1 INI to JSON in any directory\n :return:\n \"\"\"\n\n # start with NO changes\n logging.info(\"test #0 - all defaults\")\n settings = cp_logging._process_settings()\n # logging.debug(\"settings={}\".format(settings))\n\n self.assertIsNone(settings[cp_logging.SETS_FILE])\n self.assertIsNone(settings[cp_logging.SETS_SYSLOG_IP])\n\n self.assertEqual(settings[cp_logging.SETS_NAME], cp_logging.DEF_NAME)\n self.assertEqual(settings[cp_logging.SETS_LEVEL], logging.INFO)\n\n logging.info(\"test #1 - confirm the LEVEL setting\")\n tests = [\n (\"10\", logging.DEBUG),\n (10, logging.DEBUG),\n (\"debug\", logging.DEBUG),\n (\"Debug\", logging.DEBUG),\n (\"DEBUG\", logging.DEBUG),\n\n (-10, ValueError),\n (10.0, ValueError),\n (\"Junk\", ValueError),\n (\"\", ValueError),\n (None, ValueError),\n ]\n\n for test in tests:\n value = test[0]\n expect = test[1]\n\n # logging.info(\"\")\n # logging.debug(\"Level={0}, type={1}\".format(value, type(value)))\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n \"\",\n \"[logging]\",\n \"level = {}\".format(value),\n ]\n settings = self._make_ini_file(ini_data)\n\n if expect == ValueError:\n with self.assertRaises(ValueError):\n cp_logging._process_settings(settings)\n else:\n settings = cp_logging._process_settings(settings)\n self.assertEqual(settings[cp_logging.SETS_LEVEL], expect)\n\n logging.info(\"test #2 - confirm the NAME setting\")\n\n expect = \"tcp_echo\"\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n ]\n settings = self._make_ini_file(ini_data)\n settings = cp_logging._process_settings(settings)\n self.assertEqual(settings[cp_logging.SETS_NAME], expect)\n\n expect = \"runny\"\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n \"\",\n \"[logging]\",\n \"name = {}\".format(expect),\n ]\n settings = self._make_ini_file(ini_data)\n settings = cp_logging._process_settings(settings)\n self.assertEqual(settings[cp_logging.SETS_NAME], expect)\n\n # expect = \"\" (empty string - is ValueError)\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n \"\",\n \"[logging]\",\n \"name = \",\n ]\n settings = self._make_ini_file(ini_data)\n with self.assertRaises(ValueError):\n cp_logging._process_settings(settings)\n\n logging.info(\"test #3 - confirm the LOG FILE NAME setting\")\n tests = [\n (\"log.txt\", \"log.txt\"),\n (\"test/log.txt\", \"test/log.txt\"),\n (\"\", None),\n ]\n\n for test in tests:\n value = test[0]\n expect = test[1]\n\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n \"\",\n \"[logging]\",\n \"log_file = {}\".format(expect),\n ]\n settings = self._make_ini_file(ini_data)\n settings = cp_logging._process_settings(settings)\n self.assertEqual(settings[cp_logging.SETS_FILE], expect)\n\n logging.info(\"test #4 - confirm the SYSLOG SERVER setting\")\n tests = [\n (\"192.168.0.10\", \"192.168.0.10\", 514),\n (' (\"192.168.0.10\", 514)', \"192.168.0.10\", 514),\n ('[\"192.168.0.10\", 514]', \"192.168.0.10\", 514),\n ('(\"10.4.23.10\", 8514)', \"10.4.23.10\", 8514),\n (\"\", None, 514),\n ('(\"\", 8514)', ValueError, 0),\n ('(\"10.4.23.10\", -1)', ValueError, 0),\n ('(\"10.4.23.10\", 0x10000)', ValueError, 0),\n ]\n\n for test in tests:\n value = test[0]\n expect_ip = test[1]\n expect_port = test[2]\n\n ini_data = [\n \"[application]\",\n \"name = tcp_echo\",\n \"\",\n \"[logging]\",\n \"syslog = {}\".format(value),\n ]\n settings = self._make_ini_file(ini_data)\n\n if expect_ip == ValueError:\n with self.assertRaises(ValueError):\n cp_logging._process_settings(settings)\n else:\n settings = cp_logging._process_settings(settings)\n self.assertEqual(settings[cp_logging.SETS_SYSLOG_IP], expect_ip)\n if expect_ip is not None:\n self.assertEqual(settings[cp_logging.SETS_SYSLOG_PORT], expect_port)\n\n # clean up the temp file\n self._remove_name_no_error(self.TEST_FILE_NAME_INI)\n self._remove_name_no_error(self.TEST_FILE_NAME_JSON)\n self._remove_name_no_error(self.TEST_FILE_NAME_JSON + \".save\")\n\n return\n\n def _make_ini_file(self, data_list: list):\n \"\"\"Bounce settings through INI and JSON\"\"\"\n from cp_lib.load_settings import propagate_ini_to_json\n\n _han = open(self.TEST_FILE_NAME_INI, 'w')\n for line in data_list:\n _han.write(line + \"\\n\")\n _han.close()\n\n propagate_ini_to_json(self.TEST_FILE_NAME_INI, self.TEST_FILE_NAME_JSON)\n file_han = open(self.TEST_FILE_NAME_JSON, \"r\")\n settings = json.load(file_han)\n file_han.close()\n\n return settings\n\n @staticmethod\n def _remove_name_no_error(file_name):\n \"\"\"\n Just remove if exists\n :param str file_name: the file\n :return:\n \"\"\"\n if os.path.isdir(file_name):\n shutil.rmtree(file_name)\n\n else:\n try: # second, try if common file\n os.remove(file_name)\n except FileNotFoundError:\n pass\n return\n\n\nif __name__ == '__main__':\n # logging.basicConfig(level=logging.INFO)\n logging.basicConfig(level=logging.DEBUG)\n unittest.main()\n", "sub_path": "test/test_cp_logging.py", "file_name": "test_cp_logging.py", "file_ext": "py", "file_size_in_byte": 6481, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 25, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 25, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_FILE", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 28, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_SYSLOG_IP", "line_number": 29, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 29, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_NAME", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 31, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.DEF_NAME", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging.SETS_LEVEL", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 32, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 32, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 36, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 37, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 38, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 39, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 66, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 66, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 68, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 68, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_LEVEL", "line_number": 69, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 69, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 71, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 79, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 79, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_NAME", "line_number": 80, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 80, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 91, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 91, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_NAME", "line_number": 92, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 92, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 104, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 104, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 106, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 125, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 125, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_FILE", "line_number": 126, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 126, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 128, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 156, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 156, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging._process_settings", "line_number": 158, "usage_type": "call"}, {"api_name": "cp_lib.cp_logging", "line_number": 158, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_SYSLOG_IP", "line_number": 159, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 159, "usage_type": "name"}, {"api_name": "cp_lib.cp_logging.SETS_SYSLOG_PORT", "line_number": 161, "usage_type": "attribute"}, {"api_name": "cp_lib.cp_logging", "line_number": 161, "usage_type": "name"}, {"api_name": "cp_lib.load_settings.propagate_ini_to_json", "line_number": 179, "usage_type": "call"}, {"api_name": "json.load", "line_number": 181, "usage_type": "call"}, {"api_name": "os.path.path.isdir", "line_number": 193, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 193, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 193, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 194, "usage_type": "call"}, {"api_name": "os.path.remove", "line_number": 198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 198, "usage_type": "name"}, {"api_name": "logging.basicConfig", "line_number": 206, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 206, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 207, "usage_type": "call"}]} +{"seq_id": "629813298", "text": "from main import ticker\nfrom csv import DictReader\nimport matplotlib\nimport matplotlib.dates as dates\nimport numpy as np\nimport datetime \n\nclass MovingAverage:\n def __init__(self, numDays):\n self.numDays = numDays\n self.priceQueue = []\n self.movingAverage = []\n\n def isEmpty(self):\n return self.priceQueue == []\n\n def enqueue(self, item):\n self.priceQueue.insert(0, item)\n\n def dequeue(self):\n self.priceQueue.pop()\n \n def size(self):\n return len(self.priceQueue)\n\n def mean(self):\n return sum(self.priceQueue) / float(len(self.priceQueue))\n\n def updateMA(self, day, price):\n self.enqueue(price)\n if day >= self.numDays - 1:\n self.movingAverage.append(self.mean())\n self.dequeue()\n\n#trade algorithm classes should inherit from this class\nclass Trade:\n def __init__(self):\n self.bullishDates = []\n self.bearishDates = []\n self.tradeList = []\n self.returns = []\n self.holding = False\n\n def buy(self, day, price):\n self.startPrice = price\n self.holding = True\n self.bullishDates.append(row['Date'])\n \n #if percent < 100 holding should be True until all shares \"held\" are sold\n #sum of percent should not exceed 100 \n def sell(self, day, price, percent=100, holding=False):\n self.bearishDates.append(row['Date']) \n if self.holding == True: \n self.returns.append(np.round(100 * (price - self.startPrice) / self.startPrice, 2))\n self.holding = False\n\n\nclass MAAlgorithm(Trade):\n def movingAverageIntersection(self, day, price, MA1, MA2):\n if MA2.numDays > MA1.numDays:\n self.smallMA = MA1\n self.bigMA = MA2\n else:\n self.smallMA = MA2\n self.bigMA = MA1\n\n if day >= self.bigMA.numDays:\n self.curSmallMA = self.smallMA.movingAverage[day - self.smallMA.numDays]\n self.curBigMA = self.bigMA.movingAverage[day - self.bigMA.numDays]\n self.prevSmallMA = self.smallMA.movingAverage[day - self.smallMA.numDays - 1]\n self.prevBigMa = self.bigMA.movingAverage[day - self.bigMA.numDays - 1]\n if self.curSmallMA > self.curBigMA and self.prevSmallMA < self.prevBigMa:\n self.buy(day, price)\n \n if self.curSmallMA < self.curBigMA and self.prevSmallMA > self.prevBigMa:\n self.sell(day, price)\n \n\ndayList = []\npriceList = []\nfiftyDay = MovingAverage(50)\ntwoHundredDay = MovingAverage(200)\ntest1 = MAAlgorithm()\nwith open ('data\\\\{}.csv'.format(ticker), 'rt') as csvfile:\n data = DictReader(csvfile)\n day = 0\n for row in data:\n if row['Close'] != 'null':\n dateString = row['Date']\n price = float(row['Close'])\n dayList.append(datetime.datetime.strptime(dateString, \"%Y-%m-%d\")) \n priceList.append(price)\n\n fiftyDay.updateMA(day, price)\n twoHundredDay.updateMA(day, price)\n\n test1.movingAverageIntersection(day, price, fiftyDay, twoHundredDay) \n\n day += 1\n\n\n \n\n\n\n\n\n", "sub_path": "dataAnalysis.py", "file_name": "dataAnalysis.py", "file_ext": "py", "file_size_in_byte": 3164, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.round", "line_number": 54, "usage_type": "call"}, {"api_name": "main.ticker", "line_number": 84, "usage_type": "argument"}, {"api_name": "csv.DictReader", "line_number": 85, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 91, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 91, "usage_type": "attribute"}]} +{"seq_id": "93359381", "text": "from config import *\nimport pykka\nfrom schedule import *\n\nclass ScheduleActor(pykka.ThreadingActor):\n\tdef __init__(self, bot):\n\t\tsuper(ScheduleActor, self).__init__()\n\t\tself.bot = bot\n\t\tself.tape = []\n\t\tself.scheduler = Scheduler()\n\t\tself.state = 'start'\n\n\tdef on_receive(self, message):\n\t\tmsg = message['msg']\n\t\tif self.state == 'start':\n\t\t\tif msg == 'add':\n\t\t\t\tself.state = 'add'\n\t\t\t\tself.bot.send_text('enter interval: ')\n\t\t\telif msg == 'list':\n\t\t\t\tlist = self.scheduler.list_tasks()\n\t\t\t\ts = 'tasks:\\n'\n\t\t\t\tfor i in range(len(list)):\n\t\t\t\t\tif list[i].canceled == False:\n\t\t\t\t\t\ts += str(i) + ': ' + str(list[i].interval) + '\\n'\n\t\t\t\tself.bot.send_text(s)\n\t\t\telif msg == 'cancel':\n\t\t\t\tself.state = 'cancel'\n\t\t\t\tself.bot.send_text('Please enter the task number: ')\n\t\t\telif msg == 'exit':\n\t\t\t\tself.scheduler.clear()\n\t\t\t\tself.bot.send_text('Restart')\n\t\telif self.state == 'add':\n\t\t\tinterval = int(msg)\n\t\t\tself.scheduler.add(Task(self.bot, interval))\n\t\t\tself.state = 'start'\n\t\telif self.state == 'cancel':\n\t\t\ttask_num = int(msg)\n\t\t\tself.scheduler.cancel(self.scheduler.tasks[task_num])\n\t\t\tself.state = 'start'", "sub_path": "actors.py", "file_name": "actors.py", "file_ext": "py", "file_size_in_byte": 1103, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pykka.ThreadingActor", "line_number": 5, "usage_type": "attribute"}]} +{"seq_id": "205193378", "text": "##\n# Copyright (c) 2007-2013 Cyrus Daboo. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##\n\nfrom pycalendar.datetime import DateTime\nfrom pycalendar.icalendar import definitions\nfrom pycalendar.icalendar.component import Component\nfrom pycalendar.icalendar.componentexpanded import ComponentExpanded\nfrom pycalendar.icalendar.property import Property\nfrom pycalendar.icalendar.recurrenceset import RecurrenceSet\nfrom pycalendar.timezone import Timezone\nfrom pycalendar.utils import set_difference\nimport uuid\n\nclass ComponentRecur(Component):\n\n propertyCardinality_STATUS_Fix = (\n definitions.cICalProperty_STATUS,\n )\n\n @staticmethod\n def mapKey(uid, rid=None):\n if uid:\n result = \"u:\" + uid\n if rid is not None:\n result += rid\n return result\n else:\n return None\n\n\n @staticmethod\n def sort_by_dtstart_allday(e1, e2):\n\n if e1.self.mStart.isDateOnly() and e2.self.mStart.isDateOnly():\n return e1.self.mStart < e2.self.mStart\n elif e1.self.mStart.isDateOnly():\n return True\n elif (e2.self.mStart.isDateOnly()):\n return False\n elif e1.self.mStart == e2.self.mStart:\n if e1.self.mEnd == e2.self.mEnd:\n # Put ones created earlier in earlier columns in day view\n return e1.self.mStamp < e2.self.mStamp\n else:\n # Put ones that end later in earlier columns in day view\n return e1.self.mEnd > e2.self.mEnd\n else:\n return e1.self.mStart < e2.self.mStart\n\n\n @staticmethod\n def sort_by_dtstart(e1, e2):\n if e1.self.mStart == e2.self.mStart:\n if (\n e1.self.mStart.isDateOnly() and e2.self.mStart.isDateOnly() or\n not e1.self.mStart.isDateOnly() and not e2.self.mStart.isDateOnly()\n ):\n return False\n else:\n return e1.self.mStart.isDateOnly()\n else:\n return e1.self.mStart < e2.self.mStart\n\n\n def __init__(self, parent=None):\n super(ComponentRecur, self).__init__(parent=parent)\n self.mMaster = self\n self.mMapKey = None\n self.mSummary = None\n self.mStamp = DateTime()\n self.mHasStamp = False\n self.mStart = DateTime()\n self.mHasStart = False\n self.mEnd = DateTime()\n self.mHasEnd = False\n self.mDuration = False\n self.mHasRecurrenceID = False\n self.mAdjustFuture = False\n self.mAdjustPrior = False\n self.mRecurrenceID = None\n self.mRecurrences = None\n\n # This is a special check we do only for STATUS due to a calendarserver bug\n self.cardinalityChecks += (\n self.check_cardinality_STATUS_Fix,\n )\n\n\n def duplicate(self, parent=None):\n other = super(ComponentRecur, self).duplicate(parent=parent)\n\n # Special determination of master\n other.mMaster = self.mMaster if self.recurring() else self\n\n other.mMapKey = self.mMapKey\n\n other.mSummary = self.mSummary\n\n if (self.mStamp is not None):\n other.mStamp = self.mStamp.duplicate()\n other.mHasStamp = self.mHasStamp\n\n other.mStart = self.mStart.duplicate()\n other.mHasStart = self.mHasStart\n other.mEnd = self.mEnd.duplicate()\n other.mHasEnd = self.mHasEnd\n other.mDuration = self.mDuration\n\n other.mHasRecurrenceID = self.mHasRecurrenceID\n other.mAdjustFuture = self.mAdjustFuture\n other.mAdjustPrior = self.mAdjustPrior\n if self.mRecurrenceID is not None:\n other.mRecurrenceID = self.mRecurrenceID.duplicate()\n\n other._resetRecurrenceSet()\n\n return other\n\n\n def canGenerateInstance(self):\n return not self.mHasRecurrenceID\n\n\n def recurring(self):\n return (self.mMaster is not None) and (self.mMaster is not self)\n\n\n def setMaster(self, master):\n self.mMaster = master\n self.initFromMaster()\n\n\n def getMaster(self):\n return self.mMaster\n\n\n def getMapKey(self):\n\n if self.mMapKey is None:\n self.mMapKey = str(uuid.uuid4())\n return self.mMapKey\n\n\n def getMasterKey(self):\n return ComponentRecur.mapKey(self.mUID)\n\n\n def initDTSTAMP(self):\n # Save new one\n super(ComponentRecur, self).initDTSTAMP()\n\n # Get the new one\n temp = self.loadValueDateTime(definitions.cICalProperty_DTSTAMP)\n self.mHasStamp = temp is not None\n if self.mHasStamp:\n self.mStamp = temp\n\n\n def getStamp(self):\n return self.mStamp\n\n\n def hasStamp(self):\n return self.mHasStamp\n\n\n def getStart(self):\n return self.mStart\n\n\n def hasStart(self):\n return self.mHasStart\n\n\n def getEnd(self):\n return self.mEnd\n\n\n def hasEnd(self):\n return self.mHasEnd\n\n\n def useDuration(self):\n return self.mDuration\n\n\n def isRecurrenceInstance(self):\n return self.mHasRecurrenceID\n\n\n def isAdjustFuture(self):\n return self.mAdjustFuture\n\n\n def isAdjustPrior(self):\n return self.mAdjustPrior\n\n\n def getRecurrenceID(self):\n return self.mRecurrenceID\n\n\n def isRecurring(self):\n return (self.mRecurrences is not None) and self.mRecurrences.hasRecurrence()\n\n\n def getRecurrenceSet(self):\n return self.mRecurrences\n\n\n def setUID(self, uid):\n super(ComponentRecur, self).setUID(uid)\n\n # Update the map key\n if self.mHasRecurrenceID:\n self.mMapKey = self.mapKey(self.mUID, self.mRecurrenceID.getText())\n else:\n self.mMapKey = self.mapKey(self.mUID)\n\n\n def getSummary(self):\n return self.mSummary\n\n\n def setSummary(self, summary):\n self.mSummary = summary\n\n\n def getDescription(self):\n # Get DESCRIPTION\n txt = self.loadValueString(definitions.cICalProperty_DESCRIPTION)\n if txt is not None:\n return txt\n else:\n return \"\"\n\n\n def getLocation(self):\n # Get LOCATION\n txt = self.loadValueString(definitions.cICalProperty_LOCATION)\n if txt is not None:\n return txt\n else:\n return \"\"\n\n\n def finalise(self):\n super(ComponentRecur, self).finalise()\n\n # Get DTSTAMP\n temp = self.loadValueDateTime(definitions.cICalProperty_DTSTAMP)\n self.mHasStamp = temp is not None\n if self.mHasStamp:\n self.mStamp = temp\n\n # Get DTSTART\n temp = self.loadValueDateTime(definitions.cICalProperty_DTSTART)\n self.mHasStart = temp is not None\n if self.mHasStart:\n self.mStart = temp\n\n # Get DTEND\n temp = self.loadValueDateTime(definitions.cICalProperty_DTEND)\n if temp is None:\n # Try DURATION instead\n temp = self.loadValueDuration(definitions.cICalProperty_DURATION)\n if temp is not None:\n self.mHasEnd = False\n self.mEnd = self.mStart + temp\n self.mDuration = True\n else:\n # If no end or duration then use the start (bumped by one day for\n # an all day event)\n self.mHasEnd = False\n self.mEnd = self.mStart.duplicate()\n if self.mEnd.isDateOnly():\n self.mEnd.offsetDay(1)\n self.mDuration = False\n else:\n self.mHasEnd = True\n self.mEnd = temp\n self.mDuration = False\n\n # Get SUMMARY\n temp = self.loadValueString(definitions.cICalProperty_SUMMARY)\n if temp is not None:\n self.mSummary = temp\n\n # Get RECURRENCE-ID\n self.mHasRecurrenceID = (self.countProperty(definitions.cICalProperty_RECURRENCE_ID) != 0)\n if self.mHasRecurrenceID:\n self.mRecurrenceID = self.loadValueDateTime(definitions.cICalProperty_RECURRENCE_ID)\n\n # Update the map key\n if self.mHasRecurrenceID:\n self.mMapKey = self.mapKey(self.mUID, self.mRecurrenceID.getText())\n\n # Also get the RANGE parameter\n attrs = self.findFirstProperty(definitions.cICalProperty_RECURRENCE_ID).getParameters()\n if definitions.cICalParameter_RANGE in attrs:\n self.mAdjustFuture = (attrs[definitions.cICalParameter_RANGE][0].getFirstValue() == definitions.cICalParameter_RANGE_THISANDFUTURE)\n self.mAdjustPrior = (attrs[definitions.cICalParameter_RANGE][0].getFirstValue() == definitions.cICalParameter_RANGE_THISANDPRIOR)\n else:\n self.mAdjustFuture = False\n self.mAdjustPrior = False\n else:\n self.mMapKey = self.mapKey(self.mUID)\n\n self._resetRecurrenceSet()\n\n\n def validate(self, doFix=False):\n \"\"\"\n Validate the data in this component and optionally fix any problems. Return\n a tuple containing two lists: the first describes problems that were fixed, the\n second problems that were not fixed. Caller can then decide what to do with unfixed\n issues.\n \"\"\"\n\n # Do normal checks\n fixed, unfixed = super(ComponentRecur, self).validate(doFix)\n\n # Check that any UNTIL value matches that for DTSTART\n if self.mHasStart and self.mRecurrences:\n dtutc = self.mStart.duplicateAsUTC()\n for rrule in self.mRecurrences.getRules():\n if rrule.getUseUntil():\n if rrule.getUntil().isDateOnly() ^ self.mStart.isDateOnly():\n logProblem = \"[%s] Value types must match: %s, %s\" % (\n self.getType(),\n definitions.cICalProperty_DTSTART,\n definitions.cICalValue_RECUR_UNTIL,\n )\n if doFix:\n rrule.getUntil().setDateOnly(self.mStart.isDateOnly())\n if not self.mStart.isDateOnly():\n rrule.getUntil().setHHMMSS(dtutc.getHours(), dtutc.getMinutes(), dtutc.getSeconds())\n rrule.getUntil().setTimezone(Timezone(utc=True))\n self.mRecurrences.changed()\n fixed.append(logProblem)\n else:\n unfixed.append(logProblem)\n\n return fixed, unfixed\n\n\n def check_cardinality_STATUS_Fix(self, fixed, unfixed, doFix):\n \"\"\"\n Special for bug with STATUS where STATUS:CANCELLED is added alongside\n another STATUS. In this case we want STATUS:CANCELLED to win.\n \"\"\"\n for propname in self.propertyCardinality_STATUS_Fix:\n if self.countProperty(propname) > 1:\n logProblem = \"[%s] Too many properties: %s\" % (self.getType(), propname)\n if doFix:\n # Check that one of them is STATUS:CANCELLED\n for prop in self.getProperties(propname):\n if prop.getTextValue().getValue().upper() == definitions.cICalProperty_STATUS_CANCELLED:\n self.removeProperties(propname)\n self.addProperty(Property(propname, definitions.cICalProperty_STATUS_CANCELLED))\n fixed.append(logProblem)\n break\n else:\n unfixed.append(logProblem)\n else:\n unfixed.append(logProblem)\n\n\n def _resetRecurrenceSet(self):\n # May need to create items\n self.mRecurrences = None\n if (\n (self.countProperty(definitions.cICalProperty_RRULE) != 0) or\n (self.countProperty(definitions.cICalProperty_RDATE) != 0) or\n (self.countProperty(definitions.cICalProperty_EXRULE) != 0) or\n (self.countProperty(definitions.cICalProperty_EXDATE) != 0)\n ):\n\n self.mRecurrences = RecurrenceSet()\n\n # Get RRULEs\n self.loadValueRRULE(definitions.cICalProperty_RRULE, self.mRecurrences, True)\n\n # Get RDATEs\n self.loadValueRDATE(definitions.cICalProperty_RDATE, self.mRecurrences, True)\n\n # Get EXRULEs\n self.loadValueRRULE(definitions.cICalProperty_EXRULE, self.mRecurrences, False)\n\n # Get EXDATEs\n self.loadValueRDATE(definitions.cICalProperty_EXDATE, self.mRecurrences, False)\n\n\n def FixStartEnd(self):\n # End is always greater than start if start exists\n if self.mHasStart and self.mEnd <= self.mStart:\n # Use the start\n self.mEnd = self.mStart.duplicate()\n self.mDuration = False\n\n # Adjust to approriate non-inclusive end point\n if self.mStart.isDateOnly():\n self.mEnd.offsetDay(1)\n\n # For all day events it makes sense to use duration\n self.mDuration = True\n else:\n # Use end of current day\n self.mEnd.offsetDay(1)\n self.mEnd.setHHMMSS(0, 0, 0)\n\n\n def expandPeriod(self, period, results):\n # Check for recurrence and True master\n if ((self.mRecurrences is not None) and self.mRecurrences.hasRecurrence()\n and not self.isRecurrenceInstance()):\n # Expand recurrences within the range\n items = []\n self.mRecurrences.expand(self.mStart, period, items)\n\n # Look for overridden recurrence items\n cal = self.mParentComponent\n if cal is not None:\n # Remove recurrence instances from the list of items\n recurs = []\n cal.getRecurrenceInstancesIds(definitions.cICalComponent_VEVENT, self.getUID(), recurs)\n recurs.sort()\n if len(recurs) != 0:\n temp = []\n temp = set_difference(items, recurs)\n items = temp\n\n # Now get actual instances\n instances = []\n cal.getRecurrenceInstancesItems(definitions.cICalComponent_VEVENT, self.getUID(), instances)\n\n # Get list of each ones with RANGE\n prior = []\n future = []\n for iter in instances:\n if iter.isAdjustPrior():\n prior.append(iter)\n if iter.isAdjustFuture():\n future.append(iter)\n\n # Check for special behaviour\n if len(prior) + len(future) == 0:\n # Add each expanded item\n for iter in items:\n results.append(self.createExpanded(self, iter))\n else:\n # Sort each list first\n prior.sort(self.sort_by_dtstart)\n future.sort(self.sort_by_dtstart)\n\n # Add each expanded item\n for iter1 in items:\n\n # Now step through each using the slave item\n # instead of the master as appropriate\n slave = None\n\n # Find most appropriate THISANDPRIOR item\n for i in range(len(prior) - 1, 0, -1):\n riter2 = prior[i]\n if riter2.getStart() > iter1:\n slave = riter2\n break\n\n # Find most appropriate THISANDFUTURE item\n for i in range(len(future) - 1, 0, -1):\n riter2 = future.elementAt(i)\n if riter2.getStart() < iter1:\n slave = riter2\n break\n\n if slave is None:\n slave = self\n results.append(self.createExpanded(slave, iter1))\n else:\n # Add each expanded item\n for iter in items:\n results.append(self.createExpanded(self, iter))\n\n elif self.withinPeriod(period):\n if self.isRecurrenceInstance():\n rid = self.mRecurrenceID\n else:\n rid = None\n results.append(ComponentExpanded(self, rid))\n\n\n def withinPeriod(self, period):\n # Check for recurrence\n if ((self.mRecurrences is not None) and self.mRecurrences.hasRecurrence()):\n items = []\n self.mRecurrences.expand(self.mStart, period, items)\n return len(items) != 0\n else:\n # Does event span the period (assume self.mEnd > self.mStart)\n # Check start (inclusive) and end (exclusive)\n if self.mEnd <= period.getStart() or self.mStart >= period.getEnd():\n return False\n else:\n return True\n\n\n def changedRecurrence(self):\n # Clear cached values\n if self.mRecurrences is not None:\n self.mRecurrences.changed()\n\n\n # Editing\n def editSummary(self, summary):\n # Updated cached value\n self.mSummary = summary\n\n # Remove existing items\n self.editProperty(definitions.cICalProperty_SUMMARY, summary)\n\n\n def editDetails(self, description, location):\n\n # Edit existing items\n self.editProperty(definitions.cICalProperty_DESCRIPTION, description)\n self.editProperty(definitions.cICalProperty_LOCATION, location)\n\n\n def editTiming(self):\n # Updated cached values\n self.mHasStart = False\n self.mHasEnd = False\n self.mDuration = False\n self.mStart.setToday()\n self.mEnd.setToday()\n\n # Remove existing DTSTART & DTEND & DURATION & DUE items\n self.removeProperties(definitions.cICalProperty_DTSTART)\n self.removeProperties(definitions.cICalProperty_DTEND)\n self.removeProperties(definitions.cICalProperty_DURATION)\n self.removeProperties(definitions.cICalProperty_DUE)\n\n\n def editTimingDue(self, due):\n # Updated cached values\n self.mHasStart = False\n self.mHasEnd = True\n self.mDuration = False\n self.mStart = due\n self.mEnd = due\n\n # Remove existing DUE & DTSTART & DTEND & DURATION items\n self.removeProperties(definitions.cICalProperty_DUE)\n self.removeProperties(definitions.cICalProperty_DTSTART)\n self.removeProperties(definitions.cICalProperty_DTEND)\n self.removeProperties(definitions.cICalProperty_DURATION)\n\n # Now create properties\n prop = Property(definitions.cICalProperty_DUE, due)\n self.addProperty(prop)\n\n\n def editTimingStartEnd(self, start, end):\n # Updated cached values\n self.mHasStart = self.mHasEnd = True\n self.mStart = start\n self.mEnd = end\n self.mDuration = False\n self.FixStartEnd()\n # Remove existing DTSTART & DTEND & DURATION & DUE items\n self.removeProperties(definitions.cICalProperty_DTSTART)\n self.removeProperties(definitions.cICalProperty_DTEND)\n self.removeProperties(definitions.cICalProperty_DURATION)\n self.removeProperties(definitions.cICalProperty_DUE)\n\n # Now create properties\n prop = Property(definitions.cICalProperty_DTSTART, start)\n self.addProperty(prop)\n\n # If its an all day event and the end one day after the start, ignore it\n temp = start.duplicate()\n temp.offsetDay(1)\n if not start.isDateOnly() or end != temp:\n prop = Property(definitions.cICalProperty_DTEND, end)\n self.addProperty(prop)\n\n\n def editTimingStartDuration(self, start, duration):\n # Updated cached values\n self.mHasStart = True\n self.mHasEnd = False\n self.mStart = start\n self.mEnd = start + duration\n self.mDuration = True\n\n # Remove existing DTSTART & DTEND & DURATION & DUE items\n self.removeProperties(definitions.cICalProperty_DTSTART)\n self.removeProperties(definitions.cICalProperty_DTEND)\n self.removeProperties(definitions.cICalProperty_DURATION)\n self.removeProperties(definitions.cICalProperty_DUE)\n\n # Now create properties\n prop = Property(definitions.cICalProperty_DTSTART, start)\n self.addProperty(prop)\n\n # If its an all day event and the duration is one day, ignore it\n if (not start.isDateOnly() or (duration.getWeeks() != 0)\n or (duration.getDays() > 1)):\n prop = Property(definitions.cICalProperty_DURATION, duration)\n self.addProperty(prop)\n\n\n def editRecurrenceSet(self, recurs):\n # Must have items\n if self.mRecurrences is None:\n self.mRecurrences = RecurrenceSet()\n\n # Updated cached values\n self.mRecurrences = recurs\n\n # Remove existing RRULE, EXRULE, RDATE & EXDATE\n self.removeProperties(definitions.cICalProperty_RRULE)\n self.removeProperties(definitions.cICalProperty_EXRULE)\n self.removeProperties(definitions.cICalProperty_RDATE)\n self.removeProperties(definitions.cICalProperty_EXDATE)\n\n # Now create properties\n for iter in self.mRecurrences.getRules():\n prop = Property(definitions.cICalProperty_RRULE, iter)\n self.addProperty(prop)\n for iter in self.getExrules():\n prop = Property(definitions.cICalProperty_EXRULE, iter)\n self.addProperty(prop)\n for iter in self.mRecurrences.getDates():\n prop = Property(definitions.cICalProperty_RDATE, iter)\n self.addProperty(prop)\n for iter in self.mRecurrences.getExdates():\n prop = Property(definitions.cICalProperty_EXDATE, iter)\n self.addProperty(prop)\n\n\n def excludeRecurrence(self, start):\n # Must have items\n if self.mRecurrences is None:\n return\n\n # Add to recurrence set and clear cache\n self.mRecurrences.subtract(start)\n\n # Add property\n prop = Property(definitions.cICalProperty_EXDATE, start)\n self.addProperty(prop)\n\n\n def excludeFutureRecurrence(self, start):\n # Must have items\n if self.mRecurrences is None:\n return\n\n # Adjust RRULES to end before start\n self.mRecurrences.excludeFutureRecurrence(start)\n\n # Remove existing RRULE & RDATE\n self.removeProperties(definitions.cICalProperty_RRULE)\n self.removeProperties(definitions.cICalProperty_RDATE)\n\n # Now create properties\n for iter in self.mRecurrences.getRules():\n prop = Property(definitions.cICalProperty_RRULE, iter)\n self.addProperty(prop)\n for iter in self.mRecurrences.getDates():\n prop = Property(definitions.cICalProperty_RDATE, iter)\n self.addProperty(prop)\n\n\n def initFromMaster(self):\n # Only if not master\n if self.recurring():\n # Redo this to get cached values from master\n self.finalise()\n\n # If this component does not have its own start property, use the\n # recurrence id\n # i.e. the start time of this instance has not changed - something\n # else has\n if not self.hasProperty(definitions.cICalProperty_DTSTART):\n self.mStart = self.mRecurrenceID\n\n # If this component does not have its own end/duration property,\n # the determine\n # the end from the master duration\n if (\n not self.hasProperty(definitions.cICalProperty_DTEND) and\n not self.hasProperty(definitions.cICalProperty_DURATION)\n ):\n # End is based on original events settings\n self.mEnd = self.mStart + (self.mMaster.getEnd() - self.mMaster.getStart())\n\n # If this instance has a duration, but no start of its own, then we\n # need to readjust the end\n # to account for the start being changed to the recurrence id\n elif (self.hasProperty(definitions.cICalProperty_DURATION) and\n not self.hasProperty(definitions.cICalProperty_DTSTART)):\n temp = self.loadValueDuration(definitions.cICalProperty_DURATION)\n self.mEnd = self.mStart + temp\n\n\n def createExpanded(self, master, recurid):\n return ComponentExpanded(master, recurid)\n", "sub_path": "src/pycalendar/icalendar/componentrecur.py", "file_name": "componentrecur.py", "file_ext": "py", "file_size_in_byte": 25325, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pycalendar.icalendar.component.Component", "line_number": 27, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_STATUS", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 30, "usage_type": "name"}, {"api_name": "pycalendar.datetime.DateTime", "line_number": 83, "usage_type": "call"}, {"api_name": "pycalendar.datetime.DateTime", "line_number": 85, "usage_type": "call"}, {"api_name": "pycalendar.datetime.DateTime", "line_number": 87, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 153, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTAMP", "line_number": 166, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 166, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DESCRIPTION", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 244, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_LOCATION", "line_number": 253, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 253, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTAMP", "line_number": 264, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 264, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 270, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 270, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 276, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 276, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 279, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 279, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_SUMMARY", "line_number": 298, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 298, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RECURRENCE_ID", "line_number": 303, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 303, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RECURRENCE_ID", "line_number": 305, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 305, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RECURRENCE_ID", "line_number": 312, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 312, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalParameter_RANGE", "line_number": 313, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 313, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalParameter_RANGE", "line_number": 314, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 314, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalParameter_RANGE_THISANDFUTURE", "line_number": 314, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions.cICalParameter_RANGE", "line_number": 315, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 315, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalParameter_RANGE_THISANDPRIOR", "line_number": 315, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 344, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 344, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalValue_RECUR_UNTIL", "line_number": 345, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 345, "usage_type": "name"}, {"api_name": "pycalendar.timezone.Timezone", "line_number": 351, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_STATUS_CANCELLED", "line_number": 371, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 371, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 373, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_STATUS_CANCELLED", "line_number": 373, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 373, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 386, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 386, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 387, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 387, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXRULE", "line_number": 388, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 388, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXDATE", "line_number": 389, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 389, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.recurrenceset.RecurrenceSet", "line_number": 392, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 395, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 395, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 398, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 398, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXRULE", "line_number": 401, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 401, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXDATE", "line_number": 404, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 404, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalComponent_VEVENT", "line_number": 439, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 439, "usage_type": "name"}, {"api_name": "pycalendar.utils.set_difference", "line_number": 443, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalComponent_VEVENT", "line_number": 448, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 448, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.componentexpanded.ComponentExpanded", "line_number": 503, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_SUMMARY", "line_number": 533, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 533, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DESCRIPTION", "line_number": 539, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 539, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_LOCATION", "line_number": 540, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 540, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 552, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 552, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 553, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 553, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 554, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 554, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DUE", "line_number": 555, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 555, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DUE", "line_number": 567, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 567, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 568, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 568, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 569, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 569, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 570, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 570, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 573, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DUE", "line_number": 573, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 573, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 585, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 585, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 586, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 586, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 587, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 587, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DUE", "line_number": 588, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 588, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 591, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 591, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 591, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 598, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 598, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 598, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 611, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 611, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 612, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 612, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 613, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 613, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DUE", "line_number": 614, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 614, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 617, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 617, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 617, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 623, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 623, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 623, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.recurrenceset.RecurrenceSet", "line_number": 630, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 636, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 636, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXRULE", "line_number": 637, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 637, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 638, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 638, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXDATE", "line_number": 639, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 639, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 643, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 643, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 643, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 646, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXRULE", "line_number": 646, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 646, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 649, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 649, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 649, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 652, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXDATE", "line_number": 652, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 652, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 665, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_EXDATE", "line_number": 665, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 665, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 678, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 678, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 679, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 679, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 683, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RRULE", "line_number": 683, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 683, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.property.Property", "line_number": 686, "usage_type": "call"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_RDATE", "line_number": 686, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 686, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 700, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 700, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTEND", "line_number": 707, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 707, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 708, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 708, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 716, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 716, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DTSTART", "line_number": 717, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 717, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.definitions.cICalProperty_DURATION", "line_number": 718, "usage_type": "attribute"}, {"api_name": "pycalendar.icalendar.definitions", "line_number": 718, "usage_type": "name"}, {"api_name": "pycalendar.icalendar.componentexpanded.ComponentExpanded", "line_number": 723, "usage_type": "call"}]} +{"seq_id": "103350289", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, render\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.contrib.auth import *\nfrom django.views.generic import *\nfrom administrador.forms import *\nfrom administrador.models import *\nfrom administrador.controllers import *\nfrom medico.models import *\n\n\nclass Index(TemplateView):\n template_name = 'index.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n Index, self).get_context_data(**kwargs)\n return context\n\n\nclass Register(CreateView):\n template_name = 'register.html'\n form_class = UsuarioForm\n\n def get_context_data(self, **kwargs):\n context = super(\n Register, self).get_context_data(**kwargs)\n return context\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n form = UsuarioForm(request.POST)\n if form.is_valid():\n # Registramos al usuario\n register_user(form)\n return HttpResponseRedirect(reverse_lazy('index'))\n else:\n return render_to_response('register.html',\n {'form': form},\n context_instance=RequestContext(\n request))\n\n\ndef authenticate_user(username=None, password=None):\n \"\"\" Authenticate a user based on email address as the user name. \"\"\"\n try:\n user = User.objects.get(email=username)\n if user is not None:\n return user\n except User.DoesNotExist:\n try:\n user = User.objects.get(username=username)\n if user is not None:\n return user\n except User.DoesNotExist:\n return None\n\n\ndef user_login(request):\n if request.user.is_authenticated():\n return HttpResponseRedirect(\n reverse_lazy('home'))\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user_auth = authenticate_user(username, password)\n if user_auth is not None:\n if user_auth.is_active:\n user = authenticate(username=user_auth.username,\n password=password)\n if user:\n login(request, user)\n return HttpResponseRedirect(\n reverse_lazy('home'))\n else:\n form.add_error(\n None, \"Tu correo o contraseña no son correctos\")\n else:\n form.add_error(None, \"Aún no has confirmado tu correo.\")\n user = None\n else:\n form.add_error(\n None, \"Tu correo o contraseña no son correctos\")\n else:\n context = {'form': form}\n return render_to_response('index.html', context,\n context_instance=RequestContext(request))\n\n else:\n form = LoginForm()\n context = {'form': form, 'host': request.get_host()}\n return render_to_response('index.html', context,\n context_instance=RequestContext(request))\n\n\nclass Success(TemplateView):\n template_name = 'success.html'\n\n\nclass Home(TemplateView):\n template_name = 'home.html'\n\n\nclass Inbox(TemplateView):\n template_name = 'administrador/inbox.html'\n\n\nclass VerUsuarios(TemplateView):\n template_name = 'administrador/ver_usuarios.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n VerUsuarios, self).get_context_data(**kwargs)\n\n usuarios = Usuario.objects.all()\n context['usuarios'] = usuarios\n return context\n\n\nclass ModificarUsuario(CreateView):\n template_name = 'administrador/modificar_usuario.html'\n form_class = ModificarUsuarioForm\n\n def get_context_data(self, **kwargs):\n context = super(\n ModificarUsuario, self).get_context_data(**kwargs)\n usuario = Usuario.objects.get(pk=self.kwargs['pk'])\n form = UsuarioForm(\n initial={'username': usuario.user.username,\n 'first_name': usuario.user.first_name,\n 'last_name': usuario.user.last_name,\n 'email': usuario.user.email,\n 'rol': usuario.user.groups.all()[0],\n }\n )\n\n context['form'] = form\n context['usuario'] = usuario\n\n return context\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n form = ModificarUsuarioForm(request.POST)\n form.fields['passw'].required = False\n form.fields['ci'].required = False\n if form.is_valid():\n usuario_id = kwargs['pk']\n username = request.POST['username']\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n email = request.POST['email']\n rol = request.POST['rol']\n value = modificar_usuario(usuario_id, username,\n first_name, last_name,\n email, rol)\n if value is True:\n return HttpResponseRedirect(reverse_lazy(\n 'ver_usuarios'))\n else:\n return render_to_response('administrador/modificar_usuario.html',\n {'form': form,\n 'title': 'Modificar'},\n context_instance=RequestContext(\n request))\n else:\n return render_to_response('administrador/modificar_usuario.html',\n {'form': form,\n 'title': 'Modificar'},\n context_instance=RequestContext(request))\n\n\nclass VerRoles(TemplateView):\n template_name = 'administrador/ver_roles.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n VerRoles, self).get_context_data(**kwargs)\n\n roles = Group.objects.all()\n context['roles'] = roles\n return context\n\n\nclass VerInstituciones(TemplateView):\n template_name = 'administrador/ver_instituciones.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n VerInstituciones, self).get_context_data(**kwargs)\n\n instituciones = Institucion.objects.all()\n context['instituciones'] = instituciones\n return context\n\n\nclass AgregarInstitucion(CreateView):\n template_name = 'administrador/crear_institucion.html'\n form_class = InstitucionForm\n\n def get_context_data(self, **kwargs):\n context = super(\n AgregarInstitucion, self).get_context_data(**kwargs)\n\n context['title'] = 'Agregar'\n\n return context\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n form = InstitucionForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse_lazy('ver_instituciones'))\n else:\n return render_to_response(\n 'administrador/crear_institucion.html', {'form': form},\n context_instance=RequestContext(request))\n\n\nclass ModificarInstitucion(UpdateView):\n template_name = 'administrador/crear_institucion.html'\n form_class = InstitucionForm\n success_url = reverse_lazy('ver_instituciones')\n\n def get_queryset(self):\n return Institucion.objects.filter(pk=self.kwargs['pk'])\n\n def get_context_data(self, **kwargs):\n context = super(\n ModificarInstitucion, self).get_context_data(**kwargs)\n institucion = Institucion.objects.get(pk=self.kwargs['pk'])\n form = InstitucionForm(initial={'name': institucion.name,\n 'address': institucion.address})\n context['institucion'] = institucion\n context['form'] = form\n context['title'] = 'Modificar'\n\n return context\n\n\nclass VerEspecialidades(TemplateView):\n template_name = 'administrador/ver_especialidades.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n VerEspecialidades, self).get_context_data(**kwargs)\n\n especialidad = Especialidad.objects.all()\n context['especialidades'] = especialidad\n return context\n\n\nclass AgregarEspecialidad(CreateView):\n template_name = 'administrador/crear_especialidad.html'\n form_class = EspecialidadForm\n\n def get_context_data(self, **kwargs):\n context = super(\n AgregarEspecialidad, self).get_context_data(**kwargs)\n\n context['title'] = 'Agregar'\n\n return context\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n form = EspecialidadForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse_lazy('ver_especialidades'))\n else:\n return render_to_response(\n 'administrador/crear_especialidad.html', {'form': form},\n context_instance=RequestContext(request))\n\n\nclass GestionarHistorias(TemplateView):\n template_name = 'administrador/gestionar_historias.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n GestionarHistorias, self).get_context_data(**kwargs)\n\n especialidades = Especialidad.objects.all()\n\n context['especialidades'] = especialidades\n\n return context\n\n\nclass VerPreguntas(TemplateView):\n template_name = 'administrador/ver_preguntas.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n VerPreguntas, self).get_context_data(**kwargs)\n preguntas = Pregunta.objects.filter(especialidad__pk=self.kwargs['pk'])\n especialidad = Especialidad.objects.get(pk=self.kwargs['pk'])\n context['preguntas'] = preguntas\n context['especialidad'] = especialidad\n\n return context\n\n\nclass CrearPregunta(CreateView):\n template_name = 'administrador/modificar_pregunta.html'\n form_class = PreguntasForm\n\n def get_context_data(self, **kwargs):\n context = super(\n CrearPregunta, self).get_context_data(**kwargs)\n\n form = PreguntasForm()\n\n context['form'] = form\n context['title'] = 'Crear'\n\n return context\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n result = crear_pregunta(request.POST['pregunta'], kwargs['pk'])\n if result is True:\n return HttpResponseRedirect(reverse_lazy('ver_preguntas', kwargs={'pk': kwargs['pk']}))\n else:\n return render_to_response(\n 'administrador/modificar_pregunta.html',\n context_instance=RequestContext(request))\n\n\nclass ModificarPregunta(UpdateView):\n template_name = 'administrador/modificar_pregunta.html'\n form_class = PreguntasForm\n success_url = reverse_lazy('gestionar_historias')\n\n def get_queryset(self):\n return Pregunta.objects.filter(pk=self.kwargs['pk'])\n\n def get_context_data(self, **kwargs):\n context = super(\n ModificarPregunta, self).get_context_data(**kwargs)\n\n pregunta = Pregunta.objects.get(pk=self.kwargs['pk'])\n\n form = PreguntasForm(\n initial={'pregunta': pregunta.pregunta})\n\n context['form'] = form\n context['title'] = 'Modificar'\n\n return context\n", "sub_path": "administrador/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 12536, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.http.HttpResponseRedirect", "line_number": 42, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 42, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 44, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 46, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 67, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 68, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 81, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 82, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 94, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 95, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 100, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 101, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 169, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 169, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 172, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 175, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 178, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 181, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 228, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 228, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 230, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 232, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 238, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 288, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 288, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 290, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 292, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 345, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 345, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 347, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 349, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 355, "usage_type": "call"}]} +{"seq_id": "108110726", "text": "\"\"\"\nPROGRAM SOLIDS\n--------------\n\nComputes the displacement solution for a finite element assembly\nof 2D solids under point loads using as input easy-to-create\ntext files containing element, nodal, materials and loads data.\nFortran subroutines mesher.for and contour.for are also available to\nwrite the required input files out of a Gmesh (.msh) generated file\nand to convert the results file into Gmesh post-processor files.\n\nCreated by Juan Gomez and Nicolas Guarin-Zapata as part of the course:\n\nIC0283 COMPUTATIONAL MODELLING\nUniversidad EAFIT\nDepartamento de Ingenieria Civil\n\nLast updated January 2016\n\"\"\"\nimport numpy as np\nimport preprocesor as pre\nimport postprocesor as pos\nimport assemutil as ass\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport easygui\n\n\nfolder = easygui.diropenbox(title=\"Folder for the job\") + \"/\"\nname = easygui.enterbox(\"Enter the job name\")\necho = easygui.buttonbox(\"Do you want to echo files?\",\n choices=[\"Yes\", \"No\"]) \n\nstart_time = datetime.now()\n\n\n#%%\n# MODEL ASSEMBLY\n#\n# Reads the model\nnodes, mats, elements, loads = pre.readin(folder=folder)\nif echo == \"Yes\":\n pre.echomod(nodes, mats, elements, loads, folder=folder)\n# Retrieves problem parameters\nne, nn, nm, nl, COORD = pre.proini(nodes, mats, elements, loads)\n# Counts equations and creates BCs array IBC\nneq, IBC = ass.eqcounter(nn, nodes)\n# Computes assembly operator\nDME, IELCON = ass.DME(IBC, ne, elements)\n# Assembles Global Stiffness Matrix KG\nKG = ass.matassem(IBC, mats, elements, nn, ne, neq, COORD, DME, IELCON)\n# Assembles Global Rigth Hand Side Vector RHSG\nRHSG = ass.loadasem(loads, IBC, neq, nl)\n\n#%%\n# SYSTEM SOLUTION\n#\n# Solves the system\nUG = np.linalg.solve(KG, RHSG)\nif not(np.allclose(np.dot(KG, UG), RHSG)):\n print(\"The system is not in equilibrium!\")\nend_time = datetime.now()\nprint('Duration for system solution: {}'.format(end_time - start_time))\n\n#%%\n# POST-PROCCESSING\n#\nstart_time = datetime.now()\nUC = pos.complete_disp(IBC, nodes, UG)\npos.plot_disp(UC, nodes, elements)\n\n# Scatter displacements over the elements\nUU = pos.scatter(DME, UG, ne, neq, elements)\npos.gmeshpost(IBC, nn, UG, folder=folder)\n# Generates points inside the elements and computes strain solution\nE_nodes, S_nodes = pos.strain_nodes(IELCON, UU, ne, COORD, elements, mats)\npos.plot_strain(E_nodes, nodes, elements)\npos.plot_stress(S_nodes, nodes, elements, plt_type=\"pcolor\")\neigs1, eigs2, vecs1, vecs2 = pos.principal_dirs(S_nodes)\ntri = pos.mesh2tri(nodes, elements)\npos.tri_plot(tri, eigs1, title=r\"Maximum stress: $\\sigma_1$\")\nplt.quiver(nodes[:, 1], nodes[:, 2], vecs1[:,0], vecs1[:,1], pivot=\"middle\",\n headwidth=1.5, headlength=2.5)\nend_time = datetime.now()\nprint('Duration for post processing: {}'.format(end_time - start_time))\nprint('Program terminated succesfully!')\nplt.show()\n", "sub_path": "MAIN/solids_ISO_GUI.py", "file_name": "solids_ISO_GUI.py", "file_ext": "py", "file_size_in_byte": 2856, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "easygui.diropenbox", "line_number": 29, "usage_type": "call"}, {"api_name": "easygui.enterbox", "line_number": 30, "usage_type": "call"}, {"api_name": "easygui.buttonbox", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 34, "usage_type": "name"}, {"api_name": "preprocesor.readin", "line_number": 41, "usage_type": "call"}, {"api_name": "preprocesor.echomod", "line_number": 43, "usage_type": "call"}, {"api_name": "preprocesor.proini", "line_number": 45, "usage_type": "call"}, {"api_name": "assemutil.eqcounter", "line_number": 47, "usage_type": "call"}, {"api_name": "assemutil.DME", "line_number": 49, "usage_type": "call"}, {"api_name": "assemutil.matassem", "line_number": 51, "usage_type": "call"}, {"api_name": "assemutil.loadasem", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.linalg.solve", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.allclose", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 62, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 62, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 68, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 68, "usage_type": "name"}, {"api_name": "postprocesor.complete_disp", "line_number": 69, "usage_type": "call"}, {"api_name": "postprocesor.plot_disp", "line_number": 70, "usage_type": "call"}, {"api_name": "postprocesor.scatter", "line_number": 73, "usage_type": "call"}, {"api_name": "postprocesor.gmeshpost", "line_number": 74, "usage_type": "call"}, {"api_name": "postprocesor.strain_nodes", "line_number": 76, "usage_type": "call"}, {"api_name": "postprocesor.plot_strain", "line_number": 77, "usage_type": "call"}, {"api_name": "postprocesor.plot_stress", "line_number": 78, "usage_type": "call"}, {"api_name": "postprocesor.principal_dirs", "line_number": 79, "usage_type": "call"}, {"api_name": "postprocesor.mesh2tri", "line_number": 80, "usage_type": "call"}, {"api_name": "postprocesor.tri_plot", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.quiver", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}]} +{"seq_id": "333965901", "text": "import numpy as np\nimport cv2\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n# Identify pixels above the threshold\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\n # Create an array of ones same xy size as img, but single channel\n color_select = np.zeros_like(img[:,:,0])\n # Require that each pixel be above all three threshold values in RGB\n # above_thresh will now contain a boolean array with \"True\"\n # where threshold was met\n above_thresh = (img[:,:,0] > rgb_thresh[0]) \\\n & (img[:,:,1] > rgb_thresh[1]) \\\n & (img[:,:,2] > rgb_thresh[2])\n # Index the array of zeros with the boolean array and set to 1\n color_select[above_thresh] = 1\n # Return the binary image\n return color_select\n\n# Detect color threshold within a given upper and lower bound\ndef color_thresh_range(img, rgb_thresh_low=(130, 110, 0), rgb_thresh_high=(210, 180, 40)):\n\n color_select = np.zeros_like(img[:,:,0])\n\n within_thresh = (img[:,:,0] > rgb_thresh_low[0]) & (img[:,:,1] > rgb_thresh_low[1]) & (img[:,:,2] > rgb_thresh_low[2]) & (img[:,:,0] < rgb_thresh_high[0]) & (img[:,:,1] < rgb_thresh_high[1]) & (img[:,:,2] < rgb_thresh_high[2])\n \n color_select[within_thresh] = 1\n return color_select\n\n# Define a function to convert from image coords to rover coords\ndef rover_coords(binary_img):\n # Identify nonzero pixels\n ypos, xpos = binary_img.nonzero()\n # Calculate pixel positions with reference to the rover position being at the \n # center bottom of the image. \n x_pixel = -(ypos - binary_img.shape[0]).astype(np.float)\n y_pixel = -(xpos - binary_img.shape[1]/2 ).astype(np.float)\n return x_pixel, y_pixel\n\n\n# Define a function to convert to radial coords in rover space\ndef to_polar_coords(x_pixel, y_pixel):\n # Convert (x_pixel, y_pixel) to (distance, angle) \n # in polar coordinates in rover space\n # Calculate distance to each pixel\n dist = np.sqrt(x_pixel**2 + y_pixel**2)\n # Calculate angle away from vertical for each pixel\n angles = np.arctan2(y_pixel, x_pixel)\n return dist, angles\n\n# Define a function to map rover space pixels to world space\ndef rotate_pix(xpix, ypix, yaw):\n # Convert yaw to radians\n yaw_rad = yaw * np.pi / 180\n xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad))\n \n ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))\n # Return the result \n return xpix_rotated, ypix_rotated\n\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \n # Apply a scaling and a translation\n xpix_translated = (xpix_rot / scale) + xpos\n ypix_translated = (ypix_rot / scale) + ypos\n # Return the result \n return xpix_translated, ypix_translated\n\n\n# Define a function to apply rotation and translation (and clipping)\n# Once you define the two functions above this function should work\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\n # Apply rotation\n xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\n # Apply translation\n xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\n # Perform rotation, translation and clipping all at once\n x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\n y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\n # Return the result\n return x_pix_world, y_pix_world\n\n# Define a function to perform a perspective transform\ndef perspect_transform(img, src, dst):\n \n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\n\n mask = cv2.warpPerspective(np.ones_like(img[:,:,0]), M, (img.shape[1], img.shape[0]))\n \n return warped, mask\n\n\n# Apply the above functions in succession and update the Rover state accordingly\ndef perception_step(Rover):\n # Perform perception steps to update Rover()\n # TODO: \n # NOTE: camera image is coming to you in Rover.img\n image = Rover.img\n\n valid_cam_img = True\n # 0) Image is really only valid if roll and pitch are ~0\n if Rover.pitch > 0.25 and Rover.pitch < 359.75:\n rvalid_cam_img = False\n elif Rover.roll > 0.75 and Rover.roll < 359.25:\n valid_cam_img = False\n \n # 1) Define source and destination points for perspective transform\n source = np.float32([[14, 140], [301, 140], [200, 96], [118, 96]])\n\n dst_size = 5 \n bottom_offset = 6\n destination = np.float32([[image.shape[1]/2 - dst_size, image.shape[0] - bottom_offset],\n [image.shape[1]/2 + dst_size, image.shape[0] - bottom_offset],\n [image.shape[1]/2 + dst_size, image.shape[0] - 2*dst_size - bottom_offset], \n [image.shape[1]/2 - dst_size, image.shape[0] - 2*dst_size - bottom_offset],\n ])\n\n # 2) Apply perspective transform\n warped_cam_view, cam_view_mask = perspect_transform(Rover.img, source, destination)\n\n # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\n nav_terrain_cam_view = color_thresh(warped_cam_view, rgb_thresh=(140, 160, 160))\n \n obstacle_cam_view = np.absolute(np.float32(nav_terrain_cam_view) -1) * cam_view_mask\n\n rock_cam_view = color_thresh_range(warped_cam_view, rgb_thresh_low=(130, 110, 0), rgb_thresh_high=(210, 180, 40))\n \n # 4) Update Rover.vision_image (this will be displayed on left side of screen)\n # Example: Rover.vision_image[:,:,0] = obstacle color-thresholded binary image\n # Rover.vision_image[:,:,1] = rock_sample color-thresholded binary image\n # Rover.vision_image[:,:,2] = navigable terrain color-thresholded binary image\n Rover.vision_image[:,:,0] = obstacle_cam_view * 255\n Rover.vision_image[:,:,1] = rock_cam_view * 255\n Rover.vision_image[:,:,2] = nav_terrain_cam_view * 255\n\n # 5) Convert map image pixel values to rover-centric coords\n nav_xpix, nav_ypix = rover_coords(nav_terrain_cam_view)\n obs_xpix, obs_ypix = rover_coords(obstacle_cam_view)\n rock_xpix, rock_ypix = rover_coords(rock_cam_view)\n\n # 6) Convert rover-centric pixel values to world coordinates\n scale = 10\n \n navigable_x_world, navigable_y_world = pix_to_world(nav_xpix, nav_ypix, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale) \n obstacle_x_world, obstacle_y_world = pix_to_world(obs_xpix, obs_ypix, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale)\n rock_x_world, rock_y_world = pix_to_world(rock_xpix, rock_ypix, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale)\n\n # Per the Walkthrough video, best to compensate for the actual location of the rocks which is lost during transformation\n if rock_cam_view.any():\n\n rock_distance, rock_angle = to_polar_coords(rock_xpix, rock_ypix)\n rock_index = np.argmin(rock_distance)\n rock_x_center = rock_x_world[rock_index]\n rock_y_center = rock_y_world[rock_index]\n Rover.rock_angle = rock_angle\n Rover.rock_dist = rock_distance\n else:\n Rover.rock_angle = None\n Rover.rock_dist = None\n\n\n # 7) Update Rover worldmap (to be displayed on right side of screen)\n # Example: Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1\n # Rover.worldmap[rock_y_world, rock_x_world, 1] += 1\n # Rover.worldmap[navigable_y_world, navigable_x_world, 2] += 1\n \n # only update world mape if camera image was valid\n if valid_cam_img:\n Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] += 5\n\n if rock_cam_view.any():\n Rover.worldmap[rock_y_center, rock_x_center, 1] += 255\n\n Rover.worldmap[navigable_y_world, navigable_x_world, 2] += 50\n\n # 8) Convert rover-centric pixel positions to polar coordinates\n # Update Rover pixel distances and angles\n # Rover.nav_dists = rover_centric_pixel_distances\n # Rover.nav_angles = rover_centric_angles\n rover_centric_pixel_distances, rover_centric_angles = to_polar_coords(nav_xpix, nav_ypix)\n Rover.nav_angles = rover_centric_angles\n Rover.nav_dists = rover_centric_pixel_distances\n \n \n return Rover", "sub_path": "code/perception.py", "file_name": "perception.py", "file_ext": "py", "file_size_in_byte": 8300, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.zeros_like", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.float", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 81, "usage_type": "call"}, {"api_name": "cv2.getPerspectiveTransform", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.warpPerspective", "line_number": 89, "usage_type": "call"}, {"api_name": "cv2.warpPerspective", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 155, "usage_type": "call"}]} +{"seq_id": "449436392", "text": "import re\nfrom zope.interface import implementer\nfrom twisted.internet import endpoints\nfrom foolscap.ipb import IConnectionHintHandler, InvalidHintError\n\n# This can match IPv4 IP addresses + port numbers *or* host names +\n# port numbers.\nDOTTED_QUAD_RESTR=r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"\nDNS_NAME_RESTR=r\"[A-Za-z.0-9\\-]+\"\nOLD_STYLE_HINT_RE=re.compile(r\"^(%s|%s):(\\d+){1,5}$\" % (DOTTED_QUAD_RESTR,\n DNS_NAME_RESTR))\nNEW_STYLE_HINT_RE=re.compile(r\"^tcp:(%s|%s):(\\d+){1,5}$\" % (DOTTED_QUAD_RESTR,\n DNS_NAME_RESTR))\n\n# Each location hint must start with \"TYPE:\" (where TYPE is alphanumeric) and\n# then can contain any characters except \",\" and \"/\". These are expected to\n# contain \":\"-separated fields (e.g. \"TYPE:stuff:morestuff\" or\n# \"TYPE:key=value:key=value\").\n\n# For compatibility with current and older Foolscap releases, we also accept\n# old-syle implicit TCP hints (\"host:port\"). These are caught and converted\n# into new-style \"tcp:HOST:PORT\" hints in convert_legacy_hint() before we\n# look up the handler.\n\n# To avoid being interpreted as an old-style hint, the part after TYPE: may\n# not consist of only 1-5 digits (so \"type:123\" will be treated as type=\"tcp\"\n# and hostname=\"type\"). Creators of new hint types are advised to either use\n# multiple colons (e.g. tor:HOST:PORT), or use key=value in the right-hand\n# portion (e.g. systemd:fd=3).\n\n# Future versions of foolscap may put hints in their FURLs which we do not\n# understand. We will ignore such hints. This version understands two types\n# of hints:\n#\n# HOST:PORT (old-style implicit tcp)\n# tcp:HOST:PORT (endpoint syntax for TCP connections)\n\ndef convert_legacy_hint(location):\n mo = OLD_STYLE_HINT_RE.search(location)\n if mo:\n host, port = mo.group(1), int(mo.group(2))\n return \"tcp:%s:%d\" % (host, port)\n return location\n\n@implementer(IConnectionHintHandler)\nclass DefaultTCP:\n def hint_to_endpoint(self, hint, reactor):\n # Return (endpoint, hostname), where \"hostname\" is what we pass to the\n # HTTP \"Host:\" header so a dumb HTTP server can be used to redirect us.\n mo = NEW_STYLE_HINT_RE.search(hint)\n if not mo:\n raise InvalidHintError(\"unrecognized TCP hint\")\n host, port = mo.group(1), int(mo.group(2))\n return endpoints.TCP4ClientEndpoint(reactor, host, port), host\n", "sub_path": "foolscap/connection_plugins.py", "file_name": "connection_plugins.py", "file_ext": "py", "file_size_in_byte": 2469, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "re.compile", "line_number": 10, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 12, "usage_type": "call"}, {"api_name": "foolscap.ipb.InvalidHintError", "line_number": 52, "usage_type": "call"}, {"api_name": "twisted.internet.endpoints.TCP4ClientEndpoint", "line_number": 54, "usage_type": "call"}, {"api_name": "twisted.internet.endpoints", "line_number": 54, "usage_type": "name"}, {"api_name": "zope.interface.implementer", "line_number": 45, "usage_type": "call"}, {"api_name": "foolscap.ipb.IConnectionHintHandler", "line_number": 45, "usage_type": "argument"}]} +{"seq_id": "315014365", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function, absolute_import\n\nimport os\nfrom datetime import datetime\nimport dateutil.parser\n\nimport click\n\nfrom click_project.config import config\nfrom click_project.decorators import group, option, argument, use_settings,\\\n pass_context, flag, table_format, table_fields\nfrom click_project.lib import rm, copy, TablePrinter\nfrom click_project.commands.git_store import _save, restore, current_remote,\\\n GitRemoteType, push as git_store_push, fetch as git_store_fetch,\\\n get_refs, remove as git_store_remove\nfrom click_project.log import get_logger\nfrom click_project.overloads import CommandSettingsKeyType\n\nLOGGER = get_logger(__name__)\n\n\nclass GitRecordConfig(object):\n pass\n\n\ndef assert_file_in_level(files):\n for file in files:\n if file not in config.git_record.writable:\n raise click.UsageError(\n \"{} not in level {}, try to use another level\".format(\n file, config.git_record.writeprofile\n )\n )\n\n\ndef assert_indices(files, index):\n for file in files:\n length = len(config.git_record.writable[file])\n if length <= index:\n raise click.UsageError(\n \"The record {} does not have enough record ({})\"\n \" to be given the index {}\".format(file, length, index)\n )\n\n\n@group(default_command=\"show\")\n@use_settings(\"git_record\", GitRecordConfig)\ndef git_record():\n \"\"\"With git-record, you record data files in your project that will not be\n committed but still be available by anyone cloning the git repository. In\n addition, it records the location of the data so that you don't even need to\n copy/move anything manually.\n\n To record that the directory/file foo is data, run \"git-record add\n foo\". foo will be stored in git and recorded in the project configuration.\n This command may be run several times to record another\n version of foo.\n\n To see what files are currently recorded, run \"git-record show\". It will\n show the location of the recorded files as well as their unique name known\n in git. The later ensures that the file content is always the same: thus, a\n change implies a change in the content of the file.\n\n To upload all the files so that everyone can download them, run \"git-record\n upload\"\n\n To restore the files so that they become visible in your file system, run\n \"git-record restore\". This command may be run several times to reset the\n files in case of unwanted changes.\n\n RATIONALE:\n\n It is a well known fact that storing data files in a version control system\n (VCS), such as git or svn, is a bad idea. This is because once committed,\n you can never ask the VCS to forget the data, and accumulation of data may\n take a lot of space. At some point, you generally want to archive old data\n in some backup disk and don't want to here of it anymore.\n\n On another hand, the core of git is basically a file storage system. Hence,\n while committing data in git is a bad idea, storing data is worth the try.\n\n The main advantage of this solution is that you don't need to remember the\n credential/location of the data in some random nas. The second good point is\n that since git is a content addressable storage, you are ensured to always\n get the same data: there is no risk of someone else modifying the data\n without you being aware of it.\n\n \"\"\"\n config.require_project()\n\n\n@git_record.command()\n@argument(\"file\", help=\"The file to add.\")\n@option(\"--name\", help=(\n \"Name to use, instead of the computed one.\"\n \" You should not need this option,\"\n \" unless in very specific advanced use cases\"\n))\n@option(\"-m\", \"--message\", help=\"Message to describe the record\")\n@flag(\"--create-hash-file/--dont-create-hash-file\",\n default=True,\n help=\"Create a hash file, to be consumed by generated hash scripts\")\n@flag(\"--upload/--no-upload\", help=(\n \"Upload the content as soon as added.\"\n \" People tend to forget to upload and think their data is safe on the remote.\"\n \" The default value of True is then conservative.\"), default=True)\n@pass_context\ndef add(ctx, file, name, message, create_hash_file, upload):\n \"\"\"Add the data file/directory in the git record\n\n If a content was already associated to the file, add this one on top of the\n list, allowing to retrieve later old versions of the file.\n\n You can provide a message to describe the file, so that you remember why you\n stored it.\n\n \"\"\"\n full = os.path.abspath(file)\n rel = os.path.relpath(full, config.project)\n name = _save(name, file, False, create_hash_file=create_hash_file)\n records = config.git_record.writable.get(rel, [])\n records.append({\n \"name\": name,\n \"documentation\": message,\n \"date\": datetime.now().isoformat(),\n })\n config.git_record.writable[rel] = records\n config.git_record.write()\n LOGGER.status(\"Successfully added {}\".format(name))\n if upload:\n ctx.invoke(_upload, file=(rel,))\n\n\n@git_record.command()\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\ndef remove(file):\n \"\"\"Remove the file from the git record\n\n Only the association between a git file and the given location is\n removed. To remove from git the unused files, use git-record prune.\n\n \"\"\"\n for fil in file:\n del config.git_record.writable[fil]\n LOGGER.status(\"Successfully removed {}\".format(fil))\n config.git_record.write()\n\n\n@git_record.command()\n@pass_context\ndef prune_git_files(ctx):\n \"\"\"Remove all the git files not in the git-record\n\n It removes from git all the files that are no more references by git\n records. Use this command only if you know what you are doing.\n\n \"\"\"\n for ref in [r[1] for r in get_refs()]:\n if ref not in [\n record[\"name\"]\n for records in config.git_record.readonly.values()\n for record in records\n ]:\n ctx.invoke(git_store_remove, name=\"refs/git-store/\" + ref)\n\n\n@git_record.command()\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\n@pass_context\ndef prune_old_records(ctx, file):\n \"\"\"Remove all the old records\n\nKeeping only the last record.\n\"\"\"\n file = file or config.git_record.writable.keys()\n assert_file_in_level(file)\n pruned = 0\n for fil in file:\n for name, records in config.git_record.writable.items():\n if len(records) > 1:\n pruned += len(records) - 1\n config.git_record.writable[name] = [records[-1]]\n config.git_record.write()\n if pruned:\n LOGGER.info(\n \"Pruned {} records,\"\n \" you might want to run the prune-git-files also.\".format(\n pruned\n )\n )\n\n\n@git_record.command()\ndef clean():\n \"\"\"Remove the files/directories known by git from your file system\n\n It makes the file system bare naked, like before the first restore call.\n\n \"\"\"\n for rel in config.git_record.readonly.keys():\n full = os.path.join(config.project, rel)\n if os.path.exists(full):\n LOGGER.status(\"Removing {}\".format(rel))\n rm(full)\n\n\n@git_record.command()\n@option(\"-f\", \"--from\", \"remote\", default=current_remote, type=GitRemoteType(),\n help=\"The remote to download from\")\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\n@pass_context\ndef _restore(ctx, file, remote):\n \"\"\"Restore the files from git\n\n Make them appear in your file system. If the files already exist, reset them\n to the content they should have.\n\n \"\"\"\n file = file or config.git_record.readonly.keys()\n ctx.invoke(download, file=file, remote=remote)\n for fil in file:\n values = config.git_record.readonly[fil]\n full = os.path.join(config.project, fil)\n name = values[-1][\"name\"]\n ctx.invoke(restore, file=full, name=\"refs/git-store/\" + name)\n\n\n@git_record.command(handle_dry_run=True)\n@option(\"-i\", \"--index\", help=\"Index of the record to take into account.\"\n \" 1 is the most recent one.\", type=int, default=1)\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\ndef pop(file, index):\n \"\"\"Pop the git records at index\"\"\"\n if not file:\n raise click.UsageError(\"You must precise at least one file to act upon\")\n assert_indices(file, index)\n assert_file_in_level(file)\n for fil in file:\n records = config.git_record.writable[fil]\n LOGGER.status(\"Erasing record at index {} for file {}\".format(index, fil))\n del records[-index]\n config.git_record.writable[fil] = records\n config.git_record.write()\n\n\n@git_record.command(handle_dry_run=True)\n@table_format(default='key_value')\n@table_fields(choices=['key', 'details'])\n@flag(\"-a\", \"--all\", help=\"Show all the records for a given file\")\n@option(\"-i\", \"--index\", help=\"Index of the record to take into account.\"\n \" 1 is the most recent one.\", type=int)\ndef show(format, all, fields, index):\n \"\"\"Show the git records\n\n The first value is the path where the file/directory should be located. Ths\n second value is the name of the file in the git store. Since git is content\n addressable, a same git store name indicates a same content.\n\n \"\"\"\n if index and all:\n raise click.UsageError(\"--index and --all are mutually exclusives\")\n\n index = index or 1\n locally_avail_names = {\n r[1]\n for r in get_refs()\n }\n\n def format_records(records):\n def format_record(record):\n res = record[\"name\"]\n if \"documentation\" in record and record[\"documentation\"]:\n res += \" '{}'\".format(record[\"documentation\"])\n if record[\"name\"] in locally_avail_names:\n res += \" (in here)\"\n else:\n res += \" (not in here)\"\n if \"date\" in record:\n res += \" (Recorded at {})\".format(dateutil.parser.parse(record[\"date\"]))\n return res\n\n top = records[-index]\n res = format_record(top)\n if len(records) > 1:\n res += \" ({}/{})\".format(index, len(records))\n if all and len(records) > 1:\n res += \". Other records: {}\".format(\n \", \".join(\n \"{}: {}\".format(index_ + 1, format_record(record))\n for index_, record in enumerate(reversed(records[:-1]))\n )\n )\n return res\n\n with TablePrinter(fields, format) as tp:\n for key in sorted(config.git_record.readonly.keys()):\n tp.echo(key, format_records(config.git_record.readonly[key]))\n\n\n@git_record.command()\n@option(\"-m\", \"--message\", help=\"Message to describe the record\")\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\n@option(\"-i\", \"--index\", help=\"Index of the record to take into account.\"\n \" 1 is the most recent one.\", type=int, default=1)\ndef set_documentation(file, message, index):\n \"\"\"Set the documentation of the given file\"\"\"\n # starting from the end, the index starts at 1\n file = set(file or config.git_record.writable.keys())\n assert_indices(file, index)\n assert_file_in_level(file)\n for fil in file:\n record = config.git_record.writable[fil][-index]\n if message:\n documentation = message\n else:\n documentation = click.prompt(\"Message\")\n record[\"documentation\"] = documentation\n config.git_record.write()\n\n\n@git_record.command()\n@option(\"-t\", \"--to\", \"remote\", default=current_remote, type=GitRemoteType(),\n help=\"The remote to upload to\")\n@flag(\"--force\", help=\"Force transferring the file even if it looks useless\")\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\n@pass_context\ndef _upload(ctx, file, remote, force):\n \"\"\"Upload the files/directorie\n\n So that anyone can download them.\n\"\"\"\n file = set(file or config.git_record.readonly.keys())\n remote_names = {\n r[1]\n for r in get_refs(remote)\n }\n local_names = {\n config.git_record.readonly[fil][-1][\"name\"]\n for fil in file\n }\n locally_avail_names = {\n r[1]\n for r in get_refs()\n }\n names = local_names.copy()\n for name in local_names - locally_avail_names:\n local_file = {\n fil\n for fil in file\n if config.git_record.readonly[fil][-1][\"name\"] == name\n }\n names.remove(name)\n for fil in local_file:\n file.remove(fil)\n LOGGER.error(\n \"{} is not there\"\n \" because the git file {} is not available.\"\n \" It won't be uploaded to {}\".format(\n fil,\n name,\n remote,\n ))\n local_names = names.copy()\n if not force:\n for name in local_names & remote_names:\n local_file = {\n fil\n for fil in file\n if config.git_record.readonly[fil][-1][\"name\"] == name\n }\n names.remove(name)\n for fil in local_file:\n file.remove(fil)\n LOGGER.info(\n \"{} is already in\"\n \" {} because the git file {} is already there\"\n \" (use --force to still upload)\".format(\n fil,\n remote,\n name,\n ))\n if file:\n ctx.invoke(\n git_store_push,\n remote=remote,\n name=[\"refs/git-store/\" + name for name in names],\n )\n LOGGER.status(\"Uploaded {}\".format(\n \", \".join(file)\n ))\n\n\n@git_record.command()\n@option(\"-f\", \"--from\", \"remote\", default=current_remote, type=GitRemoteType(),\n help=\"The remote to download from\")\n@flag(\"--force\", help=\"Force transferring the file even if it looks useless\")\n@argument('file', nargs=-1, type=CommandSettingsKeyType(\"git_record\"))\n@pass_context\ndef download(ctx, file, remote, force):\n \"\"\"Download the files/directories\n\n This command is generally not needed, since the restore command implies\n downloading.\n\n \"\"\"\n file = set(file or config.git_record.readonly.keys())\n remote_names = {\n r[1]\n for r in get_refs(remote)\n }\n local_names = {\n config.git_record.readonly[fil][-1][\"name\"]\n for fil in file\n }\n locally_avail_names = {\n r[1]\n for r in get_refs()\n }\n names = local_names.copy()\n if not force:\n for name in local_names & locally_avail_names:\n local_file = {\n fil\n for fil in file\n if config.git_record.readonly[fil][-1][\"name\"] == name\n }\n names.remove(name)\n for fil in local_file:\n file.remove(fil)\n LOGGER.info(\n \"{} is already there\"\n \" because the git file {} is available\"\n \" (use --force to still download it)\".format(\n fil,\n name,\n ))\n local_names = names.copy()\n for name in local_names - remote_names:\n local_file = {\n fil\n for fil in file\n if config.git_record.readonly[fil][-1][\"name\"] == name\n }\n names.remove(name)\n for fil in local_file:\n file.remove(fil)\n LOGGER.error(\n \"{} is not available in\"\n \" {} because the git file {} is missing\".format(\n fil,\n remote,\n name,\n ))\n if file:\n ctx.invoke(\n git_store_fetch,\n remote=remote,\n name=[\"refs/git-store/\" + name for name in names],\n )\n LOGGER.status(\"Downloaded {}\".format(\n \", \".join(file)\n ))\n\n\n@git_record.command()\ndef generate_scripts():\n \"\"\"Generate scripts to reset and update a git record without using git-record\n\n It create two file, git-record_save.py and git-record_reset.py in the\n current directory. Those files are pure standalone python programs that yàu\n can commit to record files in git without using git-record.\n\n The script git-record_save.py saves/updates a file/directory (given as\n parameter) in git and records its hash into a hash file with the same name\n and ending with \".hash\".\n\n You need to commit the hash file only. People can retrieve the file by\n running the script git-records_reset.py with the hash file as parameter.\n\n Those scripts give you the freedom to use a feature close enough to\n git-record without forcing you and your team to use git-record.\n\n \"\"\"\n dir = os.path.dirname(os.path.abspath(__file__))\n dst = os.getcwd()\n for file in [\"git-record_reset.py\", \"git-record_save.py\"]:\n copy(os.path.join(dir, file), dst)\n click.echo(\"To add/update a data dir/file FOO, run 'python git-record_save.py FOO'\")\n click.echo(\"To restore a data dir/file FOO, run 'python git-record_reset.py FOO'\")\n\n\n@git_record.command()\n@argument(\"file\", nargs=-1)\n@pass_context\ndef hash_restore(ctx, file):\n \"\"\"For each file, restore it using its hash file\n\n One of the two commands used to collaborate with people not using git-record,\n but still store files in git.\n\n This commands restores a file from git, reading its hash from a hash file\n with the same name and ending with \".hash\".\n\n This file must have been stored by issuing the commend `git-store\n hash-save FILE`.\n\n To collaborate with users that don't want to use git-record, generate the\n git helpers scripts with `git-record generate-scripts`, commit them and say\n to your friends to run `python git-record_update.py FILE` to save file so\n that you can retrieve them.\n\n The file name or the hash file name can be given\n\n \"\"\"\n for fil in file:\n if fil.endswith(\".hash\"):\n fil = fil[:-len(\".hash\")]\n full = os.path.abspath(fil)\n basename = os.path.basename(full)\n hash_file = os.path.join(\n os.path.dirname(full),\n basename + \".hash\"\n )\n ref = open(hash_file, \"rb\").read().decode(\"utf-8\")\n ctx.invoke(restore, file=fil, name=ref)\n\n\n@git_record.command()\n@argument(\"file\", nargs=-1)\n@flag(\"--force\", help=(\n \"Force the insertion of the file in git,\"\n \" even though a file with the same name already exists.\"\n \" Use this only if you understand what it does.\"\n))\n@pass_context\ndef hash_save(ctx, file, force):\n \"\"\"For each file, save it using its hash file\n\n One of the two commands used to collaborate with people not using git-record,\n but still store files in git.\n\n This commands saves a file in git and records its hash into a hash file with\n the same name and ending with \".hash\".\n\n This file can be retrieved by issuing the commend `git-store\n hash-restore FILE`.\n\n To collaborate with people not using git-record, generate the git helpers scripts with\n `git-record generate-scripts`, commit them and say to your friends to\n run `python git-record_reset.py FILE`\n\n The file name or the hash file name can be given\n\n \"\"\"\n for fil in file:\n if fil.endswith(\".hash\"):\n fil = fil[:-len(\".hash\")]\n full = os.path.abspath(fil)\n basename = os.path.basename(full)\n hash_file = os.path.join(\n os.path.dirname(full),\n basename + \".hash\"\n )\n name = _save(name=None, file=fil, force=force)\n ref = \"refs/git-store/\" + name\n open(hash_file, \"wb\").write(ref.encode(\"utf-8\"))\n", "sub_path": "click_project/commands/git_record/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 19806, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "click_project.log.get_logger", "line_number": 22, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 31, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 31, "usage_type": "name"}, {"api_name": "click.UsageError", "line_number": 32, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 34, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 34, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 41, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 41, "usage_type": "name"}, {"api_name": "click.UsageError", "line_number": 43, "usage_type": "call"}, {"api_name": "click_project.config.config.require_project", "line_number": 92, "usage_type": "call"}, {"api_name": "click_project.config.config", "line_number": 92, "usage_type": "name"}, {"api_name": "click_project.decorators.group", "line_number": 49, "usage_type": "call"}, {"api_name": "click_project.decorators.use_settings", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path", "line_number": 121, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "click_project.config.config.project", "line_number": 122, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 122, "usage_type": "name"}, {"api_name": "click_project.commands.git_store._save", "line_number": 123, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.writable.get", "line_number": 124, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 124, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 124, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 130, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 130, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.write", "line_number": 131, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 131, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 131, "usage_type": "name"}, {"api_name": "click_project.decorators.argument", "line_number": 96, "usage_type": "call"}, {"api_name": "click_project.decorators.option", "line_number": 97, "usage_type": "call"}, {"api_name": "click_project.decorators.option", "line_number": 102, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 103, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 106, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 110, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 147, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 147, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.write", "line_number": 149, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 149, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 149, "usage_type": "name"}, {"api_name": "click_project.decorators.argument", "line_number": 138, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 138, "usage_type": "call"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 161, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.readonly.values", "line_number": 164, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 164, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 164, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.remove", "line_number": 167, "usage_type": "argument"}, {"api_name": "click_project.decorators.pass_context", "line_number": 153, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.writable.keys", "line_number": 178, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 178, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 178, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.writable.items", "line_number": 182, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 182, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 182, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 185, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 185, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.write", "line_number": 186, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 186, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 186, "usage_type": "name"}, {"api_name": "click_project.decorators.argument", "line_number": 171, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 171, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 172, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.readonly.keys", "line_number": 203, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 203, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 203, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 204, "usage_type": "call"}, {"api_name": "os.path", "line_number": 204, "usage_type": "attribute"}, {"api_name": "click_project.config.config.project", "line_number": 204, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 204, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path", "line_number": 205, "usage_type": "attribute"}, {"api_name": "click_project.lib.rm", "line_number": 207, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.readonly.keys", "line_number": 222, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 222, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 222, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 225, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 225, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "click_project.config.config.project", "line_number": 226, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 226, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.restore", "line_number": 228, "usage_type": "argument"}, {"api_name": "click_project.decorators.option", "line_number": 211, "usage_type": "call"}, {"api_name": "click_project.commands.git_store.current_remote", "line_number": 211, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.GitRemoteType", "line_number": 211, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 213, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 213, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 214, "usage_type": "name"}, {"api_name": "click.UsageError", "line_number": 238, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 242, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 242, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 245, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 245, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.write", "line_number": 246, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 246, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 246, "usage_type": "name"}, {"api_name": "click_project.decorators.option", "line_number": 232, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 234, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 234, "usage_type": "call"}, {"api_name": "click.UsageError", "line_number": 264, "usage_type": "call"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 269, "usage_type": "call"}, {"api_name": "dateutil.parser.parser.parse", "line_number": 282, "usage_type": "call"}, {"api_name": "dateutil.parser.parser", "line_number": 282, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 282, "usage_type": "name"}, {"api_name": "click_project.lib.TablePrinter", "line_number": 298, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.readonly.keys", "line_number": 299, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 299, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 299, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 300, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 300, "usage_type": "name"}, {"api_name": "click_project.decorators.table_format", "line_number": 250, "usage_type": "call"}, {"api_name": "click_project.decorators.table_fields", "line_number": 251, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 252, "usage_type": "call"}, {"api_name": "click_project.decorators.option", "line_number": 253, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.writable.keys", "line_number": 311, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 311, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 311, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 315, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 315, "usage_type": "name"}, {"api_name": "click.prompt", "line_number": 319, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.write", "line_number": 321, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 321, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 321, "usage_type": "name"}, {"api_name": "click_project.decorators.option", "line_number": 304, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 305, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 305, "usage_type": "call"}, {"api_name": "click_project.decorators.option", "line_number": 306, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record.readonly.keys", "line_number": 335, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 335, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 335, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 338, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 341, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 341, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 346, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 353, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 353, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 372, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 372, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.push", "line_number": 387, "usage_type": "argument"}, {"api_name": "click_project.decorators.option", "line_number": 325, "usage_type": "call"}, {"api_name": "click_project.commands.git_store.current_remote", "line_number": 325, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.GitRemoteType", "line_number": 325, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 327, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 328, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 328, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 329, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record.readonly.keys", "line_number": 409, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 409, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 409, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 412, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 415, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 415, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.get_refs", "line_number": 420, "usage_type": "call"}, {"api_name": "click_project.config.config.git_record", "line_number": 428, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 428, "usage_type": "name"}, {"api_name": "click_project.config.config.git_record", "line_number": 445, "usage_type": "attribute"}, {"api_name": "click_project.config.config", "line_number": 445, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.fetch", "line_number": 459, "usage_type": "argument"}, {"api_name": "click_project.decorators.option", "line_number": 397, "usage_type": "call"}, {"api_name": "click_project.commands.git_store.current_remote", "line_number": 397, "usage_type": "name"}, {"api_name": "click_project.commands.git_store.GitRemoteType", "line_number": 397, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 399, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 400, "usage_type": "call"}, {"api_name": "click_project.overloads.CommandSettingsKeyType", "line_number": 400, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 401, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 487, "usage_type": "call"}, {"api_name": "os.path", "line_number": 487, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 487, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 488, "usage_type": "call"}, {"api_name": "click_project.lib.copy", "line_number": 490, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 490, "usage_type": "call"}, {"api_name": "os.path", "line_number": 490, "usage_type": "attribute"}, {"api_name": "click.echo", "line_number": 491, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 492, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 521, "usage_type": "call"}, {"api_name": "os.path", "line_number": 521, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 522, "usage_type": "call"}, {"api_name": "os.path", "line_number": 522, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 523, "usage_type": "call"}, {"api_name": "os.path", "line_number": 523, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 524, "usage_type": "call"}, {"api_name": "os.path", "line_number": 524, "usage_type": "attribute"}, {"api_name": "click_project.commands.git_store.restore", "line_number": 528, "usage_type": "argument"}, {"api_name": "click_project.decorators.argument", "line_number": 496, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 497, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 561, "usage_type": "call"}, {"api_name": "os.path", "line_number": 561, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 562, "usage_type": "call"}, {"api_name": "os.path", "line_number": 562, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 563, "usage_type": "call"}, {"api_name": "os.path", "line_number": 563, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 564, "usage_type": "call"}, {"api_name": "os.path", "line_number": 564, "usage_type": "attribute"}, {"api_name": "click_project.commands.git_store._save", "line_number": 567, "usage_type": "call"}, {"api_name": "click_project.decorators.argument", "line_number": 532, "usage_type": "call"}, {"api_name": "click_project.decorators.flag", "line_number": 533, "usage_type": "call"}, {"api_name": "click_project.decorators.pass_context", "line_number": 538, "usage_type": "name"}]} +{"seq_id": "104803659", "text": "\"\"\"\nUse: python total-household-subset-technical-validation.py \n\"\"\"\n\n# python\nimport datetime\nfrom typing import List, Tuple, Union\nimport glob\nimport os\nfrom os.path import join, exists\nfrom os import makedirs\nfrom datetime import datetime, timedelta\nfrom dateutil import relativedelta\nimport sys\nimport logging\n\n# data-science\nimport pandas as pd\nimport numpy as np\nimport dask as dk\nimport dask.dataframe as dd\nfrom dask.system import CPU_COUNT\nfrom dask.distributed import Client, LocalCluster\n\nprint(\"Pandas version {}\".format(pd.__version__), flush=True)\n\n\nBASE_DATA_SOURCE = sys.argv[1] if sys.argv[1] else exit()\nRESULTS_DEST = sys.argv[2] if sys.argv[2] else exit()\n\n# If destination directory does not exist, create it\nif not exists(RESULTS_DEST):\n makedirs(RESULTS_DEST)\n\n\nif __name__ == \"__main__\":\n\n # READ: https://stackoverflow.com/a/47776937/1674908\n pd.options.mode.chained_assignment = None\n\n print(\"Generating Dask Client...\", flush=True)\n client = Client(\n # address=\"localhost:8786\",\n # direct_to_workers=True,\n processes=True,\n # n_workers=int(CPU_COUNT/1.5)+1,\n silence_logs=logging.ERROR,\n local_directory=f\"/scratch/{os.environ.get('SLURM_JOB_USER')}/{os.environ.get('SLURM_JOBID')}\"\n )\n # READ: https://github.com/dask/dask/issues/4001#issuecomment-647463811\n dk.config.set({\"optimization.fuse.ave-width\": 20})\n\n # dk.config.set(scheduler='threads')\n\n print(\"Number of CPUs detected: {}\".format(CPU_COUNT), flush=True)\n # Load consumption data\n df_consum = dd.read_parquet(\n BASE_DATA_SOURCE + '/consum-parquet',\n )\n\n # print(df_consum.head(npartitions=1), flush=True)\n # percentile = df_consum[[\"value\"]][df_consum.value > 0].quantile(\n # [.8, .9, .95, .975, .98, .985, .99, .995, 1]\n # ).compute()\n # print(percentile)\n\n # df_consum = df_consum[df_consum.value <= percentile[0.985]]\n df_consum = df_consum[df_consum.value <= 1.13] # result of percentile calculated before\n\n df_consum_date_count = df_consum.groupby(\n [df_consum.id, df_consum.datetime.dt.date],\n observed=True,\n ).value.count().reset_index()\n\n df_consum_date_count.to_parquet(\n RESULTS_DEST + \"/consumption_date_count-parquet\",\n engine='pyarrow',\n compression='snappy',\n write_index=False\n )\n df_consum_date_count.compute().to_csv(\n RESULTS_DEST + \"/consumption_date_count.csv\",\n sep=\",\",\n header=True,\n index=False,\n float_format=\"%.3f\",\n )\n\n print(\"Building query to calculate 15-min mean consumption with consum-filter-95...\", flush=True)\n df_consum_15min = df_consum[[\"datetime\", \"value\"]].set_index(\n \"datetime\"\n ).resample(\"15min\").mean()\n # print(\"Executing the query...\", flush=True)\n df_consum_15min_mean = df_consum_15min[[\"value\"]].groupby(\n [df_consum_15min.index.hour, df_consum_15min.index.minute],\n observed=True,\n ).mean()\n\n print(\"Building query to calculate weekday mean consumption with consum-filter-95...\", flush=True)\n df_consum_weekday = df_consum[[\"datetime\", \"value\"]].groupby(\n [df_consum.datetime.dt.weekday],\n observed=True,\n ).mean()\n\n # print(df_consum_15min_mean.head())\n print(\"Computing consumption 15-min...\", flush=True)\n df_consum_15min_mean.compute().to_csv(\n RESULTS_DEST + \"/consumption_15min_mean.csv\",\n sep=\",\",\n header=True,\n index=True,\n float_format=\"%.3f\",\n )\n\n # print(df_consum_weekday.head())\n print(\"Computing consumption weekday...\", flush=True)\n df_consum_weekday.compute().to_csv(\n RESULTS_DEST + \"/consumption_weekday_mean.csv\",\n sep=\",\",\n header=True,\n index=True,\n float_format=\"%.3f\",\n )\n\n print(\"FIN.\")\n", "sub_path": "technical-validation-total-househould-subset.py", "file_name": "technical-validation-total-househould-subset.py", "file_ext": "py", "file_size_in_byte": 3858, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.__version__", "line_number": 25, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 28, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 32, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.options", "line_number": 39, "usage_type": "attribute"}, {"api_name": "dask.distributed.Client", "line_number": 42, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 48, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 48, "usage_type": "attribute"}, {"api_name": "dask.config.set", "line_number": 51, "usage_type": "call"}, {"api_name": "dask.config", "line_number": 51, "usage_type": "attribute"}, {"api_name": "dask.system.CPU_COUNT", "line_number": 55, "usage_type": "argument"}, {"api_name": "dask.dataframe.read_parquet", "line_number": 57, "usage_type": "call"}, {"api_name": "dask.dataframe", "line_number": 57, "usage_type": "name"}]} +{"seq_id": "533189450", "text": "\n# -*- coding: utf-8 -*-\nfrom config import db\n\n\nclass ItemIndustry(db.Model):\n __tablename__ = \"data_item_industry\"\n\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n item_id = db.Column(db.Integer)\n industry_id = db.Column(db.Integer)\n\n def __init__(self,item_id,industry_id):\n '''Constructor'''\n self.item_id=item_id\n self.industry_id=industry_id\n\n\n def __repr__(self):\n return 'id : %s' % self.id\n\n\n# Client and database attributes dictionary\nclinetHead = {u'id', u'itemId', u'industryId'}\ntableChangeDic = {\n \"id\":\"id\",\n \"itemId\":\"item_id\",\n \"industryId\":\"industry_id\"\n}\n\nintList = {u'id', u'itemId', u'industryId'}\n\n# db.create_all()\n", "sub_path": "boss_service/models/Data/ItemIndustry.py", "file_name": "ItemIndustry.py", "file_ext": "py", "file_size_in_byte": 708, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "config.db.Model", "line_number": 6, "usage_type": "attribute"}, {"api_name": "config.db", "line_number": 6, "usage_type": "name"}, {"api_name": "config.db.Column", "line_number": 9, "usage_type": "call"}, {"api_name": "config.db", "line_number": 9, "usage_type": "name"}, {"api_name": "config.db.Integer", "line_number": 9, "usage_type": "attribute"}, {"api_name": "config.db.Column", "line_number": 10, "usage_type": "call"}, {"api_name": "config.db", "line_number": 10, "usage_type": "name"}, {"api_name": "config.db.Integer", "line_number": 10, "usage_type": "attribute"}, {"api_name": "config.db.Column", "line_number": 11, "usage_type": "call"}, {"api_name": "config.db", "line_number": 11, "usage_type": "name"}, {"api_name": "config.db.Integer", "line_number": 11, "usage_type": "attribute"}]} +{"seq_id": "179025789", "text": "from django.contrib import admin\r\nfrom django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('', views.home, name='home'),\r\n # path('about-us', views.home, name='about'),\r\n # path('contact-us', views.contact, name='contact'),\r\n # path('search', views.search, name='search'),\r\n path('courses', views.courses, name='courses'),\r\n path('courses/', views.subject_courses, name='subjectcourses'),\r\n path('courses//', views.studyMaterials, name='study-materials'),\r\n path('courses///', views.studyMaterialsWithVideos, name='study-materials-w-videos'),\r\n path('enrollment/', views.enroll_anonymous, name='enroll_anonymous'),\r\n path('enrollment/', views.enrollment, name='enrollment'),\r\n path('enrollmentCheckout////', views.enrollmentCheckout, name='enrollmentCheckout'),\r\n path('enrollmentCheckoutFail', views.enrollmentCheckoustFail, name='enrollmentCheckoutFail'),\r\n path('enrollmentConfirmation', views.enrollmentConfirmation, name='enrollmentConfirmation'),\r\n path('enrollmentCancel', views.enrollmentCheckoutCancelled, name='enrollmentCancelled'),\r\n path('quiz////', views.quizIndiv, name='quizIndiv'),\r\n path('quizIntro////', views.quizIntro, name='quizIndiv'),\r\n path('quiz//', views.quizAll, name='quiz'),\r\n path('quiz//', views.quiznotLogged, name='quizNotLogged'),\r\n path('answer-validate', views.quizAll, name='quiz'),\r\n path('comment////', views.comment, name='comment'),\r\n path('newsletter', views.newsletter, name='newsletter'),\r\n path('other-services/cvBuilder', views.cvBuilder, name='cvBuilder'),\r\n path('other-services/cvBuilderIntro', views.cvIntro, name='cvBuilderIntro'),\r\n path('search/study-materials-subs', views.searchStudyMaterialsSubs, name='searchStudyMaterialsSubs'),\r\n path('search/quizzes', views.searchQuizzes, name='searchQuizzes'),\r\n\r\n # path('search/study-materials', views.searchStudyMaterials, name='searchStudyMaterials'),\r\n # path('reply-comment/////', views.replyComment, name='comment')\r\n\r\n \r\n\r\n # path('administrative', views.search, name='administrative'),\r\n # path('admission', views.search, name='admission'),\r\n # path('instructors', views.search, name='instructors'),\r\n # path('exam', views.search, name='exam'),\r\n\r\n]\r\n", "sub_path": "home/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2640, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "614585545", "text": "#!/user/bin/env python3\n'''\nCreate 05172019\n\n@author: meng2\n'''\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport pickle\nimport time\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport argparse\n\nfrom TCLGP import *\n\n### Parallel Library\nfrom mpi4py import MPI\n\nif __name__ == \"__main__\":\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n parser=argparse.ArgumentParser()\n parser.add_argument(\"--M\", help=\"number of inducing points\", type=int, default=20)\n parser.add_argument(\"--Q\", help=\"latent dimension size\", type=int, default=5)\n parser.add_argument(\"--MC_T\", help=\"Monte Carlo size\", type=int, default=5)\n parser.add_argument(\"--method\", help=\"methods: Adam, RSM, Adagrad\", type=str, default='Adam')\n parser.add_argument(\"--dataset\", help=\"name of dataset\", type=str, default='sim_Markov_test_train')\n parser.add_argument(\"--reg\", help=\"regularization\", type=float, default=0.)\n parser.add_argument(\"--nugget\", help=\"nugget effects in GPs\", action='store_true')\n parser.add_argument(\"--training_epochs\", help=\"number of training epochs\", type=int, default=2000)\n parser.add_argument(\"--learning_rate\", help=\"learning rate\", type=float, default=0.1)\n parser.add_argument(\"--lower_bound\", help=\"lower_bound of length scale in GP across time\", type=float, default=0)\n parser.add_argument(\"--upper_bound\", help=\"upper_bound of variance of nugget effects\", type=float, default=0)\n parser.set_defaults(nugget=False)\n args=parser.parse_args()\n\n try:\n os.chdir(os.path.dirname(__file__))\n except:\n pass\n\n # Load data\n with open('../data/'+args.dataset+'.dat', 'rb') as f:\n data_raw = pickle.load(f)\n T_train, T_test, Y_train, Y_test = data_raw\n ## T_train: N x T_train\n ## T_test: N\n ## Y_train: N x D x T_train\n ## Y_test: N x D \n # Reset shape \n Y_train = np.transpose(Y_train, axes = (0,2,1))\n N, T_max, D = Y_train.shape\n T_train = T_train.astype(np.float32)\n T_num_train = (np.ones(N)*T_max).astype(int)\n print(Y_train.shape, T_train.shape, T_num_train.shape)\n print(type(Y_train), type(T_train), type(T_num_train))\n K = [2,3]\n\n # Train data\n clgp_t = CLGP_T(M=args.M, Q=args.Q, MC_T=args.MC_T, reg=args.reg, nugget=args.nugget, error=1e-5, method=args.method, learning_rate=args.learning_rate, lower_bound=args.lower_bound, upper_bound=args.upper_bound)\n clgp_t.fit(Y_train, T_train, T_num_train, lamb = 0.001, learning_rate=args.learning_rate, training_epochs = args.training_epochs, method=args.method, verbose=False)\n\n # # predict training data\n # print(\"predict training data\")\n # clgp_t.predict_categorical(clgp_t.est_m[:,-1,:])\n # # print(\"predicted result:{}\".format(clgp_t.est_y_test))\n # # print(\"true result:{}\".format(Y_train[:,-1,:]))\n # print(\"accuracy:{}\".format(np.mean(clgp_t.est_y_test==Y_train[:,-1,:])))\n \n\n\n\n # # predict test data\n # print(\"predict testing data\")\n # clgp_t.predict_latent(T_test)\n # clgp_t.predict_categorical()\n # # print(\"predicted result:{}\".format(clgp_t.est_y_test))\n # # print(\"true result:{}\".format(Y_test))\n # pred_acc = np.mean(clgp_t.est_y_test==Y_test)\n # print(\"accuracy:{}\".format(pred_acc))\n \n # pred_acc_list = comm.gather(pred_acc, root=0)\n # if rank == 0:\n \t# np.savetxt(\"../res/pred_acc_LAM{}_Q{}\".format(args.reg, args.Q), np.asarray(pred_acc_list))\n\n\n\n\n # predict individual 0 latent process\n # clgp_t.predict_latent_process(0, verbose=True)\n \n\n\n\n\n # plot latent space\n est_l = clgp_t.est_theta[:,1:]\n sens = 1./est_l\n ## the large est_l denote the little variation in the dimension\n sens_order = [np.argsort(sens[d,:]) for d in range(D)]\n print(sens_order)\n\n IPs = clgp_t.est_Z\n ms = clgp_t.est_m\n ms_2 = ms.reshape([-1, args.Q])\n labels = Y_train.reshape([-1, D])\n labels = (labels[:,0] * K[1] + labels[:, 1]).reshape(-1)\n # print(ms_2.shape, labels.shape)\n colors = cm.rainbow(np.linspace(0,1,K[0]*K[1]))\n for d in range(D):\n fig = plt.figure()\n for i, c in zip(np.unique(labels), colors):\n plt.scatter(ms_2[labels==i,sens_order[d][-1]], ms_2[labels==i,sens_order[d][-2]], color = c, label = \"{},{}\".format(int(i/3),i%3))\n plt.scatter(IPs[:,sens_order[d][-1]], IPs[:,sens_order[d][-2]], marker='x', label = \"PI\")\n plt.xlim(-5,5)\n plt.ylim(-5,5)\n # plt.legend() \n plt.savefig(\"../res/latent_space_SIM_LAM{}_D{}.png\".format(args.reg, d))\n plt.close(fig)\n with open(\"../res/latent_space_SIM_LAM{}_D{}.pickle\".format(args.reg, d), \"wb\") as res:\n pickle.dump([ms_2, IPs, labels, colors, sens_order], res)\n\n\n ", "sub_path": "CLGP_T/src/CLGP_T_SIM.py", "file_name": "CLGP_T_SIM.py", "file_ext": "py", "file_size_in_byte": 4814, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.use", "line_number": 14, "usage_type": "call"}, {"api_name": "mpi4py.MPI.COMM_WORLD", "line_number": 25, "usage_type": "attribute"}, {"api_name": "mpi4py.MPI", "line_number": 25, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 29, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.cm.rainbow", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.cm", "line_number": 116, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 128, "usage_type": "call"}]} +{"seq_id": "279297815", "text": "###############################################################################\n# Name: test_network.py. #\n# Author gcordier #\n# Version 1.0.0 #\n# Indent: = 4 spaces (no tab). #\n# Width: 79 (comment lines < 73). #\n# license: Nope; consider the below code as public domain. #\n###############################################################################\n\nimport unittest\nimport io\nimport sys\nimport inspect\n\nfrom constants import *\nfrom network import *\nfrom factory import *\nfrom test import *\nfrom functools import partial\n\n# TODO: Is there some built-in function?\n\n\ndef is_equipotent(seq: list, teq: list) -> bool:\n \"\"\"\n Input: Two sequences, seq and teq.\n Output: True if and only if a permutation turns seq into teq.\n \"\"\"\n # Uncomment for debugging:\n # print(seq)\n # print(teq)\n if len(seq) != len(teq):\n return False\n else:\n for s in seq:\n found = False\n for t in teq:\n if s == t:\n found = True\n break\n if found is False:\n return False\n return True\n\n\n#Success\n#input_test = \"AE7, AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7\"\n#Fail\ninput_test = \"AE7, AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE77\"\n\n\n\n\ndef is_the_same_network(network_a, network_b):\n a = Network.to_string_list(network_a.to_string(NORM), SEPARATOR, NORM)\n b = Network.to_string_list(network_b.to_string(NORM), SEPARATOR, NORM)\n return set(a) == set(b)\n\n\nclass TestFactory(unittest.TestCase):\n\n def setUp(self):\n # We equip instances of Node or Network with 'print' methods.\n setattr(Node, \"print_child_\", print_child_)\n setattr(Node, \"print\", print_node)\n setattr(Network, \"print\", print_network)\n self.input_test_A = INPUT\n self.input_test_B = input_test\n\n self.network_test_A = Network.create_network(self.input_test_A)\n self.network_test_B = Network.create_network(self.input_test_B)\n self.network_test_A.name = NETWORK_NAME + \"_test_\" + \"A\"\n self.network_test_B.name = NETWORK_NAME + \"_test_\" + \"B\"\n\n self.network_test_A.from_input = Network.get_normalized_string(self.input_test_A, SEPARATOR, NORM)\n self.network_test_B.from_input = Network.get_normalized_string(self.input_test_B,SEPARATOR, NORM)\n\n def test_print(self):\n self.capture_string(self.input_test_A)\n self.capture_string(self.input_test_B)\n\n if Network.to_string_list(self.input_test_A, SEPARATOR, NORM) == \\\n Network.to_string_list(self.input_test_B, SEPARATOR, NORM):\n print(\"They encode the same network.\")\n else:\n print(\"They do not encode the same network.\")\n \n self.capture_network(self.network_test_A)\n self.capture_network(self.network_test_B)\n \n self.capture_network_to_string(self.network_test_A)\n self.capture_network_to_string(self.network_test_B)\n\n self.capture_encoded_networks(self.network_test_A, self.network_test_B)\n \n @staticmethod\n def capture_string(string):\n captured_output = io.StringIO()\n sys.stdout = captured_output\n print(line(INDENT, string))\n sys.stdout = sys.__stdout__\n method = inspect.currentframe().f_code.co_name\n log = Log.captured_object(string, print)\n print(log, captured_output.getvalue())\n #\n\n def capture_network(self, network):\n captured_output = io.StringIO()\n sys.stdout = captured_output\n self.print = partial(network.print, INDENT)\n self.print()\n sys.stdout = sys.__stdout__\n method = inspect.currentframe().f_code.co_name\n log = Log.captured_object(network, method)\n print(log, captured_output.getvalue())\n #\n\n def capture_network_to_string(self, network):\n captured_output = io.StringIO()\n sys.stdout = captured_output\n network.encoded = network.to_string(NORM)\n #\n print(network.to_string.__name__ +\" of \" + network.name + \" returned: \")\n print(network.encoded)\n #\"\n a = \"\\n Compare such normalized output with our normalized input \"\n b = \"(above: input, below: output)\"\n print(a + b)\n print(network.from_input)\n print(network.encoded)\n print(\"\\n\")\n print(\"They {} describe the same network.\".format(\"\" if\n Network.to_string_list(network.encoded, SEPARATOR, NORM) == \n Network.to_string_list(network.from_input, SEPARATOR, NORM) \n else \"do not\"\n )\n )\n sys.stdout = sys.__stdout__\n method = inspect.currentframe().f_code.co_name\n log = Log.captured_object(network, method)\n print(log, captured_output.getvalue())\n #\n\n def capture_encoded_networks(self, network_a, network_b):\n captured_output = io.StringIO()\n sys.stdout = captured_output\n print(self.compare_two_encoded_networks(network_a, network_b))\n sys.stdout = sys.__stdout__\n method = inspect.currentframe().f_code.co_name\n log_a = Log.captured_object(network_a, method)\n log_b = Log.captured_object(network_b, method)\n print(log_a, captured_output.getvalue())\n print(log_b, captured_output.getvalue())\n #\n\n def compare_two_encoded_networks(self, network_a, network_b):\n s = network_a.name + \" and \" + network_b.name\n t = \" {} encode the same network.\".format(\n \"\" if is_the_same_network(network_a, network_b) else \" do not\"\n )\n return s + t\n #\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "test_network.py", "file_name": "test_network.py", "file_ext": "py", "file_size_in_byte": 5967, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "unittest.TestCase", "line_number": 60, "usage_type": "attribute"}, {"api_name": "io.StringIO", "line_number": 98, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 99, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 101, "usage_type": "attribute"}, {"api_name": "sys.__stdout__", "line_number": 101, "usage_type": "attribute"}, {"api_name": "inspect.currentframe", "line_number": 102, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 108, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 109, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 110, "usage_type": "call"}, {"api_name": "network.print", "line_number": 110, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 112, "usage_type": "attribute"}, {"api_name": "sys.__stdout__", "line_number": 112, "usage_type": "attribute"}, {"api_name": "inspect.currentframe", "line_number": 113, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 119, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 120, "usage_type": "attribute"}, {"api_name": "network.encoded", "line_number": 121, "usage_type": "attribute"}, {"api_name": "network.to_string", "line_number": 121, "usage_type": "call"}, {"api_name": "network.to_string", "line_number": 123, "usage_type": "attribute"}, {"api_name": "network.name", "line_number": 123, "usage_type": "attribute"}, {"api_name": "network.encoded", "line_number": 124, "usage_type": "attribute"}, {"api_name": "network.from_input", "line_number": 129, "usage_type": "attribute"}, {"api_name": "network.encoded", "line_number": 130, "usage_type": "attribute"}, {"api_name": "network.encoded", "line_number": 133, "usage_type": "attribute"}, {"api_name": "network.from_input", "line_number": 134, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 138, "usage_type": "attribute"}, {"api_name": "sys.__stdout__", "line_number": 138, "usage_type": "attribute"}, {"api_name": "inspect.currentframe", "line_number": 139, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 145, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 146, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 148, "usage_type": "attribute"}, {"api_name": "sys.__stdout__", "line_number": 148, "usage_type": "attribute"}, {"api_name": "inspect.currentframe", "line_number": 149, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 165, "usage_type": "call"}]} +{"seq_id": "612779360", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport contextlib\nimport io\nimport os\n\nfrom click.testing import CliRunner\n\nimport pytest\nfrom prequ.scripts.update import main\n\n\n@pytest.yield_fixture\ndef pip_conf(tmpdir):\n pip_conf_file = 'pip.conf' if os.name != 'nt' else 'pip.ini'\n path = (tmpdir / pip_conf_file).strpath\n with open(path, 'w') as f:\n f.write(\n '[global]\\n'\n 'index-url = http://localhost\\n'\n 'trusted-host = localhost\\n')\n old_value = os.environ.get('PIP_CONFIG_FILE')\n try:\n os.environ['PIP_CONFIG_FILE'] = path\n yield path\n finally:\n if old_value is not None:\n os.environ['PIP_CONFIG_FILE'] = old_value\n else:\n del os.environ['PIP_CONFIG_FILE']\n os.remove(path)\n\n\n@contextlib.contextmanager\ndef run_check(pip_conf, options=None, requirements=None):\n assert os.path.exists(pip_conf)\n runner = CliRunner()\n with runner.isolated_filesystem():\n create_prerequirements(options, requirements)\n out = runner.invoke(main, ['-v'])\n yield out\n\n\ndef create_prerequirements(options=None, requirements=None):\n with io.open('requirements.pre', 'wt', encoding='utf-8') as fp:\n if options:\n fp.write('options:\\n')\n for (key, value) in options.items():\n fp.write(' {}: {}\\n'.format(key, value))\n fp.write('requirements:\\n')\n if not requirements:\n fp.write(' base: \"\"\\n')\n else:\n fp.write(' base: |')\n for req in requirements:\n fp.write(req + '\\n')\n\n\ndef test_default_pip_conf_read(pip_conf):\n with run_check(pip_conf) as out:\n assert 'Using indexes:\\n http://localhost' in out.output\n assert '--index-url http://localhost' in out.output\n\n\ndef test_extra_index_option(pip_conf):\n options = {\n 'extra_index_urls': (\n '[\"http://extraindex1.com\", \"http://extraindex2.com\"]')\n }\n with run_check(pip_conf, options) as out:\n assert ('--index-url http://localhost\\n'\n '--extra-index-url http://extraindex1.com\\n'\n '--extra-index-url http://extraindex2.com' in out.output)\n\n\ndef test_wheel_dir_option(pip_conf):\n with run_check(pip_conf, options={'wheel_dir': 'foo/bar'}) as out:\n assert '--find-links foo/bar\\n' in out.output\n\n\ndef test_trusted_host_option(pip_conf):\n options = {'trusted_hosts': '[\"example.com\", \"other.example.com\"]'}\n with run_check(pip_conf, options) as out:\n assert ('--trusted-host example.com\\n'\n '--trusted-host other.example.com\\n') in out.output\n\n\ndef test_invalid_option(pip_conf):\n options = {'invalid': 'foobar'}\n with run_check(pip_conf, options) as out:\n assert out.exit_code != 0\n assert type(out.exc_info[1]).__name__ == 'InvalidPreRequirements'\n assert '{}'.format(out.exc_info[1]) == (\n 'Errors in pre-requirement data:'\n ' Unknown key name: \"options.invalid\"')\n\n\ndef test_umlaut_in_pre_requirements_file(pip_conf):\n options = {'wheel_sources': '{\"mämmi\": \"http://localhost/mämmi\"}'}\n with run_check(pip_conf, options) as out:\n assert out.exit_code == 0\n", "sub_path": "tests/test_prequ_update.py", "file_name": "test_prequ_update.py", "file_ext": "py", "file_size_in_byte": 3253, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.name", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 24, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 33, "usage_type": "call"}, {"api_name": "pytest.yield_fixture", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "click.testing.CliRunner", "line_number": 39, "usage_type": "call"}, {"api_name": "prequ.scripts.update.main", "line_number": 42, "usage_type": "argument"}, {"api_name": "contextlib.contextmanager", "line_number": 36, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "357594725", "text": "from django.urls import path\n\nfrom articles.views import (\n ArticleCreateListView,\n ArticleRetriveListDeleteView,\n ArticleUpVoteView,\n ArticleDownVoteView,\n ArticleNeutralVoteView,\n AllArticleListView\n )\n\nurlpatterns = [\n path('api/article/', ArticleCreateListView.as_view(), name='article_create_list'),\n path('api/article/all/', AllArticleListView.as_view(), name='all_article_list'),\n path('api/article//', ArticleRetriveListDeleteView.as_view(), name='article_rud'),\n path('api/article//upvote/', ArticleUpVoteView.as_view(), name='article_upvote'),\n path('api/article//downvote/', ArticleDownVoteView.as_view(), name='article_downvote'),\n path('api/article//neutralvote/', ArticleNeutralVoteView.as_view(), name='article_neutralvote'),\n]", "sub_path": "articles/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 829, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "articles.views.ArticleCreateListView.as_view", "line_number": 13, "usage_type": "call"}, {"api_name": "articles.views.ArticleCreateListView", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "articles.views.AllArticleListView.as_view", "line_number": 14, "usage_type": "call"}, {"api_name": "articles.views.AllArticleListView", "line_number": 14, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "articles.views.ArticleRetriveListDeleteView.as_view", "line_number": 15, "usage_type": "call"}, {"api_name": "articles.views.ArticleRetriveListDeleteView", "line_number": 15, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "articles.views.ArticleUpVoteView.as_view", "line_number": 16, "usage_type": "call"}, {"api_name": "articles.views.ArticleUpVoteView", "line_number": 16, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "articles.views.ArticleDownVoteView.as_view", "line_number": 17, "usage_type": "call"}, {"api_name": "articles.views.ArticleDownVoteView", "line_number": 17, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "articles.views.ArticleNeutralVoteView.as_view", "line_number": 18, "usage_type": "call"}, {"api_name": "articles.views.ArticleNeutralVoteView", "line_number": 18, "usage_type": "name"}]} +{"seq_id": "153964225", "text": "#coding:utf-8\n\nimport manage\nfrom api import post\nfrom lxml import html\nimport requests\nfrom db.models import Parser\n\nURL = 'https://kyrtag.kg'\nGROUP_ID = '1184'\n\n\npage = requests.get(URL + '/kg')\ntree = html.fromstring(page.content)\nurl = tree.xpath('//ul[@class=\"news\"]//li[@class=\"item\"]//div[@class=\"right-col\"]//h2[@class=\"title\"]//a/@href')[0]\ntitle = tree.xpath('//h2[@class=\"title\"]//a[@href=\"'+ url +'\"]/text()')[0].strip()\n\nparse = Parser.objects.get(parse_site='KYRTAG')\n\nlast_parsed_url = parse.last_parsed_url\n\nif(url == last_parsed_url):\n print('Already parsed')\nelse:\n post(title, URL + url, GROUP_ID)\n parse.last_parsed_url = url\n parse.save()\n\n\n", "sub_path": "parsers/kyrtag.py", "file_name": "kyrtag.py", "file_ext": "py", "file_size_in_byte": 674, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 13, "usage_type": "call"}, {"api_name": "lxml.html.fromstring", "line_number": 14, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 14, "usage_type": "name"}, {"api_name": "db.models.Parser.objects.get", "line_number": 18, "usage_type": "call"}, {"api_name": "db.models.Parser.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "db.models.Parser", "line_number": 18, "usage_type": "name"}, {"api_name": "api.post", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "176886740", "text": "\"\"\"\nCompute the set of URLs which contains command lines that contains a specific\nutility.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport html\nimport pickle\nimport re\nimport sqlite3\nimport sys\nsys.path.append('../../')\n\nfrom bashlint import bash, data_tools\n\nCODE_REGEX = re.compile(r\"
([^<]+)<\\/code><\\/pre>\")\nNUM_COMMAND_THRESHOLD = 40\n\ndef extract_code(text):\n    for match in CODE_REGEX.findall(text):\n        if match.strip():\n            yield html.unescape(match.replace(\"
\", \"\\n\"))\n\ndef extract_oneliner_from_code(code_block):\n for cmd in code_block.splitlines():\n if cmd.startswith('$ '):\n cmd = cmd[2:]\n if cmd.startswith('# '):\n cmd = cmd[2:]\n comment = re.search(r'\\s+#\\s+', cmd)\n if comment:\n old_cmd = cmd\n cmd = cmd[:comment.start()]\n print('Remove comment: {} -> {}'.format(old_cmd, cmd))\n cmd = cmd.strip()\n\n # discard code block opening line\n if not cmd.endswith('{') and not cmd.endswith('[') and not cmd.endswith('('):\n yield cmd\n \ndef run():\n sqlite_filename = sys.argv[1]\n url_prefix = 'https://stackoverflow.com/questions/'\n\n urls = {}\n commands = {}\n\n with sqlite3.connect(sqlite_filename, detect_types=sqlite3.PARSE_DECLTYPES) as db:\n count = 0\n for post_id, answer_body in db.cursor().execute(\"\"\"\n SELECT questions.Id, answers.Body FROM questions, answers\n WHERE questions.Id = answers.ParentId\n ORDER BY questions.Score DESC\"\"\"):\n print(post_id)\n for code_block in extract_code(answer_body):\n for cmd in extract_oneliner_from_code(code_block):\n print('command string: {}'.format(cmd))\n ast = data_tools.bash_parser(cmd)\n if not ast:\n continue\n utilities = data_tools.get_utilities(ast)\n for utility in utilities:\n if utility in bash.top_100_utilities:\n print('extracted: {}, {}'.format(utility, cmd))\n temp = data_tools.ast2template(ast, loose_constraints=True)\n if not utility in commands:\n commands[utility] = {}\n commands[utility][temp] = cmd\n urls[utility] = {'{}{}'.format(url_prefix, post_id)}\n else:\n if len(commands[utility]) >= NUM_COMMAND_THRESHOLD:\n continue\n if not temp in commands[utility]:\n commands[utility][temp] = cmd\n urls[utility].add('{}{}'.format(url_prefix, post_id))\n count += 1\n if count % 1000 == 0:\n completed = False\n for utility in bash.top_100_utilities:\n if not utility in commands or len(commands[utility]) < NUM_COMMAND_THRESHOLD:\n completed = False\n else:\n print('{} collection done.'.format(utility))\n\n if completed:\n break\n\n with open('stackoverflow.urls', 'wb') as o_f:\n pickle.dump(urls, o_f)\n with open('stackoverflow.commands', 'wb') as o_f:\n pickle.dump(commands, o_f)\n\n for utility in commands:\n print('{} ({})'.format(utility, len(commands[utility])))\n for cmd in commands[utility]:\n print(cmd)\n\nif __name__ == \"__main__\":\n run()\n", "sub_path": "data/stackoverflow/collect_urls.py", "file_name": "collect_urls.py", "file_ext": "py", "file_size_in_byte": 3757, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.path.append", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 18, "usage_type": "call"}, {"api_name": "html.unescape", "line_number": 24, "usage_type": "call"}, {"api_name": "re.search", "line_number": 32, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 44, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlite3.PARSE_DECLTYPES", "line_number": 50, "usage_type": "attribute"}, {"api_name": "bashlint.data_tools.bash_parser", "line_number": 60, "usage_type": "call"}, {"api_name": "bashlint.data_tools", "line_number": 60, "usage_type": "name"}, {"api_name": "bashlint.data_tools.get_utilities", "line_number": 63, "usage_type": "call"}, {"api_name": "bashlint.data_tools", "line_number": 63, "usage_type": "name"}, {"api_name": "bashlint.bash.top_100_utilities", "line_number": 65, "usage_type": "attribute"}, {"api_name": "bashlint.bash", "line_number": 65, "usage_type": "name"}, {"api_name": "bashlint.data_tools.ast2template", "line_number": 67, "usage_type": "call"}, {"api_name": "bashlint.data_tools", "line_number": 67, "usage_type": "name"}, {"api_name": "bashlint.bash.top_100_utilities", "line_number": 81, "usage_type": "attribute"}, {"api_name": "bashlint.bash", "line_number": 81, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 91, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 93, "usage_type": "call"}]} +{"seq_id": "13782604", "text": "from bs4 import BeautifulSoup\nimport csv\nimport requests\nimport unicodedata\nimport re\nimport datetime\n\n\n\nurl = 'https://santemontreal.qc.ca/population/coronavirus-covid-19/'\nresponse = requests.get(url, timeout=10)\nsoup = BeautifulSoup(response.content, 'html.parser')\ntable = soup.findAll('table', attrs={'class':'contenttable'})[3]\n\ntoday = datetime.datetime.now()\nyesterday = today - datetime.timedelta(days=1)\ndate = yesterday.strftime('%Y-%m-%d')\n\noutput_rows = [['Arrondissements', 'Cas Confirmés']]\nfor table_row in table.findAll('tr'):\n columns = table_row.findAll('td')[0:2]\n output_row = []\n for column in columns:\n column_text = column.text\n column_text = unicodedata.normalize('NFKD', column_text).strip()\n column_text = column_text.replace('*', '')\n if re.search('[a-zA-Z]', column_text) is None:\n column_text = column_text.replace(' ', '')\n elif column_text == 'Territoire à confirmer2':\n column_text = column_text.replace('2', '')\n output_row.append(column_text)\n output_rows.append(output_row)\noutput_rows = filter(None, output_rows)\n \nwith open('data\\\\' + str(date) + '.csv', 'w', encoding='utf-8', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(output_rows)", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1288, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 16, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 25, "usage_type": "call"}, {"api_name": "re.search", "line_number": 27, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "443799281", "text": "import signal\nfrom plexstuff import signal_handler\nsignal.signal( signal.SIGINT, signal_handler )\nimport logging, os, re, time\nfrom itertools import chain\nfrom multiprocessing import Pool\nfrom argparse import ArgumentParser\n#\nfrom plexstuff.plexcore import plexcore_deluge, plexcore\nfrom plexstuff.plextvdb import plextvdb_torrents, plextvdb\n\ndef get_items_eztv_io( name, maxnum = 10, verify = True ):\n assert( maxnum >= 5 )\n items, status = plextvdb_torrents.get_tv_torrent_eztv_io(\n name, maxnum = maxnum, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, EZTV.IO COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_items_jackett( name, maxnum = 1000, raw = False, verify = True ):\n assert( maxnum >= 5 )\n logging.info( 'started jackett %s.' % name )\n items, status = plextvdb_torrents.get_tv_torrent_jackett(\n name, maxnum = maxnum, raw = raw, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, JACKETT COULD NOT FIND %s.' % name )\n return None\n return items\n \ndef get_items_zooqle( name, maxnum = 10, verify = True ):\n assert( maxnum >= 5 )\n items, status = plextvdb_torrents.get_tv_torrent_zooqle(\n name, maxnum = maxnum, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, ZOOQLE COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_items_tpb(name, maxnum = 10, doAny = False, raiseError = False, verify = True ):\n assert( maxnum >= 5 )\n items, status = plextvdb_torrents.get_tv_torrent_tpb(\n name, maxnum = maxnum, doAny = doAny, verify = verify )\n if status != 'SUCCESS':\n if raiseError:\n raise ValueError('ERROR, TPB COULD NOT FIND %s.' % name)\n logging.info( 'ERROR, TPB COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_items_torrentz( name, maxnum = 10, verify = True ):\n assert( maxnum >= 5 )\n items, status = plextvdb_torrents.get_tv_torrent_torrentz(\n name, maxnum = maxnum, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, TORRENTZ COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_items_rarbg( name, maxnum = 10, verify = True ):\n assert( maxnum >= 10 )\n items, status = plextvdb_torrents.get_tv_torrent_rarbg(\n name, maxnum = maxnum, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, RARBG COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_items_kickass( name, maxnum = 10, verify = True ):\n assert( maxnum >= 10 )\n items, status = plextvdb_torrents.get_tv_torrent_kickass(\n name, maxnum = maxnu, verify = verify )\n if status != 'SUCCESS':\n logging.info( 'ERROR, KICKASS COULD NOT FIND %s.' % name )\n return None\n return items\n\ndef get_tv_torrent_items(\n items, filename = None, to_torrent_server = False ):\n if len( items ) != 1:\n sortdict = { idx + 1 : item for ( idx, item ) in enumerate(items) }\n bs = 'Choose TV episode or series:\\n%s\\n' % '\\n'.join(\n map(lambda idx: '%d: %s (%d SE, %d LE)' % ( idx, sortdict[ idx ][ 'title' ],\n sortdict[ idx ][ 'seeders' ],\n sortdict[ idx ][ 'leechers' ]),\n sorted( sortdict ) ) )\n iidx = input( bs )\n try:\n iidx = int( iidx.strip( ) )\n if iidx not in sortdict:\n print('Error, need to choose one of the TV files. Exiting...')\n return\n magnet_link = sortdict[ iidx ][ 'link' ]\n actmov = sortdict[ iidx ][ 'title' ]\n except Exception:\n print('Error, did not give a valid integer value. Exiting...')\n return\n else:\n actmov = max( items )[ 'title' ]\n magnet_link = max( items )[ 'link' ]\n\n print('Chosen TV show: %s' % actmov )\n if to_torrent_server: # upload to deluge server\n client, status = plexcore_deluge.get_deluge_client( )\n if status != 'SUCCESS':\n print( status )\n return\n plexcore_deluge.deluge_add_magnet_file(\n client, magnet_link )\n elif filename is None:\n print('magnet link: %s' % magnet_link )\n else:\n with open(filename, 'w') as openfile:\n openfile.write('%s\\n' % magnet_link )\n\ndef process_magnet_items( name, raw = False, verify = True, maxnum = 10 ):\n time0 = time.time( )\n #\n ## check for jackett\n if plexcore.get_jackett_credentials( ) is None:\n pool = Pool( processes = 5 )\n jobs = list(map(\n lambda func: pool.apply_async( func, args = ( name, maxnum ) ),\n ( get_items_zooqle, get_items_rarbg, #get_items_kickass,\n get_items_torrentz, get_items_eztv_io ) ) )\n jobs.append( pool.apply_async( get_items_tpb, args = (\n name, maxnum, False, False ) ) ) # args.do_any = False\n else:\n pool = Pool( processes = 3 )\n jobs = list(map(\n lambda func: pool.apply_async( func, args = ( name, maxnum, verify ) ),\n ( get_items_zooqle, get_items_eztv_io ) ) )\n jobs.append( pool.apply_async( get_items_jackett, args = ( name, maxnum, raw, verify ) ) )\n items_all = list( chain.from_iterable( filter( None, map(lambda job: job.get( ), jobs ) ) ) )\n logging.info( 'search for torrents took %0.3f seconds.' % ( time.time( ) - time0 ) )\n pool.close( )\n pool.join( )\n if len( items_all ) != 0: return items_all\n return None\n \ndef main( ):\n parser = ArgumentParser( )\n parser.add_argument('-n', '--name', dest='name', type=str, action='store', required = True,\n help = 'Name of the TV show to get.')\n parser.add_argument('--maxnum', dest='maxnum', type=int, action='store', default = 10,\n help = 'Maximum number of torrents to look through. Default is 10.')\n parser.add_argument('--raw', dest='do_raw', action='store_true', default = False,\n help = 'If chosen, then use the raw string (for jackett) to download the torrent.' )\n parser.add_argument('-f', '--filename', dest='filename', action='store', type=str,\n help = 'If defined, put torrent or magnet link into filename.')\n parser.add_argument('--add', dest='do_add', action='store_true', default = False,\n help = 'If chosen, push the magnet link into the deluge server.' )\n parser.add_argument('--info', dest='do_info', action='store_true', default = False,\n help = 'If chosen, run in info mode.' )\n parser.add_argument('--noverify', dest='do_verify', action='store_false', default = True,\n help = 'If chosen, do not verify SSL connections.' )\n args = parser.parse_args( )\n logger = logging.getLogger( )\n if args.do_info: logger.setLevel( logging.INFO )\n #\n time0 = time.time( )\n items = process_magnet_items(\n args.name, maxnum = args.maxnum,\n raw = args.do_raw, verify = args.do_verify )\n\n logging.info( 'took %0.3f seconds to get TV torrents for %s.' % (\n time.time( ) - time0, args.name ) )\n if items is not None:\n #\n ## sort from most seeders + leecher to least\n items_sorted = sorted( items, key = lambda tup: (\n -tup['seeders'] - tup['leechers'], tup['title'] ) )[:args.maxnum]\n get_tv_torrent_items( items_sorted, filename = args.filename, to_torrent_server = args.do_add )\n", "sub_path": "plexstuff/plextvdb/cli/get_tv_tor.py", "file_name": "get_tv_tor.py", "file_ext": "py", "file_size_in_byte": 7591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "signal.signal", "line_number": 3, "usage_type": "call"}, {"api_name": "plexstuff.signal_handler", "line_number": 3, "usage_type": "argument"}, {"api_name": "signal.SIGINT", "line_number": 3, "usage_type": "attribute"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_eztv_io", "line_number": 14, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 14, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 23, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_jackett", "line_number": 24, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 24, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 27, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_zooqle", "line_number": 33, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 33, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 36, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_tpb", "line_number": 42, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 42, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 47, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_torrentz", "line_number": 53, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 53, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 56, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_rarbg", "line_number": 62, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 62, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 65, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents.get_tv_torrent_kickass", "line_number": 71, "usage_type": "call"}, {"api_name": "plexstuff.plextvdb.plextvdb_torrents", "line_number": 71, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 74, "usage_type": "call"}, {"api_name": "plexstuff.plexcore.plexcore_deluge.get_deluge_client", "line_number": 104, "usage_type": "call"}, {"api_name": "plexstuff.plexcore.plexcore_deluge", "line_number": 104, "usage_type": "name"}, {"api_name": "plexstuff.plexcore.plexcore_deluge.deluge_add_magnet_file", "line_number": 108, "usage_type": "call"}, {"api_name": "plexstuff.plexcore.plexcore_deluge", "line_number": 108, "usage_type": "name"}, {"api_name": "time.time", "line_number": 117, "usage_type": "call"}, {"api_name": "plexstuff.plexcore.plexcore.get_jackett_credentials", "line_number": 120, "usage_type": "call"}, {"api_name": "plexstuff.plexcore.plexcore", "line_number": 120, "usage_type": "name"}, {"api_name": "multiprocessing.Pool", "line_number": 121, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 129, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 134, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 134, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 135, "usage_type": "call"}, {"api_name": "time.time", "line_number": 135, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 142, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 158, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 159, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 161, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 166, "usage_type": "call"}, {"api_name": "time.time", "line_number": 167, "usage_type": "call"}]} +{"seq_id": "203017354", "text": "\"\"\"Fetch weather for a given location.\"\"\"\nimport requests\nfrom emoji import emojize\nfrom pandas import DataFrame\nfrom requests.exceptions import HTTPError\n\nfrom config import CHATANGO_OBI_ROOM, METRIC_SYSTEM_USERS, WEATHERSTACK_API_KEY\nfrom logger import LOGGER\n\n\ndef weather_by_location(location: str, weather: DataFrame, room: str, user: str) -> str:\n \"\"\"\n Return temperature and weather per city/state/zip.\n\n :param location: City or location to fetch weather for.\n :type location: str\n :param weather: Table matching types of weather to emojis.\n :type weather: DataFrame\n :param location: City or location to fetch weather for.\n :type location: str\n :param room: Name the Chatango room that made the request (used for metric system).\n :type room: str\n :param user: User who made the request (used for metric system).\n :type user: str\n :returns: str\n \"\"\"\n units = \"f\"\n endpoint = \"http://api.weatherstack.com/current\"\n params = {\n \"access_key\": WEATHERSTACK_API_KEY,\n \"query\": location.replace(\";\", \"\"),\n \"units\": \"f\",\n }\n if room == CHATANGO_OBI_ROOM or user in METRIC_SYSTEM_USERS:\n params[\"units\"] = \"m\"\n units = \"c\"\n try:\n req = requests.get(endpoint, params=params)\n data = req.json()\n if data.get(\"success\") is False:\n LOGGER.warning(\n f'Failed to get weather for `{location}`: {data[\"error\"][\"info\"]}'\n )\n return emojize(\n f\":warning:️️ wtf even is `{location}` :warning:\", use_aliases=True\n )\n if req.status_code == 200 and data.get(\"current\"):\n weather_code = data[\"current\"][\"weather_code\"]\n weather_emoji = weather.find_row(\"code\", weather_code).get(\"icon\")\n if weather_emoji:\n weather_emoji = emojize(weather_emoji, use_aliases=True)\n response = f'{data[\"request\"][\"query\"]}: \\\n {weather_emoji} {data[\"current\"][\"weather_descriptions\"][0]}. \\\n {data[\"current\"][\"temperature\"]}°{units} \\\n (feels like {data[\"current\"][\"feelslike\"]}°{units}). \\\n {data[\"current\"][\"precip\"] * 100}% precipitation.'\n return response\n except HTTPError as e:\n LOGGER.error(f\"Failed to get weather for `{location}`: {e.response.content}\")\n return emojize(\n f\":warning:️️ fk me the weather API is down :warning:\",\n use_aliases=True,\n )\n except KeyError as e:\n LOGGER.error(f\"KeyError while fetching weather for `{location}`: {e}\")\n return emojize(\n f\":warning:️️ omfg u broke the bot WHAT DID YOU DO IM DEAD AHHHHHH :warning:\",\n use_aliases=True,\n )\n except Exception as e:\n LOGGER.error(f\"Failed to get weather for `{location}`: {e}\")\n return emojize(\n f\":warning:️️ omfg u broke the bot WHAT DID YOU DO IM DEAD AHHHHHH :warning:\",\n use_aliases=True,\n )\n", "sub_path": "broiestbot/commands/weather.py", "file_name": "weather.py", "file_ext": "py", "file_size_in_byte": 3076, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.DataFrame", "line_number": 11, "usage_type": "name"}, {"api_name": "config.WEATHERSTACK_API_KEY", "line_number": 30, "usage_type": "name"}, {"api_name": "config.CHATANGO_OBI_ROOM", "line_number": 34, "usage_type": "name"}, {"api_name": "config.METRIC_SYSTEM_USERS", "line_number": 34, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 38, "usage_type": "call"}, {"api_name": "logger.LOGGER.warning", "line_number": 41, "usage_type": "call"}, {"api_name": "logger.LOGGER", "line_number": 41, "usage_type": "name"}, {"api_name": "emoji.emojize", "line_number": 44, "usage_type": "call"}, {"api_name": "emoji.emojize", "line_number": 51, "usage_type": "call"}, {"api_name": "requests.exceptions.HTTPError", "line_number": 58, "usage_type": "name"}, {"api_name": "logger.LOGGER.error", "line_number": 59, "usage_type": "call"}, {"api_name": "logger.LOGGER", "line_number": 59, "usage_type": "name"}, {"api_name": "emoji.emojize", "line_number": 60, "usage_type": "call"}, {"api_name": "logger.LOGGER.error", "line_number": 65, "usage_type": "call"}, {"api_name": "logger.LOGGER", "line_number": 65, "usage_type": "name"}, {"api_name": "emoji.emojize", "line_number": 66, "usage_type": "call"}, {"api_name": "logger.LOGGER.error", "line_number": 71, "usage_type": "call"}, {"api_name": "logger.LOGGER", "line_number": 71, "usage_type": "name"}, {"api_name": "emoji.emojize", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "112051291", "text": "# -*- coding: utf-8 -*- \n\n# 1,get homepage\thttp://cpc.people.com.cn/gbzl/flcx.html\n# 2,analyze names and urls\n# 3,use urls to get html\n# 4,analyze people.html\thttp://cpc.people.com.cn/gbzl/html/121000287.html\n\t\t\t\t\t\t# gbzl.people.com.cn/grzy.php?id=140400136\n# 5,insert into sql\n\nimport requests,re,time\nfrom bs4 import BeautifulSoup\nfrom db import *\n\n\ndef getHtml(url):\n\tif url.isdigit():\n\t\ttmp = {'id':url}\n\t\thomepage = requests.get('http://gbzl.people.com.cn/grzy.php',params = tmp)\n\telse:\n\t\thomepage = requests.get(url)\n\tresult = homepage.text.encode(homepage.encoding)\n\treturn result\n\ndef getUrls(homepage):\n\tIDs = []\n\tpattern = 'grzy\\.php\\?id=\\d{9}'\n\tresults = re.findall(pattern,homepage)\n\tfor url in results:\n\t\tID = url[-9:]\n\t\tif ID not in IDs:\n\t\t\tIDs.append(ID)\n\treturn IDs\n\ndef analyzePeople(url):\n\thtml = getHtml(url)\n\tsoup = BeautifulSoup(html,'lxml')\n\t\n\t# [name,now,birthDay,sex,born,nation,school,degree,partyDay,workDay,mainExp]\n\tname = soup.find('strong').text\n\tnow = soup.find('p').text\n\tbirthDay = soup.find_all('li')[0].text[5:]\n\tsex = soup.find_all('li')[1].text[-1]\n\tborn = soup.find_all('li')[2].text[3:]\n\tnation = soup.find_all('li')[3].text[3:]\n\tschool = soup.find_all('li')[4].text[5:]\n\tdegree = soup.find_all('li')[5].text[6:]\n\tpartyDay = soup.find_all('li')[6].text[5:]\n\tworkDay = soup.find_all('li')[6].text[7:]\n\tmainExp = soup.find(class_='jili').text\n\tresult = (name,now,birthDay,sex,born,nation,school,degree,partyDay,workDay,mainExp)\n\tprint('name : %s\\n'%name)\n\treturn result\n\ndef main(homeUrl):\n\tstartTime = time.time()\n\tconn = initialDB('db.sqlite')\n\thomepage = getHtml(homeUrl)\n\turls = getUrls(homepage)\n\tnum = len(urls)\n\tcount = 0\n\tfor url in urls:\n\t\tprint('------------------')\n\t\tprint('count : %s/%s'%(count,num))\n\t\tprint('id : %s'%url)\n\t\ttry:\n\t\t\ttmp = analyzePeople(url)\n\t\texcept Exception as e:\n\t\t\tcount+=1\n\t\t\tcontinue\t\t\n\t\tinsertDB(tmp,conn)\n\t\tif count % 10 ==0:\n\t\t\tconn.commit()\n\t\tcount+=1\n\tconn.close()\n\tusedTime = time.time()-startTime\n\tprint('Total used %s seconds.'%usedTime)\n\nif __name__ == '__main__':\n\tmain('http://cpc.people.com.cn/gbzl/flcx.html')", "sub_path": "01_Chinese_leaders/go.py", "file_name": "go.py", "file_ext": "py", "file_size_in_byte": 2096, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 18, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 20, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 27, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 36, "usage_type": "call"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "240337721", "text": "import torch\nimport torchvision\nimport torchvision.transforms as transforms\n\ntransform = transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n)\n\ntrain_set = torchvision.datasets.CIFAR10(\n root=\"./data\", train=True, download=True, transform=transform\n)\ntrain_loader = torch.utils.data.DataLoader(\n train_set, batch_size=1000, shuffle=True, num_workers=2\n)\n\ntest_set = torchvision.datasets.CIFAR10(\n root=\"./data\", train=False, download=True, transform=transform\n)\ntest_loader = torch.utils.data.DataLoader(\n test_set, batch_size=1000, shuffle=False, num_workers=2\n)\n\nclasses = (\n \"plane\",\n \"car\",\n \"bird\",\n \"cat\",\n \"deer\",\n \"dog\",\n \"frog\",\n \"horse\",\n \"ship\",\n \"truck\",\n)\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ConvNet(nn.Module):\n def __init__(self, dropout_rate, activation_function_type):\n super(ConvNet, self).__init__()\n\n if activation_function_type == \"relu\":\n activation_function = nn.ReLU()\n elif activation_function_type == \"sigmoid\":\n activation_function = nn.Sigmoid()\n elif activation_function_type == \"leaky_relu\":\n activation_function = nn.LeakyReLU()\n\n self.layer1 = nn.Sequential(\n # 3 is the rbg\n nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(32),\n activation_function,\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(64),\n activation_function,\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.layer3 = nn.Sequential(\n nn.Conv2d(64, 128, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(128),\n activation_function,\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.drop_out = nn.Dropout(p=dropout_rate)\n self.fc1 = nn.Linear(4 * 4 * 128, 1000)\n self.fc2 = nn.Linear(1000, 10)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = out.reshape(out.size(0), -1)\n out = self.drop_out(out)\n out = self.fc1(out)\n out = self.fc2(out)\n return out\n\n\nfrom utils import train\nimport torch.optim as optim\nfrom torch.nn import BatchNorm2d\n\nnet = ConvNet(0.5, 'relu')\nepochs = 100\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(net.parameters(), lr=0.01)\n\nlist_of_dropout_rates = [0, 0.25, 0.5]\nlist_of_activation_functions = [\"sigmoid\", \"relu\", \"leaky_relu\"]\nlist_of_optimizers = [\"SGD\", \"SGD_momentum\", \"Adam\"]\n\nif __name__ == \"__main__\":\n train(\n epochs=epochs,\n model=net,\n optimizer=optimizer,\n criterion=criterion,\n train_loader=train_loader,\n test_loader=test_loader,\n file_name='test'\n )\n", "sub_path": "example_network.py", "file_name": "example_network.py", "file_ext": "py", "file_size_in_byte": 2979, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torchvision.transforms.Compose", "line_number": 5, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 5, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 6, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 6, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 6, "usage_type": "call"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 9, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 12, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 16, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 64, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 92, "usage_type": "name"}, {"api_name": "utils.train", "line_number": 99, "usage_type": "call"}]} +{"seq_id": "97474243", "text": "#!/usr/bin/env python3\n# -*- coding: utf8 -*-\n\n\"\"\"\nthis is created and tested with Python 3.6.5\nwritten 2018 by Chuck Wernicke for General Bytes\n\nparts of this code were extracted from python3-krakenex\nhttps://github.com/veox/python3-krakenex\n\n# Requires python-requests. Install with pip:\n#\tpip install requests\n# or, with easy-install:\n#\teasy_install requests\n\"\"\"\n\nimport sys, json, hmac, hashlib, time, requests, getpass\n\n# private query signing\nimport urllib.parse\nimport base64\n\nif sys.version_info[0] < 3:\n\tprint (\"ERROR: Python version 3 is required to use this script!\")\n\tprint (\"Install with: sudo apt install python3\")\n\tprint ()\n\tquit ()\n\nAPI_URL = 'https://api.kraken.com'\nAPI_VER = '0'\n\n# Kraken API object\nclass KrakenAPI(object):\n\tdef __init__(self, key='', secret=''):\n\t\t\"\"\" Create an object with authentication information.\n\t\t:param key: (optional) key identifier for queries to the API\n\t\t:type key: str\n\t\t:param secret: (optional) actual private key used to sign messages\n\t\t:type secret: str\n\t\t:returns: None\n\t\t\"\"\"\n\t\tself.key = key\n\t\tself.secret = secret\n\t\tself.uri = API_URL\n\t\tself.apiversion = API_VER\n\t\tself.session = requests.Session()\n\t\tself.session.headers.update({\n\t\t\t'User-Agent': 'GB Key Verifier/1.0 (+https://generalbytes.com)'\n\t\t})\n\t\tself.response = None\n\t\tself._json_options = {}\n\t\treturn\n\n\tdef _query(self, urlpath, data, headers=None, timeout=None):\n\t\t\"\"\" Low-level query handling.\n\t\t.. note::\n\t\t Use :py:meth:`query_private` or :py:meth:`query_public`\n\t\t unless you have a good reason not to.\n\t\t:param urlpath: API URL path sans host\n\t\t:type urlpath: str\n\t\t:param data: API request parameters\n\t\t:type data: dict\n\t\t:param headers: (optional) HTTPS headers\n\t\t:type headers: dict\n\t\t:param timeout: (optional) if not ``None``, a :py:exc:`requests.HTTPError`\n\t\t\t\t\t\twill be thrown after ``timeout`` seconds if a response\n\t\t\t\t\t\thas not been received\n\t\t:type timeout: int or float\n\t\t:returns: :py:meth:`requests.Response.json`-deserialised Python object\n\t\t:raises: :py:exc:`requests.HTTPError`: if response status not successful\n\t\t\"\"\"\n\t\tif data is None:\n\t\t\tdata = {}\n\t\tif headers is None:\n\t\t\theaders = {}\n\n\t\turl = self.uri + urlpath\n\n\t\tself.response = self.session.post(url, data = data, headers = headers, timeout = timeout)\n\n\t\tif self.response.status_code not in (200, 201, 202):\n\t\t\tself.response.raise_for_status()\n\n\t\treturn self.response.json(**self._json_options)\n\n\tdef _nonce(self):\n\t\t\"\"\" Nonce counter.\n\t\t:returns: an always-increasing unsigned integer (up to 64 bits wide)\n\t\t\"\"\"\n\t\treturn int(1000*time.time())\n\t\t\t\n\tdef _sign(self, data, urlpath):\n\t\t\"\"\" Sign request data according to Kraken's scheme.\n\t\t:param data: API request parameters\n\t\t:type data: dict\n\t\t:param urlpath: API URL path sans host\n\t\t:type urlpath: str\n\t\t:returns: signature digest\n\t\t\"\"\"\n\t\tpostdata = urllib.parse.urlencode(data)\n\n\t\t# Unicode-objects must be encoded before hashing\n\t\tencoded = (str(data['nonce']) + postdata).encode()\n\t\tmessage = urlpath.encode() + hashlib.sha256(encoded).digest()\n\n\t\tsignature = hmac.new(base64.b64decode(self.secret),\n\t\t\t\t\t\t\t message, hashlib.sha512)\n\t\tsigdigest = base64.b64encode(signature.digest())\n\n\t\treturn sigdigest.decode()\n\t\n\tdef query_private(self, method, data=None, timeout=None):\n\t\t\"\"\" Performs an API query that requires a valid key/secret pair.\n\t\t:param method: API method name\n\t\t:type method: str\n\t\t:param data: (optional) API request parameters\n\t\t:type data: dict\n\t\t:param timeout: (optional) if not ``None``, a :py:exc:`requests.HTTPError`\n\t\t\t\t\t\twill be thrown after ``timeout`` seconds if a response\n\t\t\t\t\t\thas not been received\n\t\t:type timeout: int or float\n\t\t:returns: :py:meth:`requests.Response.json`-deserialised Python object\n\t\t\"\"\"\n\t\tif data is None:\n\t\t\tdata = {}\n\n\t\tif not self.key or not self.secret:\n\t\t\traise Exception('Either key or secret is not set!')\n\n\t\tdata['nonce'] = self._nonce()\n\n\t\turlpath = '/' + self.apiversion + '/private/' + method\n\n\t\theaders = {\n\t\t\t'API-Key': self.key,\n\t\t\t'API-Sign': self._sign(data, urlpath)\n\t\t}\n\n\t\treturn self._query(urlpath, data, headers, timeout = timeout)\n\t\t\n\t\n\tdef query_public(self, method, data=None, timeout=None):\n\t\t\"\"\" Performs an API query that does not require a valid key/secret pair.\n\t\t:param method: API method name\n\t\t:type method: str\n\t\t:param data: (optional) API request parameters\n\t\t:type data: dict\n\t\t:param timeout: (optional) if not ``None``, a :py:exc:`requests.HTTPError`\n\t\t\t\t\t\twill be thrown after ``timeout`` seconds if a response\n\t\t\t\t\t\thas not been received\n\t\t:type timeout: int or float\n\t\t:returns: :py:meth:`requests.Response.json`-deserialised Python object\n\t\t\"\"\"\n\t\tif data is None:\n\t\t\tdata = {}\n\n\t\turlpath = '/' + self.apiversion + '/public/' + method\n\n\t\treturn self._query(urlpath, data, timeout = timeout)\n\nShowKeys=False\nif str(sys.argv).find(\"ShowKeys\") > 0:\n\tShowKeys=True\n\nprint ()\nprint(\"You are about to test your Kraken API parameters...\")\n\ntry:\t\n\t\n\tif ShowKeys:\n\t\tAPI_KEY = input('Please enter your Kraken API Key: ')\n\telse:\n\t\tAPI_KEY = getpass.getpass('Please enter your Kraken API Key: ')\n\t# API Key override can be entered here, or typed at the command line above\n\t#API_KEY = \"\"\n\n\tif ShowKeys:\n\t\tAPI_SECRET = input('Please enter your Kraken API Secret: ')\n\telse:\n\t\tAPI_SECRET = getpass.getpass('Please enter your Kraken API Secret: ')\n\t# API Secret override can be entered here, or typed at the command line above\n\t#API_SECRET = \"\"\n\n\tkraken = KrakenAPI(API_KEY, API_SECRET)\n\n\treply = kraken.query_private('Balance', None, 5)\n\tassert reply['error'] == []\n\n\tprint(\"SUCCESS! Your Kraken API is working with your keys.\")\n\tprint ()\n\tprint (\"Your Kraken fiat & balance:\")\n\tfor x in reply['result']:\n\t\tif str(x)[0] == \"Z\":\n\t\t\tprint(str(x)[1:] + \": \" + str(reply['result'][x]))\n\tprint ()\n\tprint (\"Your Kraken wallets & balances:\")\n\tfor x in reply['result']:\n\t\tif str(x)[0] == \"X\":\n\t\t\tprint(\" \" + str(x)[1:] + \": \" + str(reply['result'][x]))\n\t\telif str(x)[0] != \"Z\":\n\t\t\tprint(str(x) + \": \" + str(reply['result'][x]))\n\nexcept KeyboardInterrupt:\n\tprint (\" ABORTING!\")\nexcept ConnectionError:\n\tprint (\"ERROR: Kraken refused to connect:\" + str(sys.exc_info()))\nexcept requests.Timeout:\n\tprint (\"ERROR: Timeout connecting to Kraken!\")\nexcept AssertionError:\n\tprint ()\n\tprint (\"ERROR: Your API Keys failed! Code: \" + str(reply['error']))\n\tif len(API_KEY) > 4:\n\t\tprint (\"Using KEY: \" + API_KEY[0:2] + \"...\" + API_KEY[-2:])\n\telse:\n\t\tprint (\"Bad KEY: \" + API_KEY)\n\tif len(API_SECRET) > 4:\n\t\tprint (\"Using Secret: \" + API_SECRET[0:2] + \"...\" + API_SECRET[-2:])\n\telse:\n\t\tprint (\"Bad Secret: \" + API_SECRET)\nexcept:\n\tprint (\"ERROR: Unknown failure testing Kraken auth: \" + str(sys.exc_info()))\n\nprint ()\nprint (\"exiting Kraken auth test...\")\n", "sub_path": "Support/Python/kraken.py", "file_name": "kraken.py", "file_ext": "py", "file_size_in_byte": 6667, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.version_info", "line_number": 23, "usage_type": "attribute"}, {"api_name": "requests.Session", "line_number": 46, "usage_type": "call"}, {"api_name": "time.time", "line_number": 90, "usage_type": "call"}, {"api_name": "urllib.parse.parse.urlencode", "line_number": 100, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 100, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 100, "usage_type": "name"}, {"api_name": "hashlib.sha256", "line_number": 104, "usage_type": "call"}, {"api_name": "hmac.new", "line_number": 106, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 106, "usage_type": "call"}, {"api_name": "hashlib.sha512", "line_number": 107, "usage_type": "attribute"}, {"api_name": "base64.b64encode", "line_number": 108, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 162, "usage_type": "attribute"}, {"api_name": "getpass.getpass", "line_number": 173, "usage_type": "call"}, {"api_name": "getpass.getpass", "line_number": 180, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 206, "usage_type": "call"}, {"api_name": "requests.Timeout", "line_number": 207, "usage_type": "attribute"}, {"api_name": "sys.exc_info", "line_number": 221, "usage_type": "call"}]} +{"seq_id": "370466862", "text": "import sys, datetime\nfrom decimal import *\nfrom PyQt5.QtWidgets import QApplication,QDialog,QMessageBox, QTableWidgetItem,QWidget\nfrom PyQt5 import uic\nfrom form_entrada import Ui_form_entrada\nfrom PyQt5.QtCore import pyqtRemoveInputHook\nfrom E_producto import E_producto\nfrom E_inventario import E_inventario\nfrom E_movimientos import E_movimiento\n\n\nclass entrada(QDialog):\n obj_form = Ui_form_entrada()\n lista_producto=[]\n lista_producto_agregados = []\n\n def __init__(self):\n QDialog.__init__(self)\n obj_form= Ui_form_entrada()\n self.obj_form.setupUi(self)\n self.obj_form.btn_buscar.clicked.connect(self.buscar)\n self.obj_form.btn_limpiar.clicked.connect(self.limpiar_todo)\n self.obj_form.btn_agregar.clicked.connect(self.agregar)\n self.obj_form.btn_confirmar.clicked.connect(self.confirmar)\n\n\n def confirmar(self):\n confirma = QMessageBox.question(self, 'Alerta ', \"Esta seguro de agregar estos productos?\",\n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n if confirma == QMessageBox.Yes:\n #pyqtRemoveInputHook()\n #import pdb; pdb.set_trace()\n obj_e_movimiento= E_movimiento()\n obj_e_movimiento.fecha =datetime.datetime.now()\n\n for item in self.lista_producto_agregados:\n obj_e_movimiento.cantidad = self.obj_form.doubleSpinBox.text()\n obj_e_movimiento.id_producto = item.id_producto\n obj_e_movimiento.tipo = \"Entrada\"\n obj_e_movimiento.guardar(obj_e_movimiento)\n\n obj_e_inventario = E_inventario()\n result = obj_e_inventario.get_inventario_id_producto(item.id_producto)\n if result == False:\n obj_e_inventario.guardar(item)\n\n else:\n #pyqtRemoveInputHook()\n #import pdb; pdb.set_trace()\n item.cantidad = Decimal(result.cantidad) +Decimal(item.cantidad.replace(\",\", \".\"))\n item.id_inventario=result.id_inventario\n obj_e_inventario.actualizar(item)\n\n\n def agregar(self):\n obj_e_producto= E_producto()\n producto= obj_e_producto.get_producto_nombre(self.obj_form.cbx_producto.currentText())\n obj_e_inventario=E_inventario()\n obj_e_inventario.cantidad=self.obj_form.doubleSpinBox.text()\n obj_e_inventario.id_producto=producto.id_producto\n self.lista_producto_agregados.append(obj_e_inventario)\n\n rowPosition = self.obj_form.tw_productos.rowCount()\n self.obj_form.tw_productos.insertRow(rowPosition)\n self.obj_form.tw_productos.setItem(rowPosition, 0, QTableWidgetItem(str(producto.id_producto)))\n self.obj_form.tw_productos.setItem(rowPosition, 1, QTableWidgetItem(producto.nombre))\n self.obj_form.tw_productos.setItem(rowPosition, 2, QTableWidgetItem(str(self.obj_form.doubleSpinBox.text())))\n self.obj_form.tw_productos.setItem(rowPosition, 3, QTableWidgetItem(str(self.obj_form.dateEdit.text())))\n\n\n\n\n\n def buscar(self):\n self.limpiar()\n obj_E_producto= E_producto()\n if self.obj_form.lne_nombre_buscar.text() !=\"\":\n self.lista_producto= obj_E_producto.get_producto_nombre_like(self.obj_form.lne_nombre_buscar.text())\n self.llenar_combo()\n elif self.obj_form.lne_codigo_buscar.text() != \"\":\n self.lista_producto = obj_E_producto.get_producto_codigo_like(self.obj_form.lne_codigo_buscar.text())\n self.llenar_combo()\n\n def limpiar_todo(self):\n self.limpiar()\n self.obj_form.lne_nombre_buscar.setText(\"\")\n self.obj_form.lne_codigo_buscar.setText(\"\")\n while (self.obj_form.tw_productos.rowCount() > 0):\n self.obj_form.tw_productos.removeRow(0)\n\n def llenar_combo(self):\n for producto in self.lista_producto:\n self.obj_form.cbx_producto.addItem(producto.nombre)\n\n\n\n def limpiar(self):\n self.obj_form.cbx_producto.clear()\n\n\n", "sub_path": "w_form_entrada.py", "file_name": "w_form_entrada.py", "file_ext": "py", "file_size_in_byte": 4066, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 12, "usage_type": "name"}, {"api_name": "form_entrada.Ui_form_entrada", "line_number": 13, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDialog.__init__", "line_number": 18, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 18, "usage_type": "name"}, {"api_name": "form_entrada.Ui_form_entrada", "line_number": 19, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 28, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 28, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 29, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 29, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 29, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 31, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 31, "usage_type": "name"}, {"api_name": "E_movimientos.E_movimiento", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "attribute"}, {"api_name": "E_inventario.E_inventario", "line_number": 43, "usage_type": "call"}, {"api_name": "E_producto.E_producto", "line_number": 57, "usage_type": "call"}, {"api_name": "E_inventario.E_inventario", "line_number": 59, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 66, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 67, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 68, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 69, "usage_type": "call"}, {"api_name": "E_producto.E_producto", "line_number": 77, "usage_type": "call"}]} +{"seq_id": "350126421", "text": "from django.conf.urls import url, include\nfrom .views import home, post_list, post_detail, post_new, post_edit, signup, delete_post\nfrom django.contrib.auth.views import login, logout\n\nurlpatterns = [\n url(r'^$', home, name=\"home_view\"),\n url(r'^postlist$', post_list, name = 'post_list_view'),\n url(r'^post/(?P[0-9]+)/$', post_detail, name = 'post_detail_view'),\n url(r'^post/(?P[0-9]+)/delete/$', delete_post, name = 'delete_post'),\n url(r'^post/new/$',post_new, name = 'post_new_view'),\n url(r'^post/(?P[0-9]+)/edit/$', post_edit, name='post_edit'),\n url(r'^signup/$', signup.as_view(),name = 'signup' ),\n url(r'^login/$', login , {'template_name': 'ParraCity/login.html'}, name='login_city'),\n\turl(r'^logout/$', logout ,{'template_name': 'ParraCity/logout.html'}, name='logout_city'),\n\n]\n", "sub_path": "ParraCity/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 829, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "views.home", "line_number": 6, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "views.post_list", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "views.post_detail", "line_number": 8, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "views.delete_post", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "views.post_new", "line_number": 10, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "views.post_edit", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "views.signup.as_view", "line_number": 12, "usage_type": "call"}, {"api_name": "views.signup", "line_number": 12, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.login", "line_number": 13, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.logout", "line_number": 14, "usage_type": "argument"}]} +{"seq_id": "551756082", "text": "import time\nimport jwt\nimport cgi\nimport json\nfrom sys import version as python_version\nfrom cgi import parse_header, parse_multipart\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nfrom urllib.parse import parse_qs\n\nsecret_key = \"abcd1234\"\n\nHOST_NAME = 'localhost'\nPORT_NUMBER = 8080\n\n\nclass TestServerHandler(BaseHTTPRequestHandler):\n def do_HEAD(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n\n def do_GET(self):\n \"\"\"Respond to a GET request.\"\"\"\n self.send_response(200)\n\n if self.path == \"/\":\n path = \"index.html\"\n self.send_header('Content-Type', 'text/html')\n elif self.path == \"/embed.js\":\n path = \"embed.js\"\n elif self.path == \"/embedjs.css\":\n path = \"embedjs.css\"\n elif self.path == \"/favicon.ico\":\n return \"\"\n\n self.end_headers()\n file = open(path, \"r\").read().encode('utf-8')\n self.wfile.write(file)\n\n def do_POST(self):\n self.send_response(200)\n post_data = self.parse_POST()\n if self.path == \"/tokenize/\":\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n encoded_jwt = jwt.encode(post_data, secret_key, algorithm='HS256')\n self.wfile.write(encoded_jwt)\n elif self.path == \"/submit/\":\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n decoded_jwt = jwt.decode(post_data['token'], secret_key, algorithm='HS256')\n self.wfile.write(json.dumps(decoded_jwt).encode('utf-8'))\n\n def parse_POST(self):\n ctype, pdict = parse_header(self.headers['content-type'])\n if ctype == 'multipart/form-data':\n postvars = parse_multipart(self.rfile, pdict)\n elif ctype == 'application/x-www-form-urlencoded':\n length = int(self.headers['content-length'])\n postvars = parse_qs(\n self.rfile.read(length),\n keep_blank_values=1)\n else:\n postvars = {}\n postvars = {k.decode('utf-8'): v[0].decode('utf-8') for k, v in postvars.items()}\n return postvars\n\n\nif __name__ == '__main__':\n server_class = HTTPServer\n httpd = server_class((HOST_NAME, PORT_NUMBER), TestServerHandler)\n print(time.asctime(), f\"Server Starts - {HOST_NAME}:{PORT_NUMBER}\")\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n pass\n httpd.server_close()\n print(time.asctime(), f\"Server Stops - {HOST_NAME}:{PORT_NUMBER}\")\n", "sub_path": "app/static/widget/test_server.py", "file_name": "test_server.py", "file_ext": "py", "file_size_in_byte": 2614, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "http.server.BaseHTTPRequestHandler", "line_number": 16, "usage_type": "name"}, {"api_name": "jwt.encode", "line_number": 46, "usage_type": "call"}, {"api_name": "jwt.decode", "line_number": 51, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 52, "usage_type": "call"}, {"api_name": "cgi.parse_header", "line_number": 55, "usage_type": "call"}, {"api_name": "cgi.parse_multipart", "line_number": 57, "usage_type": "call"}, {"api_name": "urllib.parse.parse_qs", "line_number": 60, "usage_type": "call"}, {"api_name": "http.server.HTTPServer", "line_number": 70, "usage_type": "name"}, {"api_name": "time.asctime", "line_number": 72, "usage_type": "call"}, {"api_name": "time.asctime", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "1605884", "text": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nDESC=\"\"\"EPP script to copy input UDFs into output UDFs by matching names\n\nChuan Wang, Science for Life Laboratory, Stockholm, Sweden\n\"\"\"\nimport os\nimport sys\n\nfrom argparse import ArgumentParser\nfrom genologics.lims import Lims\nfrom genologics.entities import Process\nfrom genologics.config import BASEURI, USERNAME, PASSWORD\n\n\ndef main(lims, pid, udfs):\n\n process = Process(lims, id = pid)\n\n inputs = process.all_inputs()\n input_udf_dict = dict()\n for input in inputs:\n if input.name not in input_udf_dict.keys():\n input_udf_dict[input.name] = dict(input.udf.items())\n else:\n sys.stderr.write('ERROR: Duplicated artifact name {}!'.format(input.name))\n sys.exit(2)\n\n outputs = [i for i in process.all_outputs() if i.type == 'Analyte']\n for output in outputs:\n if output.name in input_udf_dict.keys():\n for udf in udfs:\n if udf in input_udf_dict[output.name].keys():\n output.udf[udf] = input_udf_dict[output.name][udf]\n output.put()\n else:\n sys.stderr.write('ERROR: Specified UDF {} not found!'.format(udf))\n sys.exit(2)\n else:\n sys.stderr.write('ERROR: Output name {} not found!'.format(output.name))\n sys.exit(2)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=DESC)\n parser.add_argument('--pid', required=True, help='Lims id for current Process')\n parser.add_argument('--udfs', nargs='+', required=True, help='List of output UDF to be copied from input; e.g. --udf A B C D')\n args = parser.parse_args()\n\n lims = Lims(BASEURI, USERNAME, PASSWORD)\n lims.check_version()\n main(lims, args.pid, args.udfs)\n", "sub_path": "scripts/copy_input_udf_to_output.py", "file_name": "copy_input_udf_to_output.py", "file_ext": "py", "file_size_in_byte": 1821, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "genologics.entities.Process", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 27, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 28, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 38, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 39, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 41, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 41, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 42, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 46, "usage_type": "call"}, {"api_name": "genologics.lims.Lims", "line_number": 51, "usage_type": "call"}, {"api_name": "genologics.config.BASEURI", "line_number": 51, "usage_type": "argument"}, {"api_name": "genologics.config.USERNAME", "line_number": 51, "usage_type": "argument"}, {"api_name": "genologics.config.PASSWORD", "line_number": 51, "usage_type": "argument"}]} +{"seq_id": "128011866", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport re\n\nimport numpy as np\nfrom scipy.interpolate import interp2d\n# from scipy.interpolate import interp1d\n\n# '/home/charles-antoine/Bureau/ROSS4_tabR'\n\n\nclass PredCountsFromQLF_Class():\n\n def __init__(self):\n\n self.QLF_OK = False\n self.EFF_OK = False\n self.QLF_EFF_OK = False\n\n # QLF\n self.QLF_nz = 0\n self.QLF_stepz = 0\n # self.QLF_tabz = None\n self.QLF_zlimit = None\n\n self.QLF_nmag = 0\n self.QLF_stepmag = 0\n self.QLF_tabmag = None\n self.QLF_maglimit = None\n\n self.QLF_dNdzdmag = None\n self.QLF_Ndzdmag = None\n\n # EFF\n self.EFF_zlimit = None\n self.EFF_maglimit = None\n self.EFF_dzdmag = None\n\n # QLF_EFF\n self.QLF_EFF_zlimit = None\n self.QLF_EFF_maglimit = None\n\n self.interpEFF_dzdmag = None\n self.interpQLF_dNdzdmag = None\n self.interpQLF_EFF_dNdzdmag = None\n\n self.QLF_EFF_dNdz = None\n self.QLF4Compl_dNdz = None\n self.Compl_dz = None\n\n self.QLF_EFF_dNdmag = None\n self.QLF4Compl_dNdmag = None\n self.Compl_dmag = None\n\n self.QLF_EFF_dNdzdmag = None\n self.QLF4Compl_dNdzdmag = None\n self.Compl_dzdmag = None\n\n def LoadQLF_Data(self, fpn_QLF_Data, mMzred=np.array([0., 6.]),\n skyArea=10000.):\n\n # Data loading in \"dataStr\"\n dataStr = np.loadtxt(fpn_QLF_Data, dtype=str, delimiter='\\n')\n self.QLF_nz = len(re.findall(r'\\d+(?:\\.\\d+)?', dataStr[0])) - 1\n self.QLF_nmag = len(dataStr)\n\n # ZRED\n self.QLF_zlimit = np.linspace(mMzred[0], mMzred[1],\n self.QLF_nz + 1, endpoint=True)\n self.QLF_stepz = self.QLF_zlimit[1] - self.QLF_zlimit[0]\n # self.QLF_tabz = self.QLF_zlimit[0 : -1] + self.QLF_stepz / 2.\n\n #\n self.QLF_tabmag = np.zeros(self.QLF_nmag)\n self.QLF_dNdzdmag = np.zeros((self.QLF_nmag + 1, self.QLF_nz + 1))\n\n for nL, line in enumerate(dataStr):\n dNdzdmag = re.findall(r'\\d+(?:\\.\\d+)?', line)\n dNdzdmag = np.asarray(dNdzdmag).astype(np.float)\n self.QLF_tabmag[nL] = dNdzdmag[0]\n self.QLF_dNdzdmag[nL + 1, 1:] = dNdzdmag[1:]\n\n self.QLF_stepmag = self.QLF_tabmag[1] - self.QLF_tabmag[0]\n\n # MAG\n self.QLF_maglimit = np.zeros(self.QLF_nmag + 1)\n self.QLF_maglimit[0: -1] = self.QLF_tabmag - self.QLF_stepmag / 2.\n self.QLF_maglimit[-1] = self.QLF_maglimit[-2] + self.QLF_stepmag\n\n self.QLF_dNdzdmag /= skyArea\n\n self.QLF_Ndzdmag = np.cumsum(np.cumsum(\n self.QLF_dNdzdmag, axis=0), axis=1)\n\n self.QLF_OK = True\n self.QLF_EFF_OK = False\n\n def LoadEffData(self, EFFdata, EFFzlimit, EFFmaglimit):\n\n self.EFF_dzdmag = np.copy(EFFdata)\n self.EFF_zlimit = np.copy(EFFzlimit)\n self.EFF_maglimit = np.copy(EFFmaglimit)\n\n self.EFF_OK = True\n self.QLF_EFF_OK = False\n\n def PrelOpFunc(self):\n\n if self.QLF_OK & self.EFF_OK & (not self.QLF_EFF_OK):\n\n # QLF_EFF_zlimit\n self.QLF_EFF_zlimit = np.unique(np.hstack((self.QLF_zlimit,\n self.EFF_zlimit)))\n\n maxQLF_EFF_zlimit = min(float(np.max(self.QLF_zlimit)),\n float(np.max(self.EFF_zlimit)))\n minQLF_EFF_zlimit = max(float(np.min(self.QLF_zlimit)),\n float(np.min(self.EFF_zlimit)))\n test = (self.QLF_EFF_zlimit >= minQLF_EFF_zlimit) & \\\n (self.QLF_EFF_zlimit <= maxQLF_EFF_zlimit)\n\n self.QLF_EFF_zlimit = self.QLF_EFF_zlimit[test]\n\n # QLF_EFFmaglimit\n self.QLF_EFF_maglimit = np.unique(\n np.hstack((self.QLF_maglimit,\n self.EFF_maglimit)))\n\n maxQLF_EFF_maglimit = min(float(np.max(self.QLF_maglimit)),\n float(np.max(self.EFF_maglimit)))\n minQLF_EFF_maglimit = max(float(np.min(self.QLF_maglimit)),\n float(np.min(self.EFF_maglimit)))\n test = (self.QLF_EFF_maglimit >= minQLF_EFF_maglimit) & \\\n (self.QLF_EFF_maglimit <= maxQLF_EFF_maglimit)\n\n self.QLF_EFF_maglimit = self.QLF_EFF_maglimit[test]\n\n xnew = self.QLF_EFF_zlimit\n ynew = self.QLF_EFF_maglimit\n\n # EFF\n x = self.EFF_zlimit.flatten()\n y = self.EFF_maglimit.flatten()\n z = self.EFF_dzdmag\n\n# ==============================================================================\n# f2d_EFF = interp2d(x, y, z, kind = 'linear',\n# copy = True, bounds_error = True)\n# interpEFF_dzdmag = f2d_EFF(xnew, ynew)\n# ==============================================================================\n\n interpXinds = np.digitize(xnew, x, right=True) - 1\n interpXinds = np.maximum(interpXinds, 0)\n\n interpYinds = np.digitize(ynew, y, right=True) - 1\n interpYinds = np.maximum(interpYinds, 0)\n\n interpXYgridInds = np.meshgrid(interpXinds, interpYinds)\n\n self.interpEFF_dzdmag = z[interpXYgridInds[1],\n interpXYgridInds[0]]\n\n # QLF\n x = self.QLF_zlimit.flatten()\n y = self.QLF_maglimit.flatten()\n z = self.QLF_Ndzdmag\n\n f2d_QLF = interp2d(x, y, z, kind='linear',\n copy=True, bounds_error=True)\n\n interpQLF_Ndzdmag = f2d_QLF(xnew, ynew)\n\n interpQLF_dNdzdmag = np.copy(interpQLF_Ndzdmag)\n interpQLF_dNdzdmag[:, 1:] -= \\\n np.copy(interpQLF_dNdzdmag[:, : -1])\n interpQLF_dNdzdmag[1:, :] -= \\\n np.copy(interpQLF_dNdzdmag[: -1, :])\n\n self.interpQLF_dNdzdmag = interpQLF_dNdzdmag\n\n interpQLF_EFF_dNdzdmag = np.zeros(self.interpQLF_dNdzdmag.shape)\n interpQLF_EFF_dNdzdmag = self.interpEFF_dzdmag * self.interpQLF_dNdzdmag\n self.interpQLF_EFF_dNdzdmag = interpQLF_EFF_dNdzdmag\n\n self.QLF_EFF_OK = True\n\n# =============================================================================\n# def ZREDComplEvalFunc(self, zlimit) :\n#\n# if self.QLF_EFF_OK:\n#\n# xnew = self.QLF_EFF_zlimit\n# assert(np.min(zlimit) >= np.min(xnew))\n# assert(np.max(zlimit) <= np.max(xnew))\n#\n# interpQLF_dNdz = np.sum(self.interpQLF_dNdzdmag, axis = 0)\n# interpQLF_Ndz = np.cumsum(interpQLF_dNdz)\n#\n# # QLF_EFF dNdz\n# interpQLF_EFF_dNdz = np.sum(self.interpQLF_EFF_dNdzdmag, axis = 0)\n# interpQLF_EFF_Ndz = np.cumsum(interpQLF_EFF_dNdz)\n#\n# f1d_QLF_EFF = interp1d(xnew, interpQLF_EFF_Ndz, kind = 'linear',\n# copy = True, bounds_error = True)\n#\n# f1d_QLF = interp1d(xnew, interpQLF_Ndz, kind = 'linear',\n# copy = True, bounds_error = True)\n#\n# self.QLF_EFF_dNdz = f1d_QLF_EFF(zlimit)\n# self.QLF_EFF_dNdz[1 :] -= np.copy(self.QLF_EFF_dNdz[: -1])\n#\n# self.QLF4Compl_dNdz = f1d_QLF(zlimit)\n# self.QLF4Compl_dNdz[1 :] -= np.copy(self.QLF4Compl_dNdz[: -1])\n#\n# self.Compl_dz = self.QLF_EFF_dNdz[1 :] / self.QLF4Compl_dNdz[1 :]\n# self.Compl_dz[np.isnan(self.Compl_dz)] = 0.\n#\n# return self.Compl_dz\n#\n# def RComplEvalFunc(self, maglimit):\n#\n# if self.QLF_EFF_OK:\n#\n# ynew = self.QLF_EFF_maglimit\n# assert(np.min(maglimit) >= np.min(ynew))\n# assert(np.max(maglimit) <= np.max(ynew))\n#\n# interpQLF_dNdmag = np.sum(self.interpQLF_dNdzdmag, axis = 1)\n# interpQLF_Ndmag = np.cumsum(interpQLF_dNdmag)\n#\n# # QLF_EFF dNdmag\n# interpQLF_EFF_dNdmag = np.sum(self.interpQLF_EFF_dNdzdmag, axis = 1)\n# interpQLF_EFF_Ndmag = np.cumsum(interpQLF_EFF_dNdmag)\n#\n# f1d_QLF_EFF = interp1d(ynew, interpQLF_EFF_Ndmag, kind = 'linear',\n# copy = True, bounds_error = True)\n#\n# f1d_QLF = interp1d(ynew, interpQLF_Ndmag, kind = 'linear',\n# copy = True, bounds_error = True)\n#\n# self.QLF_EFF_dNdmag = f1d_QLF_EFF(maglimit)\n# self.QLF_EFF_dNdmag[1 :] -= np.copy(self.QLF_EFF_dNdmag[: -1])\n#\n# self.QLF4Compl_dNdmag = f1d_QLF(maglimit)\n# self.QLF4Compl_dNdmag[1 :] -= np.copy(self.QLF4Compl_dNdmag[: -1])\n#\n# self.Compl_dmag = self.QLF_EFF_dNdmag[1 :] / self.QLF4Compl_dNdmag[1 :]\n# self.Compl_dmag[np.isnan(self.Compl_dmag)] = 0.\n#\n# return self.Compl_dmag\n# =============================================================================\n\n def R_ZREDComplEvalFunc(self, zlimit, maglimit):\n\n if self.QLF_EFF_OK:\n\n xnew = self.QLF_EFF_zlimit\n assert(np.min(zlimit) >= np.min(xnew))\n assert(np.max(zlimit) <= np.max(xnew))\n\n ynew = self.QLF_EFF_maglimit\n assert(np.min(maglimit) >= np.min(ynew))\n assert(np.max(maglimit) <= np.max(ynew))\n\n interpQLF_EFF_Ndzdmag = np.cumsum(np.cumsum(\n self.interpQLF_EFF_dNdzdmag, axis=0), axis=1)\n\n f2d_QLF_EFF = interp2d(xnew, ynew, interpQLF_EFF_Ndzdmag,\n kind='linear', copy=True,\n bounds_error=True)\n\n QLF_EFF4Compl_Ndzdmag = f2d_QLF_EFF(zlimit, maglimit)\n\n QLF_EFF4Compl_dNdzdmag = np.copy(QLF_EFF4Compl_Ndzdmag)\n QLF_EFF4Compl_dNdzdmag[:, 1:] -= \\\n np.copy(QLF_EFF4Compl_dNdzdmag[:, :-1])\n QLF_EFF4Compl_dNdzdmag[1:, :] -= \\\n np.copy(QLF_EFF4Compl_dNdzdmag[:-1, :])\n\n self.QLF_EFF4Compl_dNdzdmag = QLF_EFF4Compl_dNdzdmag\n\n # QLF\n interpQLF_Ndzdmag = np.cumsum(np.cumsum(\n self.interpQLF_dNdzdmag, axis=0), axis=1)\n\n f2d_QLF = interp2d(xnew, ynew, interpQLF_Ndzdmag,\n kind='linear', copy=True,\n bounds_error=True)\n\n QLF4Compl_Ndzdmag = f2d_QLF(zlimit, maglimit)\n\n QLF4Compl_dNdzdmag = np.copy(QLF4Compl_Ndzdmag)\n QLF4Compl_dNdzdmag[:, 1:] -= \\\n np.copy(QLF4Compl_dNdzdmag[:, :-1])\n QLF4Compl_dNdzdmag[1:, :] -= \\\n np.copy(QLF4Compl_dNdzdmag[:-1, :])\n\n self.QLF4Compl_dNdzdmag = QLF4Compl_dNdzdmag\n\n self.Compl_dzdmag = self.QLF_EFF4Compl_dNdzdmag[1:, 1:] / self.QLF4Compl_dNdzdmag[1:, 1:]\n self.Compl_dzdmag[np.isnan(self.Compl_dzdmag)] = 0.\n self.Compl_dzdmag[np.isinf(self.Compl_dzdmag)] = 0.\n\n return self.Compl_dzdmag\n\n def R_ZRED_EffVarEvalFunc(self, OBJ_QSO_dNdzdmag):\n\n self.EffVar4Compl_dzdmag = None\n\n self.Eff4Compl_dzdmag = np.copy(self.Compl_dzdmag)\n\n if True: # loi de poisson\n self.EffVar4Compl_dzdmag = self.Eff4Compl_dzdmag * (1. - self.Eff4Compl_dzdmag)\n self.EffVar4Compl_dzdmag /= OBJ_QSO_dNdzdmag\n self.EffVar4Compl_dzdmag[OBJ_QSO_dNdzdmag == 0.] = 0.\n else: # loi binomiale\n self.Count4Complt_Ndzdmag = self.Eff4Compl_dzdmag * OBJ_QSO_dNdzdmag\n self.EffVar4Compl_dzdmag = OBJ_QSO_dNdzdmag - self.Count4Complt_Ndzdmag + 1.\n self.EffVar4Compl_dzdmag *= self.Count4Complt_Ndzdmag + 1.\n self.EffVar4Compl_dzdmag /= (OBJ_QSO_dNdzdmag + 2)**2 * (OBJ_QSO_dNdzdmag + 3)\n self.EffVar4Compl_dzdmag[OBJ_QSO_dNdzdmag == 0.] = 0.\n\n return self.EffVar4Compl_dzdmag\n\n def ZRED_EffVarEvalFunc(self):\n\n self.EffVar4Compl_dz = self.EffVar4Compl_dzdmag * (self.QLF4Compl_dNdzdmag[1:, 1:])**2\n\n self.EffVar4Compl_dz = np.sum(self.EffVar4Compl_dz, axis=0)\n tmp_var = np.sum(self.QLF4Compl_dNdzdmag[1:, 1:], axis=0)**2\n self.EffVar4Compl_dz /= tmp_var\n\n self.EffVar4Compl_dz[tmp_var == 0.] = 0.\n\n return self.EffVar4Compl_dz\n\n def R_EffVarEvalFunc(self):\n\n self.EffVar4Compl_dmag = self.EffVar4Compl_dzdmag * (self.QLF4Compl_dNdzdmag[1:, 1:])**2\n\n self.EffVar4Compl_dmag = np.sum(self.EffVar4Compl_dmag, axis=1)\n tmp_var = np.sum(self.QLF4Compl_dNdzdmag[1:, 1:], axis=1)**2\n self.EffVar4Compl_dmag /= tmp_var\n\n self.EffVar4Compl_dmag[tmp_var == 0.] = 0.\n\n return self.EffVar4Compl_dmag\n", "sub_path": "py/desitarget/train/train_test_RF/util/PredCountsFromQLF_ClassModule.py", "file_name": "PredCountsFromQLF_ClassModule.py", "file_ext": "py", "file_size_in_byte": 12749, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 63, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 75, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.digitize", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 158, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp2d", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 258, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 259, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 265, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp2d", "line_number": 268, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 283, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp2d", "line_number": 286, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.isinf", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 330, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 342, "usage_type": "call"}]} +{"seq_id": "520518417", "text": "# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nfrom scipy.optimize import curve_fit\nfrom scipy.special import factorial\n\n\n# %%\ni=50\nj=1\n#Read=\"C:/Users/antoi/Desktop/Vitesse_shunt/\"+str(i)+\"_\"+str(j)+\".csv\"\nRead=\"railpropre_125_200Hz.csv\"\ndata=pd.read_csv(Read,skiprows=44).values\ndata\n\n\n# %%\nVolts=data[3:,3]\nTime=data[3:,1]\nAmps=data[3:,2]\nVolts = Volts.astype(np.float)\nTime= Time.astype(np.float)\nAmps= Amps.astype(np.float)\n\n\n# %%\n#print('Volts ='+'[' +\", \".join([str(x) for x in Volts])+']')\n\n\n# %%\nVoltsNorm=(Volts>0.6)*1\n\n# %% [markdown]\n# # Statistique \n\n# %%\nplt.figure(figsize=(10,5))\nplt.scatter(Time,Volts,linewidth=1)\nlen(Volts)\n\n\n# %%\n#Volts=Volts[50:900]\n#Time=Time[50:900]\n\n# %% [markdown]\n# ## Trouver les points où le déshuntage commence\n\n# %%\nfor i in np.arange(0,len(Volts),1):\n if Volts[i] < 0.2:\n First=i\n break;\n \nfor i in np.flip(np.arange(0,len(Volts),1)):\n if Volts[i] < 0.2:\n Last=i\n break;\n\n\n# %%\nVolts=Volts[First:Last]\nTime=Time[First:Last]\nplt.figure(figsize=(10,5))\nplt.plot(Time,Volts,linewidth=1)\n\n\n# %%\nLast\n\n# %% [markdown]\n# # Plot de la distribution\n\n# %%\nMax=np.max(Volts)\nMin=0\nPas=0.005\nBalayage=np.arange(Min,Max+Pas,Pas)\nBalayage\n\n\n# %%\nNombre=np.zeros(len(Balayage)-1)\nVoltsHist=np.zeros(len(Balayage)-1)\nfor i in np.arange(0,len(Balayage)-1,1):\n A=(Volts>Balayage[i])*1\n B=(Volts', views.detail.as_view(), name ='detalle'),\n# path('/resulado/', views.results.as_view(), name ='resultado'),\n# path('/votar/', views.vote, name ='votar'),\n \n# ]\n\n# cambiando a vistas basaadas en clases\n\n\n\nurlpatterns = [\n\n path('indice/', views.index, name ='indice'),\n path('detalle/', views.detail, name ='detalle'),\n path('/votar/', views.vote, name ='votar'),\n path('/resulado/', views.results, name ='resultado'),\n \n \n \n path('contacto/', views.contacto, name='contacto'), \n path('crear_articulo/', views.CrearArticulo.as_view(), name='CrearArticulo')\n\n\n# creando otras vistas para ver ejemplo carro de comparas\n\n \n ]\n\n", "sub_path": "gestionPedidos/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 940, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "gestionPedidos.views.index", "line_number": 23, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "gestionPedidos.views.detail", "line_number": 24, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "gestionPedidos.views.vote", "line_number": 25, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "gestionPedidos.views.results", "line_number": 26, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 26, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "gestionPedidos.views.contacto", "line_number": 30, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "gestionPedidos.views.CrearArticulo.as_view", "line_number": 31, "usage_type": "call"}, {"api_name": "gestionPedidos.views.CrearArticulo", "line_number": 31, "usage_type": "attribute"}, {"api_name": "gestionPedidos.views", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "238696984", "text": "# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport re\nfrom PIL import Image\n\nif __name__ == '__main__':\n xmlfolderpath = \"./annotations/\"\n\n imgfilepath = \"./images/\"\n\n\n outputxmlpath=xmlfolderpath+'output/'\n #os.makedirs(outputxmlpath, exist_ok=True)\n\n xmlfiles = [ x.split(\".\")[0] for x in sorted(os.listdir(xmlfolderpath)) if x!=\".DS_Store\" and x!=\"output\"]\n imgfiles = [ x.split(\".\")[0] for x in sorted(os.listdir(imgfilepath)) if x!=\".DS_Store\"]\n imgfiles_exts=[ x.split(\".\")[-1] for x in sorted(os.listdir(imgfilepath)) if x!=\".DS_Store\"]\n\n #print(xmlfiles)\n #print(imgfiles)\n print(\"##################### check xml files\")\n for i,xmlfilename in enumerate(xmlfiles):\n if not xmlfilename in imgfiles:\n print( \"Error: \"+xmlfilename+ \".png/jpg are not found. Please search it, or delete \"+xmlfilename+\".png/jpg\")\n #######\n with open(xmlfolderpath+xmlfilename+\".xml\") as f:\n rawfile = f.read()\n #print(xmlfilename)\n #print(rawfile)\n #print(re.findall(\"\\d{1,4}\",rawfile))\n #print(re.findall(\"\\d{1,4}\",rawfile))\n if len(re.findall(\"\\d{1,4}\",rawfile))==0:\n print(\"ERROR: xml file exists, but No anottation on \",xmlfilename)\n width=int(re.sub(r\"\\D\", \"\", re.findall(\"\\d{1,4}\",rawfile)[0]) )\n height=int( re.sub(r\"\\D\", \"\", re.findall(\"\\d{1,4}\",rawfile)[0]) )\n xmax=int(re.sub(r\"\\D\", \"\", re.findall(\"\\d{1,4}\",rawfile)[0]) )\n ymax=int(re.sub(r\"\\D\", \"\", re.findall(\"\\d{1,4}\",rawfile)[0]) )\n if width.*\",rawfile)[0]\n\n ######### filename の変更\n rawfile=re.sub(r\".png\",r\".jpg\",rawfile)\n ######### の削除\n rawfile=re.sub(r\".*\",\"\",rawfile)\n im = Image.open(imgfilepath+xmlfilename+\".\"+imgfiles_exts[i])\n img_width=int(im.size[0])\n img_height=int(im.size[1])\n\n if width!=img_width:\n print(\"different width ({0},{1}): {2}\".format(width,img_width,imgfilepath+xmlfilename) )\n if height!=img_height:\n print(\"different height ({0},{1}): {2}\".format(height,img_height,imgfilepath+xmlfilename) )\n\n # ファイルの書き込み\n # with open(outputxmlpath+xmlfilename+\".xml\",mode='w') as f:\n # f.write(rawfile)\n\n\n print(\"##################### check img files\")\n for i,imgfilename in enumerate(imgfiles):\n if not imgfilename in xmlfiles:\n print(\"Error: No annotation file. \" + imgfilename + \".\"+imgfiles_exts[i]+ \" will be deleted, [y/n] \")\n ans=input()\n if ans!=\"n\":\n print(imgfilepath+imgfilename+\".\"+imgfiles_exts[i]+\" is deleted.\")\n os.remove( imgfilepath+imgfilename+\".\"+imgfiles_exts[i] )\n\n else:\n print(imgfilepath + imgfilename+\".\"+imgfiles_exts[i] + \" is not deleted.\")\n", "sub_path": "check_imgandxml.py", "file_name": "check_imgandxml.py", "file_ext": "py", "file_size_in_byte": 3168, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 17, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 19, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 34, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 36, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 36, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 37, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 37, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 38, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 38, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 39, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 39, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 44, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 47, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 49, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 50, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 50, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "318964789", "text": "\r\nimport numpy as np\r\nimport sounddevice as sd\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.fftpack import fft\r\nfrom scipy import signal as window\r\nimport suaBibSignal as sig\r\n\r\n\r\n\r\nclass signalMeu:\r\n\r\n def __init__(self):\r\n self.init = 0\r\n\r\n def generateSin(self, freq, amplitude, time, fs):\r\n n = time*fs\r\n x = np.linspace(0.0, time, n)\r\n s = amplitude*np.sin(freq*x*2*np.pi)\r\n return (x, s)\r\n\r\n def calcFFT(self, signal, fs):\r\n # https://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html\r\n N = len(signal)\r\n W = window.hamming(N)\r\n T = 1/fs\r\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\r\n yf = fft(signal*W)\r\n return(xf, np.abs(yf[0:N//2]))\r\n\r\n def plotFFT(self, signal, fs):\r\n x,y = self.calcFFT(signal, fs)\r\n plt.figure()\r\n plt.plot(x, np.abs(y))\r\n plt.title('Fourier')\r\n \r\n def makeTone(self, input):\r\n\r\n freqDeAmostragem = 44100\r\n\r\n duration = 5\r\n\r\n gainX = 0.2\r\n gainY = 0.2\r\n\r\n s1209 = self.generateSin(1209, gainY, duration,freqDeAmostragem)\r\n s1336 = self.generateSin(1336, gainY, duration,freqDeAmostragem)\r\n s1477 = self.generateSin(1477, gainY, duration,freqDeAmostragem)\r\n s1633 = self.generateSin(1633, gainY, duration,freqDeAmostragem)\r\n s697 = self.generateSin(697, gainY, duration,freqDeAmostragem)\r\n s770 = self.generateSin(770, gainY, duration,freqDeAmostragem)\r\n s852 = self.generateSin(852, gainY, duration,freqDeAmostragem)\r\n s941 = self.generateSin(941, gainY, duration,freqDeAmostragem)\r\n\r\n if input == '1':\r\n return s1209[1]+s697[1],s1209,s697\r\n\r\n elif input == '2':\r\n return s1336[1]+s697[1],s1336,s697\r\n\r\n elif input == '3':\r\n return s1477[1]+s697[1],s1477,s697\r\n\r\n elif input == '4':\r\n return s1209[1]+s770[1],s1209,s770\r\n\r\n elif input == '5':\r\n return s1336[1]+s770[1],s1336,s770\r\n\r\n elif input == '6':\r\n return s1477[1]+s770[1],s1477,s770\r\n\r\n elif input == '7':\r\n return s1209[1]+s852[1],s1209,s852\r\n\r\n elif input == '8':\r\n return s1336[1]+s852[1],s1336,s852\r\n\r\n elif input == '9':\r\n return s1477[1]+s852[1],s1477,s852\r\n\r\n elif input == '0':\r\n return s1336[1]+s941[1],s1336,s941\r\n\r\n elif input == 'X':\r\n return s1209[1]+s941[1],s1209,s941\r\n\r\n elif input == '#':\r\n return s1477[1]+s941[1],s1477,s941\r\n\r\n elif input == 'A':\r\n return s1633[1]+s697[1],s1633,s697\r\n\r\n elif input == 'B':\r\n return s1633[1]+s770[1],s1633,s770\r\n\r\n elif input == 'C':\r\n return s1633[1]+s852[1],s1633,s852\r\n\r\n elif input == 'D':\r\n return s1633[1]+s941[1],s1633,s941\r\n\r\n\r\n", "sub_path": "P7/suaBibSignal.py", "file_name": "suaBibSignal.py", "file_ext": "py", "file_size_in_byte": 2886, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.linspace", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 19, "usage_type": "attribute"}, {"api_name": "scipy.signal.hamming", "line_number": 25, "usage_type": "call"}, {"api_name": "scipy.signal", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 27, "usage_type": "call"}, {"api_name": "scipy.fftpack.fft", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}]} +{"seq_id": "551750607", "text": "import asyncio\nfrom pytrade import login, client\n\nsteam_cli = login.AsyncClient('name', 'pass', shared_secret=\"secret\")\nmanager = client.TradeManager('steam 64 id', key='apikey', identity_secret=\"your other secret\")\n\n# This will be called, when it completes the client.login\n@manager.on('logged_on')\nasync def login():\n print('Logged in!')\n\n# On a new trade, this will be called. an EconTradeOffer.TradeOffer object will be passed in\n@manager.on('new_trade')\nasync def new_offer(trade_offer):\n print(f\"Got Offer: {trade_offer.tradeofferid}\")\n if trade_offer.steamid_other.toString() == manager.steamid.toString():\n print(\"This offer is from us! Accepting\")\n await trade_offer.accept()\n else:\n print(\"Not from us, declining\")\n await trade_offer.decline()\n\n# This is called at the end of polling\n@manager.on('end_poll')\nasync def poll_end():\n print(\"Poll ended.\")\n\n# This is called at the start of polling\n@manager.on('start_poll')\nasync def poll_start():\n print(\"Poll started\")\n\n# This is called when a trade is accepted\n@manager.on('trade_accepted')\nasync def accepted_offer(trade_offer):\n print(f\"Accepted Offer: {trade_offer.tradeofferid}\")\n\n# This is the basic setup for the program, and it will run forever. Currently, there is no \"nice\" way to end it.\nloop = asyncio.get_event_loop()\nloop.run_until_complete(asyncio.ensure_future(manager.login(steam_cli)))\nmanager.run_forever()", "sub_path": "example.py", "file_name": "example.py", "file_ext": "py", "file_size_in_byte": 1432, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pytrade.login.AsyncClient", "line_number": 4, "usage_type": "call"}, {"api_name": "pytrade.login", "line_number": 4, "usage_type": "name"}, {"api_name": "pytrade.client.TradeManager", "line_number": 5, "usage_type": "call"}, {"api_name": "pytrade.client", "line_number": 5, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 39, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "250126490", "text": "import math\nimport matplotlib.pyplot as plt\n\nx_T = [100, 110, 120, 129, 140, 149, 158, 168, 179, 188, 198, 209, 219, 226, 234, 240]\ny_T = [0, 3, 6, 10, 15, 20, 26, 32, 37, 34, 30, 27, 23, 19, 16, 14]\nx_D = [0]\ny_D = [60]\nv_D = 20\ndist_TD = []\nfor t in range(13):\n print(\"time t = \", t)\n dist_TD.append(math.sqrt(((x_T[t] - x_D[t]) ** 2) + ((y_T[t] - y_D[t]) ** 2))) #distance calculation at time t\n sin = (y_T[t] - y_D[t]) / dist_TD[t]\n cos = (x_T[t] - x_D[t]) / dist_TD[t]\n x_dNew = x_D[t] + v_D * cos\n y_dNew = y_D[t] + v_D * sin\n x_D.append(x_dNew)\n y_D.append(y_dNew)\n #dist_update =\n print(dist_TD[t])\n if dist_TD[t] <10:\n print(\"Booom!!\")\n break\n\n\n# multiline plot\n# plotting the points\nplt.plot(x_T, y_T, label=\"Target\")\nplt.plot(x_D, y_D, label=\"Defender\")\n# naming the x axis\nplt.xlabel('x axis')\n# naming the y axis\nplt.ylabel('y axis')\nplt.legend()\nplt.show()\n\n# scatter plot\nplt.scatter(x_T, y_T, label=\"Target\")\nplt.scatter(x_D, y_D, label=\"Defender\")\nplt.legend()\nplt.show()", "sub_path": "lab_4/pursuit_problem.py", "file_name": "pursuit_problem.py", "file_ext": "py", "file_size_in_byte": 1036, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "math.sqrt", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}]} +{"seq_id": "114944266", "text": "from Utils import *\n\nfolder = 'waveform_data'\ndf = pd.DataFrame( columns = [ 'Filename', 'Liv_1', 'Liv_2', 'Liv_3', 'dim'])\n\nfor root, dirs, files in os.walk(folder):\n for filename in files:\n if filename.endswith((\".hdf5\")):\n print(filename)\n # create_dir( folder + '/' + filename )\n f = h5py.File( folder + '/' + filename, 'r')\n liv_1 = list( f.keys())\n for l in liv_1:\n data = f[ l ]\n liv_2 = list(data.keys())\n for ch in liv_2:\n data[ ch ].keys()\n liv_3 = list(data[ ch ].keys())\n for trg in liv_3:\n df = df.append( {'Filename': filename, 'Liv_1': l, 'Liv_2':ch, 'Liv_3': trg,\n 'dim': len(data[ ch ][ trg ].value)}, ignore_index=True)\ndf.to_csv('file_description.csv')\n\n\n# primo plot\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-whitegrid')\n#\n\ny= data[b][c].value\nx = range(len(y))\nmax(y)\nmin(y)\nnp.mean(y)\n# print(x)\nplt.plot(x, y, color='black');\nplt.show()\n\n\n# Plot di tutti i dati, non molto utile\nfor b in liv_2:\n for c in liv_3:\n y=data[b][c].value\n x=range(len(y))\n plt.plot(x,y, color='black')\n plt.show()", "sub_path": "data_extraction_and_plotting.py", "file_name": "data_extraction_and_plotting.py", "file_ext": "py", "file_size_in_byte": 1286, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 27, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}]} +{"seq_id": "160346697", "text": "import logging\n\nfrom app.service import AppService\n\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# create console handler and set level to debug\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# add formatter to ch\nch.setFormatter(formatter)\n\n# add ch to logger\nlogger.addHandler(ch)\n\n\ndef main():\n content = AppService.get_content_from_url()\n json = AppService.xml_to_json(content)\n logger.info(\"Result: %s\", json)\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 601, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 7, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 11, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 13, "usage_type": "call"}, {"api_name": "app.service.AppService.get_content_from_url", "line_number": 23, "usage_type": "call"}, {"api_name": "app.service.AppService", "line_number": 23, "usage_type": "name"}, {"api_name": "app.service.AppService.xml_to_json", "line_number": 24, "usage_type": "call"}, {"api_name": "app.service.AppService", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "263901548", "text": "from collections import defaultdict\nimport numpy as np\nfrom copy import deepcopy\n\nfrom cascade_at.settings.settings_config import SettingsConfig\nfrom cascade_at.dismod.integrand_mappings import INTEGRAND_MAP\n\n\nCASCADE_LEVEL_ID = ['most_detailed']\n\n\ndef measures_to_exclude_from_settings(settings: SettingsConfig):\n \"\"\"\n Gets the measures to exclude from the data from the model\n settings configuration.\n \"\"\"\n if not settings.model.is_field_unset(\"exclude_data_for_param\"):\n measures_to_exclude = [\n INTEGRAND_MAP[m].name\n for m in settings.model.exclude_data_for_param\n if m in INTEGRAND_MAP]\n else:\n measures_to_exclude = list()\n if settings.policies.exclude_relative_risk:\n measures_to_exclude.append(\"relrisk\")\n return measures_to_exclude\n\n\ndef data_eta_from_settings(settings: SettingsConfig, default: float = np.nan):\n \"\"\"\n Gets the data eta from the settings Configuration.\n The default data eta is np.nan.\n \"\"\"\n data_eta = defaultdict(lambda: default)\n if not settings.eta.is_field_unset(\"data\") and settings.eta.data:\n data_eta = defaultdict(lambda: float(settings.eta.data))\n for set_eta in settings.data_eta_by_integrand:\n data_eta[INTEGRAND_MAP[set_eta.integrand_measure_id].name] = float(set_eta.value)\n return data_eta\n\n\ndef density_from_settings(settings: SettingsConfig, default: str = \"gaussian\"):\n \"\"\"\n Gets the density from the settings Configuration.\n The default density is \"gaussian\".\n \"\"\"\n density = defaultdict(lambda: default)\n if not settings.model.is_field_unset(\"data_density\") and settings.model.data_density:\n density = defaultdict(lambda: settings.model.data_density)\n for set_density in settings.data_density_by_integrand:\n density[INTEGRAND_MAP[set_density.integrand_measure_id].name] = set_density.value\n return density\n\n\ndef data_cv_from_settings(settings: SettingsConfig, default: float = 0.0):\n \"\"\"\n Gets the data min coefficient of variation from the settings Configuration\n\n Args:\n settings: (cascade.settings.configuration.Configuration)\n default: (float) default data cv\n\n Returns:\n dictionary of data cv's from settings\n \"\"\"\n data_cv = defaultdict(lambda: default)\n if not settings.model.is_field_unset(\"minimum_meas_cv\") and settings.model.minimum_meas_cv:\n data_cv = defaultdict(\n lambda: float(settings.model.minimum_meas_cv))\n for set_data_cv in settings.data_cv_by_integrand:\n data_cv[INTEGRAND_MAP[\n set_data_cv.integrand_measure_id].name] = float(\n set_data_cv.value)\n return data_cv\n\n\ndef min_cv_from_settings(settings: SettingsConfig, default: float = 0.0) -> defaultdict:\n \"\"\"\n Gets the minimum coefficient of variation by rate and level\n of the cascade from settings.\n \"\"\"\n # This is a hack to over-ride the default value while the visualization\n # team is fixing the bug in the cascade level drop-down menu.\n if not settings.is_field_unset(\"min_cv\") and settings.min_cv:\n cascade_levels = [cv.cascade_level_id for cv in settings.min_cv]\n values = [cv.value for cv in settings.min_cv]\n if \"most_detailed\" in cascade_levels:\n default = values[cascade_levels.index(\"most_detailed\")]\n inner = defaultdict(lambda: default)\n outer = defaultdict(lambda: deepcopy(inner))\n\n if not settings.is_field_unset(\"min_cv\") and settings.min_cv:\n for cv in settings.min_cv:\n # The following lambda function is the only way to get the defaultdict\n # creation to work within a loop. It does *not* work if you only do\n # defaultdict(lambda: cv.value). As you go through the iterations, it just\n # pulls in the current value for cv because lambda functions can't go back in time.\n outer.update({cv.cascade_level_id: defaultdict(lambda val=cv.value: val)})\n if not settings.is_field_unset(\"min_cv_by_rate\") and settings.min_cv_by_rate:\n for rate_cv in settings.min_cv_by_rate:\n outer[rate_cv.cascade_level_id].update({rate_cv.rate_measure_id: rate_cv.value})\n return outer\n\n\ndef nu_from_settings(settings: SettingsConfig, default: float = np.nan):\n \"\"\"\n Gets nu from the settings Configuration.\n The default nu is np.nan.\n \"\"\"\n nu = defaultdict(lambda: default)\n nu[\"students\"] = settings.students_dof.data\n nu[\"log_students\"] = settings.log_students_dof.data\n return nu\n", "sub_path": "src/cascade_at/settings/convert.py", "file_name": "convert.py", "file_ext": "py", "file_size_in_byte": 4526, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 12, "usage_type": "name"}, {"api_name": "cascade_at.dismod.integrand_mappings.INTEGRAND_MAP", "line_number": 19, "usage_type": "name"}, {"api_name": "cascade_at.dismod.integrand_mappings.INTEGRAND_MAP", "line_number": 21, "usage_type": "name"}, {"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 29, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 29, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 36, "usage_type": "call"}, {"api_name": "cascade_at.dismod.integrand_mappings.INTEGRAND_MAP", "line_number": 38, "usage_type": "name"}, {"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 42, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 47, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 49, "usage_type": "call"}, {"api_name": "cascade_at.dismod.integrand_mappings.INTEGRAND_MAP", "line_number": 51, "usage_type": "name"}, {"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 55, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 66, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 68, "usage_type": "call"}, {"api_name": "cascade_at.dismod.integrand_mappings.INTEGRAND_MAP", "line_number": 71, "usage_type": "name"}, {"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 77, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 89, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 90, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 90, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 98, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 77, "usage_type": "name"}, {"api_name": "cascade_at.settings.settings_config.SettingsConfig", "line_number": 105, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 105, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 110, "usage_type": "call"}]} +{"seq_id": "603752275", "text": "import aioredis\nimport asyncio\nimport collections\nimport logging\n\nlog = logging.getLogger(__name__)\n\nBanEntry = collections.namedtuple('BanEntry', 'guild_id user_id reason')\n\n\nclass BanStorage:\n \"\"\"An interface for access store all of the bans seen by the bot.\n\n This information is transitive and is never written to disc.\n Implemented as a Redis mapping:\n - Key: \"ban:{user_id}:{guild_id}\"\n - Value: Ban Reason. Empty string if None.\n - Timeout: Constant provided at initialization.\n \"\"\"\n\n def __init__(self, bot, timeout=300):\n self.storage = bot.storage\n self.timeout = timeout\n\n @property\n def redis(self):\n return self.storage.redis\n\n async def save_all_bans(self, bot):\n \"\"\"Saves all bans for every guild a bot is in to the store.\"\"\"\n await asyncio.gather(*[self.save_bans(guild) for guild in bot.guilds])\n\n async def save_bans(self, guild):\n \"\"\"Atomically saves all of the bans for a given guild to the backng\n store.\n \"\"\"\n if not guild.me.guild_permissions.ban_members:\n return\n bans = await guild.bans()\n\n if len(bans) <= 0:\n return\n\n mapping = {(guild.id, ban.user.id): ban.reason or ''\n for ban in bans}\n await self.storage.bans.set_all(mapping)\n\n async def save_ban(self, guild_id, user_id, reason):\n await self.storage.bans.set((guild_id, user_id), reason or '')\n\n async def get_bans(self, user_id, guild_ids):\n \"\"\"Gets the ban information for a given user for a set of guilds.\n Returns: an async generator of BanEntry objects.\n \"\"\"\n try:\n keys = ((guild_id, user_id) for guild_id in guild_ids)\n results = await self.storage.bans.get_all(keys)\n return [BanEntry(guild_id=key[0], user_id=key[1],\n reason=value if value != '' else None)\n for key, value in results.items() if value is not None]\n except aioredis.MultiExecError:\n log.exception('Failure in fetching bans:')\n raise\n\n async def clear_ban(self, guild, user):\n \"\"\"Clears a ban from the storage.\n Params:\n guild_id [int] - The guild ID.\n user_id [int] - The user ID.\n \"\"\"\n await self.storage.bans.clear((guild.id, user.id))\n", "sub_path": "hourai/extensions/validation/storage.py", "file_name": "storage.py", "file_ext": "py", "file_size_in_byte": 2387, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 8, "usage_type": "call"}, {"api_name": "asyncio.gather", "line_number": 31, "usage_type": "call"}, {"api_name": "aioredis.MultiExecError", "line_number": 61, "usage_type": "attribute"}]} +{"seq_id": "62576202", "text": "from neo4j import GraphDatabase\nfrom dotenv import load_dotenv\nimport os\nimport pymongo\n\nload_dotenv()\n\n\ndriver = GraphDatabase.driver(\"bolt://%s:7687\" % os.getenv(\"NEO_URL\"), encrypted=False)\n\n\ndef make_query(symbol: str, sd: float, expected_returns: float, beta: float, alpha: float):\n return \"MERGE (:Company {symbol: '%s', sd: %f, expected_returns: %f, beta: %f, alpha: %f})\" % \\\n (symbol, sd, expected_returns, beta, alpha)\n\n\ndef init_neo4j():\n mongo_client = pymongo.MongoClient(\"localhost\", 27017) # Connect to MongoDB\n db = mongo_client.stocks # Nom database\n collection = db.stock\n elems = collection.find()\n\n with driver.session() as session:\n try:\n session.run(\"CREATE CONSTRAINT ON (c: Company) ASSERT c.symbol IS UNIQUE\")\n except:\n pass\n for elem in elems:\n del elem[\"_id\"]\n del elem[\"data\"]\n query = make_query(**elem)\n print(query)\n session.run(query)\n\n\ninit_neo4j()\n", "sub_path": "src/init_neo4j.py", "file_name": "init_neo4j.py", "file_ext": "py", "file_size_in_byte": 1010, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 6, "usage_type": "call"}, {"api_name": "neo4j.GraphDatabase.driver", "line_number": 9, "usage_type": "call"}, {"api_name": "neo4j.GraphDatabase", "line_number": 9, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 9, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "10177217", "text": "import pickle\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom vecstack import stacking\n\nfeatures = [\"career\", \"educ\", \"it_descr\", \"it_group_prop\", \"it_group_count\", \"it_post_count\", \"it_post_prop\", \"site\",\n \"tight_post\", \"y\"]\n\npath_label0_xlsx = \"data/label_data_0.xlsx\"\ndf_label_0 = pd.read_excel(path_label0_xlsx)\n\npath_base1 = \"data/Base1.xlsx\"\ndf_base = pd.read_excel(path_base1)\n\npath_non_prog = \"data/non_prog_parsed.xlsx\"\ndf_non = pd.read_excel(path_non_prog)\n\ndf_base = df_base.loc[:1000, features]\ndf_base.reset_index(inplace=True, drop=True)\n\ndf_non = df_non.loc[:, features]\ndf_label_0 = df_label_0.loc[:, features]\n\ndf = pd.concat([df_base, df_label_0, df_non], ignore_index=True)\n\nX, y = df.drop('y', axis=1).values, df['y'].values\nX_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, test_size=0.25)\n\npath_to_models = ['catbst', 'rf_new', 'rf_new1', 'rf_new', 'xgb_new', 'xgb_new1', 'xgb_new1_XY']\npath_to_models = list(map(lambda x: 'models/' + x, path_to_models))\nmodels = [pickle.load(open(name, 'rb')) for name in path_to_models]\n\nS_train, S_test = stacking(models, X_train, y_train, X_test,\n regression=False,\n mode='oof_pred_bag',\n needs_proba=False,\n save_dir=None,\n metric=accuracy_score,\n n_folds=5,\n stratified=True,\n shuffle=True,\n verbose=2)\nfor model in models:\n model = model.fit(S_train, y_train)\n y_pred = model.predict(S_test)\n print('Accuracy: {}'.format(accuracy_score(y_test, y_pred)))\n", "sub_path": "models/stacking/stack.py", "file_name": "stack.py", "file_ext": "py", "file_size_in_byte": 1766, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.read_excel", "line_number": 11, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 25, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 28, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 32, "usage_type": "call"}, {"api_name": "vecstack.stacking", "line_number": 34, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 39, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "331988584", "text": "from bs4 import BeautifulSoup\nimport requests\n\nfrom timer import timing\n\n@timing\ndef Search(item):\n url = \"https://www.runelocus.com/tools/rs-item-id-list/?search=\"+str(item) \n source = requests.get(url).text\n soup = BeautifulSoup(source, 'lxml')\n return soup\n\nSearch(\"pickaxe\")", "sub_path": "test_2.py", "file_name": "test_2.py", "file_ext": "py", "file_size_in_byte": 290, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 10, "usage_type": "call"}, {"api_name": "timer.timing", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "444008833", "text": "from django.urls import path\nfrom .views import CampanhasList, CampanhaEdit, CampanhaDelete, CampanhaNovo\n\nurlpatterns = [\n path('', CampanhasList.as_view(), name='list_campanhas'),\n path('editar/', CampanhaEdit.as_view(), name='update_campanha'),\n path('delete/', CampanhaDelete.as_view(), name='delete_campanha'),\n path('novo', CampanhaNovo.as_view(), name='create_campanha'),\n\n]\n", "sub_path": "apps/campanhas/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 410, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "views.CampanhasList.as_view", "line_number": 5, "usage_type": "call"}, {"api_name": "views.CampanhasList", "line_number": 5, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "views.CampanhaEdit.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "views.CampanhaEdit", "line_number": 6, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "views.CampanhaDelete.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "views.CampanhaDelete", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "views.CampanhaNovo.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "views.CampanhaNovo", "line_number": 8, "usage_type": "name"}]} +{"seq_id": "87903360", "text": "#!/usr/bin/env python\n\nfrom flask import make_response, request, render_template, send_file, Response\nfrom flask.views import MethodView\nfrom werkzeug.utils import secure_filename\nimport os\nimport re\nimport json\nimport mimetypes\nfrom uuid import uuid4\nimport shutil\nimport hashlib\n\nimport prepare_app as prep\nimport operations\nfrom decorators import path_operation\nfrom trigger_actions import actions\n\n\nCHUNKSIZE = 1 << 20\n\n\ndef partial_response(path, start, end=None):\n file_size = os.path.getsize(path)\n\n if end is None:\n end = file_size - start - 1\n end = min(end, file_size - 1)\n length = end - start + 1\n\n with open(path, 'rb') as fd:\n fd.seek(start)\n _bytes = fd.read(length)\n assert len(_bytes) == length\n\n response = Response(\n _bytes,\n 206,\n mimetype=mimetypes.guess_type(path)[0],\n direct_passthrough=True,\n )\n response.headers.add(\n 'Content-Range', f'bytes {start}-{end}/{file_size}'\n )\n response.headers.add(\n 'Accept-Ranges', 'bytes'\n )\n return response\n\n\ndef get_range(request):\n range = request.headers.get('Range')\n m = re.match(r'bytes=(?P\\d+)-(?P\\d+)?', range)\n if m:\n start = m.group('start')\n end = m.group('end')\n start = int(start)\n if end is not None:\n end = int(end)\n return start, end\n else:\n return 0, None\n\n\nclass PathView(MethodView):\n\n @path_operation()\n def get(self, path):\n if path.is_dir():\n res = self._get_dir(path)\n elif path.is_file():\n if 'Range' in request.headers:\n start, end = get_range(request)\n res = partial_response(path, start, end)\n else:\n res = send_file(path)\n res.headers.add('Content-Disposition', 'attachment')\n else:\n res = make_response('Not found', 404)\n return res\n\n def _get_dir(self, path):\n hide_dotfile = request.args.get('hide-dotfile', request.cookies.get('hide-dotfile', 'no'))\n contents = []\n total = {'size': 0, 'dir': 0, 'file': 0}\n for filename in os.listdir(path):\n if filename in prep.ignored:\n continue\n if hide_dotfile == 'yes' and filename.startswith('.'):\n continue\n filepath = path / filename\n stat_res = filepath.stat()\n info = {}\n info['name'] = filename\n info['mtime'] = stat_res.st_mtime\n ft = 'dir' if filepath.is_dir() else 'file'\n info['type'] = ft\n total[ft] += 1\n sz = stat_res.st_size\n info['size'] = sz\n total['size'] += sz\n contents.append(info)\n context = dict(paths=self.paths, contents=contents, total=total)\n page = render_template('index.html', **context)\n res = make_response(page, 200)\n # res.set_cookie('hide-dotfile', hide_dotfile, max_age=16070400)\n # TODO: answer json if json was requested\n return res\n\n def _save_file(self, fileobj, target_path):\n actions.before_upload(target_path)\n\n temppath = prep.store / str(uuid4())\n md5 = hashlib.md5()\n\n with open(temppath, 'wb') as output:\n while True:\n data = fileobj.read(CHUNKSIZE)\n if not data:\n break\n md5.update(data)\n actions.on_chunk(data, target_path)\n output.write(data)\n\n storepath = prep.store / md5.hexdigest()\n temppath.rename(storepath)\n target_path.symlink_to(storepath)\n\n actions.after_upload(target_path)\n\n @path_operation(authenticate=True, mkdirs=True)\n def put(self, path):\n result_code = 201\n info = {'status': 'success', 'msg': 'File Saved'}\n\n try:\n filename = secure_filename(path.name)\n self._save_file(request.stream, self.dir_path / filename)\n except Exception as e:\n info['status'] = 'error'\n info['msg'] = str(e)\n result_code = 500\n\n res = make_response(json.dumps(info), result_code)\n res.headers.add('Content-type', 'application/json')\n return res\n\n @path_operation(authenticate=True, mkdirs=True, path_is_folder=True)\n def post(self, path):\n result_code = 201\n info = {'status': 'success', 'msg': 'File Saved'}\n\n files = request.files.getlist('files[]')\n for file in files:\n try:\n filename = secure_filename(file.filename)\n self._save_file(file, path / filename)\n except Exception as e:\n info['status'] = 'error'\n info['msg'] = f\"{filename}: {e}\"\n result_code = 500\n\n res = make_response(json.dumps(info), result_code)\n res.headers.add('Content-type', 'application/json')\n return res\n\n @path_operation(authenticate=True, check_dir=True)\n def delete(self, path):\n result_code = 204\n info = {'status': 'success', 'msg': 'File Deleted'}\n\n try:\n filename = secure_filename(path.name)\n filepath = self.dir_path / filename\n if filepath.is_dir():\n shutil.rmtree(filepath)\n elif filepath.is_file():\n filepath.unlink()\n else:\n result_code = 404\n info = {'status': 'failure', 'msg': 'Not Found'}\n except Exception as e:\n info['status'] = 'error'\n info['msg'] = str(e)\n result_code = 500\n\n res = make_response(json.dumps(info), result_code)\n res.headers.add('Content-type', 'application/json')\n return res\n\n\napp = prep.app\npath_view = PathView.as_view('path_view')\napp.register_blueprint(operations.api)\napp.add_url_rule('/', view_func=path_view)\n# /favicon.ico\napp.add_url_rule('//', view_func=path_view)\n\nif __name__ == '__main__':\n bind = os.getenv('FS_BIND', '0.0.0.0')\n port = os.getenv('FS_PORT', '8000')\n app.run(bind, port, threaded=True, debug=False)\n", "sub_path": "file_server.py", "file_name": "file_server.py", "file_ext": "py", "file_size_in_byte": 6144, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.getsize", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.Response", "line_number": 36, "usage_type": "call"}, {"api_name": "mimetypes.guess_type", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 52, "usage_type": "name"}, {"api_name": "re.match", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.views.MethodView", "line_number": 65, "usage_type": "name"}, {"api_name": "flask.request.headers", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 73, "usage_type": "argument"}, {"api_name": "flask.send_file", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 79, "usage_type": "call"}, {"api_name": "decorators.path_operation", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "flask.request.cookies.get", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.cookies", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 86, "usage_type": "call"}, {"api_name": "prepare_app.ignored", "line_number": 87, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 105, "usage_type": "call"}, {"api_name": "trigger_actions.actions.before_upload", "line_number": 111, "usage_type": "call"}, {"api_name": "trigger_actions.actions", "line_number": 111, "usage_type": "name"}, {"api_name": "prepare_app.store", "line_number": 113, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 113, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 114, "usage_type": "call"}, {"api_name": "trigger_actions.actions.on_chunk", "line_number": 122, "usage_type": "call"}, {"api_name": "trigger_actions.actions", "line_number": 122, "usage_type": "name"}, {"api_name": "prepare_app.store", "line_number": 125, "usage_type": "attribute"}, {"api_name": "trigger_actions.actions.after_upload", "line_number": 129, "usage_type": "call"}, {"api_name": "trigger_actions.actions", "line_number": 129, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 137, "usage_type": "call"}, {"api_name": "flask.request.stream", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 138, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 144, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 144, "usage_type": "call"}, {"api_name": "decorators.path_operation", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.request.files.getlist", "line_number": 153, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 153, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 153, "usage_type": "name"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 163, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 163, "usage_type": "call"}, {"api_name": "decorators.path_operation", "line_number": 148, "usage_type": "call"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 173, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 187, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 187, "usage_type": "call"}, {"api_name": "decorators.path_operation", "line_number": 167, "usage_type": "call"}, {"api_name": "prepare_app.app", "line_number": 192, "usage_type": "attribute"}, {"api_name": "operations.api", "line_number": 194, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 200, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 201, "usage_type": "call"}]} +{"seq_id": "613062252", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 26 09:57:02 2019\r\n\r\n@author: MenegLau\r\n\"\"\"\r\n\r\nfrom PIL import Image\r\nfrom os import listdir, path\r\nimport argparse\n\ndef rescale_images(directory, size):\r\n for img in listdir(directory):\n \t img_path = path.join(directory, img)\n \t img_name, img_ext = path.splitext(img)\n \t if img_ext.lower() != '.xml':\n \t \t #break\n \t #else:\n #if img_ext.lower() == '.xml':\n # break\n #else:\r\n im = Image.open(directory+img)\r\n im_resized = im.resize(size, Image.ANTIALIAS)\r\n im_resized.save(directory+img)\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description=\"Rescale images\")\r\n parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images')\r\n parser.add_argument('-s', '--size', type=int, nargs=2, required=True, metavar=('width', 'height'), help='Image size')\r\n args = parser.parse_args()\r\n rescale_images(args.directory, args.size)", "sub_path": "transform_image_resolution.py", "file_name": "transform_image_resolution.py", "file_ext": "py", "file_size_in_byte": 1024, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 22, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 22, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 23, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 23, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "254980488", "text": "import rospy\nimport math\nfrom sensor_msgs.msg import LaserScan\nimport rospy\nimport numpy as np\nimport matplotlib\nfrom geometry_msgs.msg import Pose\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nfrom tools import n_closest\nfrom tools import rotate_2d_vector\nfrom tfTools import get_2d_point_moved_using_vector\nfrom tfTools import get_transform_vector_from_pose\nfrom geometry_msgs.msg import Point\nfrom std_msgs.msg import Float64\nimport warnings\nfrom drone_control.msg import MyNumpy\n\n\n\nclass MappingConnector():\n def __init__(self):\n #self.node=rospy.init_node(\"laserConversionNode\",anonymous=True)\n self.subMyMap=rospy.Subscriber(\"myMap\",MyNumpy,self.sub_map_memmory)\n self.x_min=-5\n self.x_max=5\n self.y_min=-5\n self.y_max=5\n self.map_resolution=0.05\n self.dimension_x=int((self.x_max-self.x_min)/self.map_resolution)\n self.dimension_y=int((self.y_max-self.y_min)/self.map_resolution)\n self.map_memmory=np.zeros((self.dimension_y,self.dimension_x))#first for x secound for y\n self.max_points=1024\n self.my_plot=None\n self.plot_fig=None\n self.is_ready=False\n self.drone_pos=None\n self.theta=None\n self.last_print_time=time.time()\n self.buffor_range=10\n #fig = plt.figure()\n #self.ax = fig.add_subplot(1,1,1)\n\n warnings.filterwarnings(\"ignore\")\n self.time_euler=time.time()\n self.time_pos=time.time()\n #rospy.spin()\n self.counter=0\n\n def get_map_memmory(self):\n return self.map_memmory\n\n def sub_map_memmory(self,msg):\n data=msg.data\n data=np.array(data)\n \n self.map_memmory=np.reshape(data,(self.dimension_y,self.dimension_x))\n #print(self.map_memmory.shape)\n #rospy.loginfo(\"jest\")\n self.is_ready=True\n\n def isReady(self):\n return self.is_ready\n\n \n\n def is_target_reachable(self,target_point):\n x_i,y_i=self.get_point_on_map_index(target_point[0],target_point[1])\n if(self.map_memmory[y_i][x_i]!=0):\n return False\n else:\n return True\n\n\n\n\n \n\n def transfer_points(self,x_array,y_array,angle):\n for i,x_p in enumerate(x_array):\n x=x_array[i]\n y=y_array[i]\n \n #rospy.loginfo(\"angle %f\"%(angle))\n \n # x,y=rotate_2d_vector([x,y],np.pi)\n x,y=rotate_2d_vector([x,y],angle)\n x,y=get_2d_point_moved_using_vector(self.drone_pos,(x,y))\n x_array[i]=x\n y_array[i]=y\n return (x_array,y_array)\n\n\n\n def get_point_on_map_index(self,x,y):\n\n x_i = int(round((x - self.x_min) / self.map_resolution))\n y_i= int(round((y - self.y_min) / self.map_resolution))\n return (x_i,y_i)\n\n def get_drone_x_y_arrays(self,x_array):\n x=np.zeros(np.size(x_array))\n y=np.zeros(np.size(x_array))\n y[:]=self.drone_pos[1]\n x[:]=self.drone_pos[0]\n return x,y\n \n \n\n\n\n def update_map_memory(self,x_array,y_array,map_resolution,x_min,y_min):\n for i, x in enumerate(x_array):\n x_i,y_i=self.get_point_on_map_index(x_array[i],y_array[i])\n self.map_memmory[y_i][x_i]=1\n neighbours=n_closest(self.map_memmory,(y_i,x_i),self.buffor_range)\n neighbours[neighbours!=1]=2\n\n def get_points_from_memory(self,value):\n points_indexs=np.where(self.map_memmory==value)\n x_index_array=points_indexs[1]\n y_index_array=points_indexs[0]\n x_array=x_index_array*self.map_resolution\n x_array=x_array+self.x_min\n\n y_array=y_index_array*self.map_resolution\n y_array=y_array+self.y_min\n\n\n return (x_array,y_array)\n \n\n\n def convert_index_to_point(self,x_i,y_i):\n x=x_i*self.map_resolution\n x=x+self.x_min\n\n y=y_i*self.map_resolution\n y=y+self.y_min\n return (x,y)\n \n\n\n\n def get_points(self,laser_data):\n points_list=[]\n current_point=[]\n for i,cordinate in enumerate(laser_data):\n \n if (i+1)%3==0:\n # current_point.append(cordinate)\n points_list.append(current_point)\n current_point=[]\n else:\n current_point.append(cordinate)\n return points_list\n\n\n def get_x_y(self,old_data):\n x=[]\n y=[]\n current_point=[]\n for i,cordinate in enumerate(old_data):\n \n if (i+1)%3==0:\n x.append(current_point[0])\n y.append(current_point[1])\n current_point=[]\n else:\n \n current_point.append(cordinate)\n\n x=np.array(x)\n y=np.array(y)\n return (x,y)", "sub_path": "mapConnector.py", "file_name": "mapConnector.py", "file_ext": "py", "file_size_in_byte": 4813, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rospy.Subscriber", "line_number": 25, "usage_type": "call"}, {"api_name": "drone_control.msg.MyNumpy", "line_number": 25, "usage_type": "argument"}, {"api_name": "numpy.zeros", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 40, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 45, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "time.time", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 58, "usage_type": "call"}, {"api_name": "tools.rotate_2d_vector", "line_number": 88, "usage_type": "call"}, {"api_name": "tfTools.get_2d_point_moved_using_vector", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 104, "usage_type": "call"}, {"api_name": "tools.n_closest", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 175, "usage_type": "call"}]} +{"seq_id": "397705271", "text": "import discord\nfrom discord.ext import commands, events\nfrom config import KEYS\nimport asyncio\nfrom datetime import datetime\nfrom pytz import timezone\nfrom collections import defaultdict\n#import challonge\n\nCOGS = [\n 'dev',\n 'help',\n 'miscellaneous',\n 'staff',\n 'channels',\n 'mongo',\n 'configuration'\n ]\n\nclass Bot(commands.AutoShardedBot, events.EventsMixin):\n def __init__(self, **kwargs):\n super().__init__(\n **kwargs,\n command_prefix= 'h.',\n case_insensitive=True,\n intents=discord.Intents.all(),\n )\n\n for i in COGS:\n self.load_extension(f\"cogs.{i}\")\n \n @property\n def mongo(self):\n return self.get_cog('Mongo')\n\n def printTime():\n format = \"%Y-%m-%d %H:%M:%S %Z%z\"\n utc = datetime.now(timezone('UTC'))\n ist = utc.astimezone(timezone('Asia/Kolkata'))\n return ist.strftime(format)\n\n async def on_ready(self):\n print(f'We have logged in as {self.user}')\n owner = self.get_user(506018589904470047)\n await owner.send(\"im up..! -\")\n\nif __name__ == \"__main__\":\n bot = Bot()\n bot.run(KEYS.discordToken)\n", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 1179, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "discord.ext.commands.AutoShardedBot", "line_number": 20, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 20, "usage_type": "name"}, {"api_name": "discord.ext.events.EventsMixin", "line_number": 20, "usage_type": "attribute"}, {"api_name": "discord.ext.events", "line_number": 20, "usage_type": "name"}, {"api_name": "discord.Intents.all", "line_number": 26, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 38, "usage_type": "call"}, {"api_name": "pytz.timezone", "line_number": 39, "usage_type": "call"}, {"api_name": "config.KEYS.discordToken", "line_number": 49, "usage_type": "attribute"}, {"api_name": "config.KEYS", "line_number": 49, "usage_type": "name"}]} +{"seq_id": "37954575", "text": "import re\nimport os\nimport tika\nimport pickle\nimport string\nprintable = set(string.printable)\n\n\n\n\nsurprisingFindings = []\npaperNames = []\nfor file in os.listdir(\"papers\"):\n\tif file.endswith(\".pdf\"):\n\t\tpaperNames.append(file)\n\n\nos.chdir(\"papers\")\ntika.initVM()\nfrom tika import parser\nfor paper in paperNames:\n\tparsed = parser.from_file(paper)\n\t# print(parsed[\"metadata\"])\n\tif \"content\" in parsed:\n\t\tpaperText = parsed[\"content\"]\n\n\t\tsentences = re.findall(r\"([^.]*\\.)\", paperText) \n\t\tfor sentenceID, sentence in enumerate(sentences):\n\t\t\t# There has to be a better way to get sentences that show surprise\n\t\t\tif \"surpris\" in sentence.lower():\n\t\t\t\tfinding = sentences[sentenceID - 1] + sentence\n\t\t\t\tsurprisingFindings.append({\"finding\": finding, \"paper\": paper})\n\n\nverifiedFindings = []\n\nfor i, findingObj in enumerate(surprisingFindings):\n\tfinding = findingObj[\"finding\"]\n\tfinding = finding.strip()\n\tfinding = finding.replace('-\\n', '')\n\tfinding = finding.replace('\\n', ' ')\n\tfinding = finding.replace('\\t', ' ')\n\tfinding = finding.replace('\\\\n', ' ') \n\tfinding = finding.replace('\\\\t', ' ')\n\tfi = finding.lower()\n\t# surprisal filters out things talking about the surprisal gradient\n\t# anger filters out sentiment classification papers where surprise is one of the sentiments\n\tif (\"not a surpris\" not in fi) and (\"unsurpris\" not in fi) and (\"not surpris\" not in fi) and (\"surprisal\" not in fi) and (\"anger\" not in fi) and (\"angry\" not in fi):\n\t\tfindingASCII = ''.join(filter(lambda x: x in string.printable, finding))\n\t\tfindingASCII = re.sub(' +', ' ', findingASCII)\n\t\tverifiedFindings.append({\"finding\": findingASCII, \"paper\": findingObj[\"paper\"]})\n\n\nwith open('findings.txt', 'wb') as f:\n\tpickle.dump(verifiedFindings, f)\n\n# print(verifiedFindings)\n\n\nfor fin in verifiedFindings:\n\tprint(fin[\"finding\"])\n\tprint(\"********************************************************************\")\n\tprint(fin[\"paper\"])\n\tprint(\"\\n\")\n\n\nprint(len(verifiedFindings))\n\n \n\n\n\n\n", "sub_path": "searcher.py", "file_name": "searcher.py", "file_ext": "py", "file_size_in_byte": 1954, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "string.printable", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 13, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 18, "usage_type": "call"}, {"api_name": "tika.initVM", "line_number": 19, "usage_type": "call"}, {"api_name": "tika.parser.from_file", "line_number": 22, "usage_type": "call"}, {"api_name": "tika.parser", "line_number": 22, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 27, "usage_type": "call"}, {"api_name": "string.printable", "line_number": 49, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 50, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 55, "usage_type": "call"}]} +{"seq_id": "215002822", "text": "\"\"\"Evaulate a language model using the test set.\n\nUsage:\n eval.py -i \n eval.py -h | --help\n\nOptions:\n -i Language model file.\n -h --help Show this screen.\n\"\"\"\nfrom docopt import docopt\nimport pickle\n\nfrom nltk.corpus import PlaintextCorpusReader\nfrom nltk.tokenize import RegexpTokenizer\n\nif __name__ == '__main__':\n opts = docopt(__doc__)\n\n filename = opts['-i']\n f = open(filename, 'rb')\n modelo = pickle.load(f)\n f.close()\n\n tokenizer = RegexpTokenizer(\"[a-zA-Z'`éèî]+\")\n\n corpus = PlaintextCorpusReader('./languagemodeling/corpus',\n 'minicorpus.txt', word_tokenizer=tokenizer)\n sents = corpus.sents()\n\n # 10% test\n cant_sents_tests = int(len(sents) * 10 / 100.0)\n test_sents = sents[:cant_sents_tests]\n\n print(\"Cross Entropy: \")\n print(modelo.cross_entropy(test_sents))\n\n print(\"Perplexity: \")\n print(modelo.perplexity(test_sents))\n\n", "sub_path": "languagemodeling/scripts/eval.py", "file_name": "eval.py", "file_ext": "py", "file_size_in_byte": 944, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "docopt.docopt", "line_number": 18, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 22, "usage_type": "call"}, {"api_name": "nltk.tokenize.RegexpTokenizer", "line_number": 25, "usage_type": "call"}, {"api_name": "nltk.corpus.PlaintextCorpusReader", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "374394667", "text": "# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/ditz/session.py\n# Compiled at: 2016-03-07 14:40:46\n\"\"\"\nInteractive session recording.\n\"\"\"\nfrom __future__ import print_function\nimport re, sys, fileinput\nfrom six import StringIO\ntry:\n import pexpect\nexcept ImportError:\n print('You need to install the pexpect module to generate session')\n print('output. This also implies using a system that supports it')\n print('(i.e., not Windows).')\n sys.exit(99)\n\nclass CmdSession(object):\n\n def __init__(self, program, prompt):\n self.child = pexpect.spawn(program, timeout=1)\n self.atprompt = False\n self.prompt = prompt\n self.flush()\n\n def command(self, prompt, response):\n if prompt is None:\n if not self.showing(self.prompt):\n self.output(self.prompt)\n self.toprompt()\n else:\n self.child.expect(prompt)\n self.child.sendline(response)\n self.atprompt = False\n return\n\n def showing(self, text):\n return self.getoutput()[-len(text):] == text\n\n def toprompt(self):\n if not self.atprompt:\n self.child.expect(self.prompt)\n self.atprompt = True\n\n def getoutput(self):\n return self.child.logfile_read.getvalue()\n\n def output(self, text):\n self.child.logfile_read.write(text)\n\n def flush(self):\n self.child.logfile_read = StringIO()\n\n def quit(self, cmd='quit'):\n self.toprompt()\n self.child.sendline(cmd)\n self.child.expect(pexpect.EOF)\n\n\ndef run_session(debug=False):\n command = ('\\n pyditz --no-search --no-pager --no-plugins --no-highlight --no-vcs\\n -c ui.name=Dilbert\\n -c ui.email=dilbert@cubicle.com\\n ').strip().replace('\\n', ' ')\n ditz = CmdSession(command, 'Ditz: ')\n for line in fileinput.input():\n m = re.match('\\\\.\\\\. command: *(.*)', line)\n if m:\n cmd = m.group(1)\n ditz.command(None, cmd)\n continue\n m = re.match('\\\\.\\\\. prompt: *(.*)', line)\n if m:\n prompt = m.group(1) or None\n continue\n m = re.match('\\\\.\\\\. reply: *(.*)', line)\n if m:\n reply = m.group(1)\n ditz.command(prompt, reply)\n continue\n m = re.match('\\\\.\\\\. (literal)?include:: */(.+\\\\.txt)', line)\n if m:\n recfile = m.group(2)\n ditz.toprompt()\n output = ditz.getoutput()\n lines = output.split('\\r\\n')[:-1]\n output = ('\\n').join(lines).rstrip() + '\\n'\n ditz.flush()\n with open(recfile, 'w') as (fp):\n fp.write(output)\n if debug:\n print()\n print('===', recfile, '===')\n print()\n print(output)\n else:\n print('Wrote', recfile)\n\n ditz.quit()\n return\n\n\nif __name__ == '__main__':\n run_session()", "sub_path": "pycfiles/pyditz-0.10.3-py2.7/session.py", "file_name": "session.py", "file_ext": "py", "file_size_in_byte": 3080, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.exit", "line_number": 19, "usage_type": "call"}, {"api_name": "pexpect.spawn", "line_number": 24, "usage_type": "call"}, {"api_name": "six.StringIO", "line_number": 55, "usage_type": "call"}, {"api_name": "pexpect.EOF", "line_number": 60, "usage_type": "attribute"}, {"api_name": "fileinput.input", "line_number": 66, "usage_type": "call"}, {"api_name": "re.match", "line_number": 67, "usage_type": "call"}, {"api_name": "re.match", "line_number": 72, "usage_type": "call"}, {"api_name": "re.match", "line_number": 76, "usage_type": "call"}, {"api_name": "re.match", "line_number": 81, "usage_type": "call"}]} +{"seq_id": "325707739", "text": "\"\"\"\nCreate a standard ticket.\n\nCreate a standard support ticket. Use a standard support ticket if you need to work out \na problem related to SoftLayer's hardware, network, or services. \nIf you require SoftLayer's assistance managing your server or content then please open an administrative ticket.\nSupport tickets may only be created in the open state. The SoftLayer API defaults new ticket properties userEditableFlag \nto true, accountId to the id of the account that your API user belongs to, and statusId to 1001 (or \"open\"). \nYou may not assign your new to ticket to users that your API user does not have access to.\nOnce your ticket is created it is placed in a queue for SoftLayer employees to work. \nAs they update the ticket new SoftLayer_Ticket_Update entries are added to the ticket object.\n\nImportant manual pages:\nhttp://sldn.softlayer.com/reference/services/SoftLayer_Ticket/createStandardTicket\nhttp://sldn.softlayer.com/reference/datatypes/SoftLayer_Ticket\n\nLicense: http://sldn.softlayer.com/article/License\nAuthor: SoftLayer Technologies, Inc. \n\"\"\"\n\nimport SoftLayer\nimport pprint\n\n# Your SoftLayer user-name.\nUSERNAME = 'set me'\n# Generate one at https://manage.softlayer.com/Administrative/apiKeychain\nAPI_KEY = 'set me'\n\n# The ticket title used for the standard ticket.\ntitle = 'Standard ticket'\n# The user id who is going to be assigned the ticket. \nassignedUser = 104672\n# The SoftLayer group that's going to service the ticket.\nsubjectId = 1001\n# This is typically the ticket's problem description.\ncontent = 'Creating a standard ticket using python client'\n\n# Build a skeleton SoftLayer_Ticket\n# containing the ticket specification values (the next is an example of the minimum required values).\nticket = {\n 'title': title, \n 'subjectId': subjectId, \n 'assignedUserId': assignedUser \n}\n\n# Declare the API client\nclient = SoftLayer.Client(username=USERNAME, api_key=API_KEY)\nticketService = client['SoftLayer_Ticket']\n\ntry:\n response = ticketService.createStandardTicket(ticket, content)\n pprint.pprint(response)\nexcept SoftLayer.SoftLayerAPIError as e: \n print(\"Unable to create a Standard ticket. Fault code: %s - Fault string: %s\" \n % (e.faultCode, e.faultString))\n\n", "sub_path": "SoftLayer_Ticket/CreateStandardTicket.py", "file_name": "CreateStandardTicket.py", "file_ext": "py", "file_size_in_byte": 2242, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "SoftLayer.Client", "line_number": 47, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 52, "usage_type": "call"}, {"api_name": "SoftLayer.SoftLayerAPIError", "line_number": 53, "usage_type": "attribute"}]} +{"seq_id": "582210095", "text": "# coding: utf-8\n#\n# Copyright 2019 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Unit tests for scripts/release_scripts/generate_release_updates.py.\"\"\"\n\nfrom __future__ import absolute_import # pylint: disable=import-only-modules\nfrom __future__ import unicode_literals # pylint: disable=import-only-modules\n\nimport os\nimport subprocess\n\nfrom core.tests import test_utils\nimport python_utils\nimport release_constants\nfrom scripts import common\nfrom scripts.release_scripts import generate_release_updates\n\nRELEASE_TEST_DIR = os.path.join('core', 'tests', 'release_sources', '')\n\nMOCK_RELEASE_SUMMARY_FILEPATH = os.path.join(\n RELEASE_TEST_DIR, 'release_summary.md')\nMOCK_RELEASE_SUMMARY_FILEPATH = os.path.join(\n RELEASE_TEST_DIR, 'release_summary.md')\n\n\nclass GenerateReleaseUpdatesTests(test_utils.GenericTestBase):\n \"\"\"Test the methods for generating release updates.\"\"\"\n\n def setUp(self):\n super(GenerateReleaseUpdatesTests, self).setUp()\n def mock_get_current_branch_name():\n return 'release-1.2.3'\n def mock_input():\n return 'y'\n self.branch_name_swap = self.swap(\n common, 'get_current_branch_name', mock_get_current_branch_name)\n self.input_swap = self.swap(\n python_utils, 'INPUT', mock_input)\n\n def test_draft_new_release(self):\n check_function_calls = {\n 'check_call_gets_called': False,\n 'ask_user_to_confirm_gets_called': False,\n 'open_new_tab_in_browser_if_possible_gets_called': False\n }\n expected_check_function_calls = {\n 'check_call_gets_called': True,\n 'ask_user_to_confirm_gets_called': True,\n 'open_new_tab_in_browser_if_possible_gets_called': True\n }\n\n all_cmd_tokens = []\n def mock_check_call(cmd_tokens):\n all_cmd_tokens.extend(cmd_tokens)\n check_function_calls['check_call_gets_called'] = True\n def mock_open_new_tab_in_browser_if_possible(unused_url):\n check_function_calls[\n 'open_new_tab_in_browser_if_possible_gets_called'] = True\n def mock_ask_user_to_confirm(unused_msg):\n check_function_calls['ask_user_to_confirm_gets_called'] = True\n def mock_get_remote_alias(unused_remote_url):\n return 'upstream'\n\n check_call_swap = self.swap(subprocess, 'check_call', mock_check_call)\n open_tab_swap = self.swap(\n common, 'open_new_tab_in_browser_if_possible',\n mock_open_new_tab_in_browser_if_possible)\n ask_user_swap = self.swap(\n common, 'ask_user_to_confirm', mock_ask_user_to_confirm)\n get_remote_alias_swap = self.swap(\n common, 'get_remote_alias', mock_get_remote_alias)\n with self.branch_name_swap, check_call_swap, open_tab_swap:\n with ask_user_swap, get_remote_alias_swap:\n generate_release_updates.draft_new_release()\n self.assertEqual(check_function_calls, expected_check_function_calls)\n\n expected_cmd_tokens = [\n 'git', 'tag', '-a', 'v1.2.3', '-m', 'Version 1.2.3',\n 'git', 'push', 'upstream', 'v1.2.3']\n self.assertEqual(all_cmd_tokens, expected_cmd_tokens)\n\n def test_prompt_user_to_send_announcement_email(self):\n check_function_calls = {\n 'open_new_tab_in_browser_if_possible_gets_called': False,\n 'get_new_authors_and_contributors_mail_ids_gets_called': False\n }\n expected_check_function_calls = {\n 'open_new_tab_in_browser_if_possible_gets_called': True,\n 'get_new_authors_and_contributors_mail_ids_gets_called': True\n }\n def mock_open_new_tab_in_browser_if_possible(unused_url):\n check_function_calls[\n 'open_new_tab_in_browser_if_possible_gets_called'] = True\n def mock_get_new_authors_and_contributors_mail_ids():\n check_function_calls[\n 'get_new_authors_and_contributors_mail_ids_gets_called'] = True\n return ['id1@email.com', 'id2@email.com']\n open_tab_swap = self.swap(\n common, 'open_new_tab_in_browser_if_possible',\n mock_open_new_tab_in_browser_if_possible)\n get_new_authors_and_contributors_mail_ids_swap = self.swap(\n generate_release_updates,\n 'get_new_authors_and_contributors_mail_ids',\n mock_get_new_authors_and_contributors_mail_ids)\n with self.branch_name_swap, self.input_swap, open_tab_swap:\n with get_new_authors_and_contributors_mail_ids_swap:\n (\n generate_release_updates\n .prompt_user_to_send_announcement_email())\n self.assertEqual(check_function_calls, expected_check_function_calls)\n\n def test_get_new_authors_and_contributors_mail_ids(self):\n with self.swap(\n release_constants, 'RELEASE_SUMMARY_FILEPATH',\n MOCK_RELEASE_SUMMARY_FILEPATH):\n self.assertEqual(\n (\n generate_release_updates\n .get_new_authors_and_contributors_mail_ids()),\n [\n 'alice@gmail.com', 'bob@gmail.com', 'casie@gmail.com',\n 'qunet@outlook.com', 'zoe@gmail.com'])\n\n def test_invalid_branch_name(self):\n def mock_get_current_branch_name():\n return 'invalid'\n branch_name_swap = self.swap(\n common, 'get_current_branch_name', mock_get_current_branch_name)\n with branch_name_swap, self.assertRaisesRegexp(\n Exception, (\n 'This script should only be run from the latest release '\n 'branch.')):\n generate_release_updates.main()\n\n def test_missing_release_summary_file(self):\n release_summary_swap = self.swap(\n release_constants, 'RELEASE_SUMMARY_FILEPATH', 'invalid.md')\n with self.branch_name_swap, release_summary_swap:\n with self.assertRaisesRegexp(\n Exception, (\n 'Release summary file invalid.md is missing. Please run '\n 'the release_info.py script and re-run this script.')):\n generate_release_updates.main()\n\n def test_prepare_for_next_release(self):\n check_function_calls = {\n 'open_new_tab_in_browser_if_possible_gets_called': False,\n 'ask_user_to_confirm_gets_called': False\n }\n expected_check_function_calls = {\n 'open_new_tab_in_browser_if_possible_gets_called': True,\n 'ask_user_to_confirm_gets_called': True\n }\n def mock_open_new_tab_in_browser_if_possible(unused_url):\n check_function_calls[\n 'open_new_tab_in_browser_if_possible_gets_called'] = True\n def mock_ask_user_to_confirm(unused_msg):\n check_function_calls['ask_user_to_confirm_gets_called'] = True\n\n open_tab_swap = self.swap(\n common, 'open_new_tab_in_browser_if_possible',\n mock_open_new_tab_in_browser_if_possible)\n ask_user_swap = self.swap(\n common, 'ask_user_to_confirm', mock_ask_user_to_confirm)\n with open_tab_swap, ask_user_swap:\n generate_release_updates.prepare_for_next_release()\n self.assertEqual(check_function_calls, expected_check_function_calls)\n\n def test_function_calls(self):\n check_function_calls = {\n 'draft_new_release_gets_called': False,\n 'prompt_user_to_send_announcement_email_gets_called': False,\n 'prepare_for_next_release_gets_called': False,\n }\n expected_check_function_calls = {\n 'draft_new_release_gets_called': True,\n 'prompt_user_to_send_announcement_email_gets_called': True,\n 'prepare_for_next_release_gets_called': True,\n }\n def mock_draft_new_release():\n check_function_calls['draft_new_release_gets_called'] = True\n def mock_prompt_user_to_send_announcement_email():\n check_function_calls[\n 'prompt_user_to_send_announcement_email_gets_called'] = True\n def mock_prepare_for_next_release():\n check_function_calls['prepare_for_next_release_gets_called'] = True\n def mock_exists(unused_filepath):\n return True\n def mock_remove(unused_filepath):\n pass\n\n release_summary_swap = self.swap(\n release_constants, 'RELEASE_SUMMARY_FILEPATH',\n MOCK_RELEASE_SUMMARY_FILEPATH)\n draft_release_swap = self.swap(\n generate_release_updates, 'draft_new_release',\n mock_draft_new_release)\n send_swap = self.swap(\n generate_release_updates, 'prompt_user_to_send_announcement_email',\n mock_prompt_user_to_send_announcement_email)\n prepare_swap = self.swap(\n generate_release_updates, 'prepare_for_next_release',\n mock_prepare_for_next_release)\n exists_swap = self.swap(os.path, 'exists', mock_exists)\n remove_swap = self.swap(os, 'remove', mock_remove)\n\n with self.branch_name_swap, release_summary_swap, prepare_swap:\n with send_swap, exists_swap, remove_swap, draft_release_swap:\n generate_release_updates.main()\n\n self.assertEqual(check_function_calls, expected_check_function_calls)\n", "sub_path": "scripts/release_scripts/generate_release_updates_test.py", "file_name": "generate_release_updates_test.py", "file_ext": "py", "file_size_in_byte": 9929, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "core.tests.test_utils.GenericTestBase", "line_number": 39, "usage_type": "attribute"}, {"api_name": "core.tests.test_utils", "line_number": 39, "usage_type": "name"}, {"api_name": "scripts.common", "line_number": 49, "usage_type": "argument"}, {"api_name": "scripts.common", "line_number": 79, "usage_type": "argument"}, {"api_name": "scripts.common", "line_number": 82, "usage_type": "argument"}, {"api_name": "scripts.common", "line_number": 84, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates.draft_new_release", "line_number": 87, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 87, "usage_type": "name"}, {"api_name": "scripts.common", "line_number": 112, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 115, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates.prompt_user_to_send_announcement_email", "line_number": 121, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 121, "usage_type": "name"}, {"api_name": "scripts.release_scripts.generate_release_updates.get_new_authors_and_contributors_mail_ids", "line_number": 131, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 131, "usage_type": "name"}, {"api_name": "scripts.common", "line_number": 141, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates.main", "line_number": 146, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 146, "usage_type": "name"}, {"api_name": "scripts.release_scripts.generate_release_updates.main", "line_number": 156, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 156, "usage_type": "name"}, {"api_name": "scripts.common", "line_number": 174, "usage_type": "argument"}, {"api_name": "scripts.common", "line_number": 177, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates.prepare_for_next_release", "line_number": 179, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 179, "usage_type": "name"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 209, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 212, "usage_type": "argument"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 215, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 217, "usage_type": "attribute"}, {"api_name": "scripts.release_scripts.generate_release_updates.main", "line_number": 222, "usage_type": "call"}, {"api_name": "scripts.release_scripts.generate_release_updates", "line_number": 222, "usage_type": "name"}]} +{"seq_id": "428348181", "text": "import digi\nimport digi.on as on\nimport digi.util as util\nimport random as rand\nimport datetime as dt\n\ndata_json = {}\n\n@on.control\ndef do_control(sv, mount):\n p, b = sv.get(\"power\", {}), sv.get(\"brightness\", {})\n p_old_status, b_old_status = p.get(\"status\"), b.get(\"status\")\n if \"intent\" in p:\n p[\"status\"] = p[\"intent\"]\n if \"intent\" in b:\n if p.get(\"status\", \"off\") == \"on\":\n b[\"status\"] = b[\"intent\"]\n else:\n b[\"status\"] = 0\n if p.get(\"status\") != p_old_status \\\n or b.get(\"status\") != b_old_status:\n report()\n\ndef report():\n model = digi.rc.view()\n power, brightness = util.get(model, \"control.power.status\"), \\\n util.get(model, \"control.brightness.status\")\n digi.pool.load(\n [{\n \"power\": power,\n \"brightness\": brightness,\n }]\n )\n\ndef sync():\n data_json = generate_data(dt.datetime.now())\n digi.logger.info(\"data_json: {}\".format(data_json))\n digi.pool.load([data_json])\n digi.logger.info(\"Sync completed\")\n\n\ndef generate_data(date):\n data_json = {\n 'calories': rand.randint(1000, 4000),\n 'date': date,\n 'distance': rand.uniform(0, 10),\n 'fairly_active_minutes': rand.randint(0, 100),\n 'floors': rand.randint(0, 200),\n 'light_active_minutes': rand.randint(0, 100),\n 'sedentary_minutes': rand.randint(0, 100),\n 'steps': rand.randint(500, 30000),\n 'very_active_minutes': rand.randint(0, 100),\n }\n\n return data_json\n\n@on.meta\ndef do_meta(meta):\n model = digi.rc.view()\n digi.logger.info(\"meta: {}\".format(meta))\n p = util.get(model, \"control.power.status\")\n i = meta.get(\"gen_interval\")\n digi.logger.info(\"p: {}\".format(p))\n digi.logger.info(\"i: {}\".format(i))\n if p == \"on\" and i > 0:\n loader.reset(i)\n loader.start()\n digi.logger.info(\"Auto sync completed\")\n elif p == \"on\" and i <= 0:\n \n #loader.stop()\n sync()\n digi.logger.info(\"Manual sync completed\")\n #if loader.is_running():\n \n else:\n #if loader.is_running():\n digi.logger.info(\"Sync stopped\")\n loader.reset(i)\n \n\nloader = util.Loader(load_fn=sync)\n\nif __name__ == '__main__':\n digi.run()\n\n\n\n\n'''\n@digi.on.model\ndef h(model):\n ...\n\nmock_gvr = \"toosh.digi.dev/v1/fitbit\"\n\n@on.control\ndef do_control(sv, mount):\n mock = get_mock(mount)\n power_attr = \"contol.power.status\"\n brightness_attr = \"control.brightness.status\"\n sync_attr = \"control.sync_request.status\"\n p = util.get(sv, power_attr)\n b = util.get(sv, brightness_attr)\n s = util.get(sv, sync_attr)\n util.update(mock, \"spec.control.power.intent\", p)\n util.update(mock, \"spec.control.brightness.intent\", b)\n util.update(mock, \"spec.control.sync_request.intent\", s)\n \ndef get_mock(mount):\n mocks = mount.get(mock_gvr, {})\n digi.logger.info(\"mocks: {}\".format(mocks))\n assert len(mocks) == 1, \"at most one mock is allowed\"\n for _, mock in mocks.items():\n return mock\n return None\n\ndef report():\n model = digi.rc.view()\n power, brightness = util.get(model, \"control.power.status\"), util.get(model, 'control.brightness.status')\n digi.pool.load(\n [\n {\n 'power': power,\n 'brightness': brightness,\n }\n ]\n )\n\n\ndef sync():\n model = digi.rc.view()\n data_json = {\n 'calories': util.get(model, \"obs.calories\"),\n 'date': util.get(model, \"obs.date\"),\n 'distance': util.get(model, \"obs.distance\"),\n 'fairly_active_minutes': util.get(model, \"obs.fairly_active_minutes\"),\n 'floors': util.get(model, \"obs.floors\"),\n 'light_active_minutes': util.get(model, \"obs.light_active_minutes\"),\n 'sedentary_minutes': util.get(model, \"obs.sedentary_minutes\"),\n 'steps': util.get(model, \"obs.steps\"),\n 'very_active_minutes': util.get(model, \"obs.very_active_minutes\"),\n }\n digi.logger.info(\"Sync completed\")\n digi.pool.load([data_json])\n \n\nloader = util.Loader(load_fn=sync)\n\n\n@on.meta\ndef do_meta(meta):\n sync_intent = util.get(model, \"control.sync_request.status\")\n i = meta.get(\"sync_interval\", -1)\n if sync_intent == \"on\" and i > 0:\n digi.logger.info(\"Auto sync completed\")\n loader.reset(i)\n loader.start()\n elif sync_intent == \"on\" and i <= 0:\n digi.logger.info(\"Manual sync completed\")\n sync()\n if loader.is_running():\n loader.stop()\n else:\n if loader.is_running():\n digi.logger.info(\"Sync stopped\")\n loader.stop()\n\n \n\n\nif __name__ == '__main__':\n digi.run()\n\n'''\n", "sub_path": "fitbit/fitbit/driver/handler.py", "file_name": "handler.py", "file_ext": "py", "file_size_in_byte": 4744, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "digi.on.control", "line_number": 9, "usage_type": "attribute"}, {"api_name": "digi.on", "line_number": 9, "usage_type": "name"}, {"api_name": "digi.rc.view", "line_number": 25, "usage_type": "call"}, {"api_name": "digi.rc", "line_number": 25, "usage_type": "attribute"}, {"api_name": "digi.util.get", "line_number": 26, "usage_type": "call"}, {"api_name": "digi.util", "line_number": 26, "usage_type": "name"}, {"api_name": "digi.util.get", "line_number": 27, "usage_type": "call"}, {"api_name": "digi.util", "line_number": 27, "usage_type": "name"}, {"api_name": "digi.pool.load", "line_number": 28, "usage_type": "call"}, {"api_name": "digi.pool", "line_number": 28, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 37, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 37, "usage_type": "attribute"}, {"api_name": "digi.pool.load", "line_number": 38, "usage_type": "call"}, {"api_name": "digi.pool", "line_number": 38, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 39, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 39, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 44, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 46, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 47, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 48, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 49, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 50, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 51, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 52, "usage_type": "call"}, {"api_name": "digi.rc.view", "line_number": 59, "usage_type": "call"}, {"api_name": "digi.rc", "line_number": 59, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 60, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 60, "usage_type": "attribute"}, {"api_name": "digi.util.get", "line_number": 61, "usage_type": "call"}, {"api_name": "digi.util", "line_number": 61, "usage_type": "name"}, {"api_name": "digi.logger.info", "line_number": 63, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 63, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 64, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 64, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 68, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 68, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 73, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 73, "usage_type": "attribute"}, {"api_name": "digi.logger.info", "line_number": 78, "usage_type": "call"}, {"api_name": "digi.logger", "line_number": 78, "usage_type": "attribute"}, {"api_name": "digi.on.meta", "line_number": 57, "usage_type": "attribute"}, {"api_name": "digi.on", "line_number": 57, "usage_type": "name"}, {"api_name": "digi.util.Loader", "line_number": 82, "usage_type": "call"}, {"api_name": "digi.util", "line_number": 82, "usage_type": "name"}, {"api_name": "digi.run", "line_number": 85, "usage_type": "call"}]} +{"seq_id": "185974873", "text": "import pygame\nimport serial\nimport struct\nimport pyautogui,sys\nimport pygame\nfrom time import sleep\nfrom pygame.locals import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport socket\nfrom struct import *\nimport math\nfrom pynput import keyboard\n\npyautogui.MINIMUM_DURATION=0\npyautogui.MINIMUM_SLEEP=0\npyautogui.PAUSE=0\nUDP_IP = \"192.168.1.104\"\nprint(\"Receiver IP: \", UDP_IP)\n# UDP_PORT = 6000\nUDP_PORT = 5050\nprint(\"Port: \", UDP_PORT)\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nsock.bind((UDP_IP, UDP_PORT))\n\ngameExit = False\n\ndef on_press(key):\n try: k = key.char # single-char keys\n except: k = key.name # other keys # stop listener\n global gameExit\n if (k=='-'):\n print('Key pressed: ' + k)\n gameExit=True\n elif(k=='*'):\n gameExit=False\n elif(k=='+'):\n pyautogui.click(button='left')\n elif(k=='/'):\n pyautogui.click(button='right')\n elif(k=='.'):\n pyautogui.doubleClick()\n\n\nlis = keyboard.Listener(on_press=on_press)\ndef game_loop():\n x = (400)\n y = (300)\n lis.start()\n\n while True:\n while not gameExit:\n data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes+\n x_m = \"%1.8f\" % unpack_from('!f', data, 24);\n y_m = \"%1.8f\" % unpack_from('!f', data, 32);\n z_m = \"%1.8f\" % unpack_from('!f', data, 28);\n y_m=-float(y_m)+float(x_m)\n\n\n print(x,y)\n if(float(z_m)<0.05 and float(z_m)>-0.05):\n z_m=0\n if(float(y_m)<0.05 and float(y_m)>-0.05):\n y_m=0\n x=(float(y_m))\n y = (float(z_m))\n if(float(y_m)<0 and float(y_m)!=0):\n x=20*(-(math.exp(-float(y_m)))*(abs(float(y_m))))\n elif(float(y_m)>0):\n x = 20*((math.exp(float(y_m)))*(abs(float(y_m))))\n if(float(z_m)<0 and float(z_m)!=0):\n y =20*(-math.exp(-float(z_m)))*((abs(float(z_m))))\n elif(float(z_m)>0):\n y = 20*((math.exp(float(z_m)))*(abs(float(z_m))))\n #pyautogui.moveTo(x,y)\n #sleep(0)\n pyautogui.moveRel(x,y)\n\ngame_loop()\n # start to listen on a separate thread\n\n", "sub_path": "moveage.py", "file_name": "moveage.py", "file_ext": "py", "file_size_in_byte": 2242, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pyautogui.MINIMUM_DURATION", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pyautogui.MINIMUM_SLEEP", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pyautogui.PAUSE", "line_number": 17, "usage_type": "attribute"}, {"api_name": "socket.socket", "line_number": 23, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 23, "usage_type": "attribute"}, {"api_name": "socket.SOCK_DGRAM", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pyautogui.click", "line_number": 39, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 41, "usage_type": "call"}, {"api_name": "pyautogui.doubleClick", "line_number": 43, "usage_type": "call"}, {"api_name": "pynput.keyboard.Listener", "line_number": 46, "usage_type": "call"}, {"api_name": "pynput.keyboard", "line_number": 46, "usage_type": "name"}, {"api_name": "math.exp", "line_number": 69, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 71, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 73, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 75, "usage_type": "call"}, {"api_name": "pyautogui.moveRel", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "87134251", "text": "#!/bin/python\n# -*- coding: utf-8 -*-\n\nimport csv\nimport openpyxl\nimport os,sys\n\nsrcf = open(\"/home/pangwz/tmp/src.csv\",encoding='gbk') #csv reader 不会自动转换,默认utf8,需要指明encoding.\nsrcreader = csv.reader(srcf)\n\ndestf = openpyxl.load_workbook('/home/pangwz/tmp/dest.xlsx')\nsheet = destf[\"硬件\"]\nprint(sheet.max_row)\nprint(sheet.max_column)\n\ni=1\ncurmax=sheet.max_row #insert_rows()后再次引用会自动+1;\nsrcreader.__next__() #skip header line\nnotmatch=[]\nfor row in srcreader:\n vid=row[0]\n adacct=row[1]\n ip=row[2]\n\n ismatch=0;\n\n print(\"try for\",vid,ip,adacct)\n for idx in range(3,sheet.max_row+1):\n #print(\"try match %d\" %idx)\n matchcell=sheet.cell(idx,4) #col4: 资产名称\n assetname=matchcell.value.lower()\n if(assetname==adacct):\n ismatch=1\n break\n\n if (assetname in adacct) or (adacct in assetname):\n print(\"assetname:\",assetname,\"adacct\",adacct)\n while 1:\n usel=input(\"Not full matching your select y/n[y]:\")\n if len(usel)== 0 or (usel.lower() == \"y\") or (usel.lower() == \"n\"):\n break;\n if (usel.lower() != \"n\"):\n ismatch=1\n break\n\n if(ismatch == 0):\n print(\"no matching\")\n notmatch.append(adacct)\n else:\n #print(\"match %d\" %idx)\n newrow=idx+1\n sheet.insert_rows(newrow)\n for srccells in sheet.iter_rows(min_row=idx,max_row=idx): #获取match 行\n for srccell in srccells:\n sheet.cell(newrow,srccell.column,srccell.value)\n\n sheet.cell(idx,5,adacct) #old hw terminal\n sheet.cell(newrow,4,vid) #newrow for vdesk 资产名称\n sheet.cell(newrow,5,adacct) #域用户\n sheet.cell(newrow,15,vid)\n sheet.cell(newrow,16,\"虚拟桌面,用于查阅IP资料,设计开发\")\n sheet.cell(newrow,19,ip)\n\nprint(\"Total no matching %d, %s\" %(len(notmatch),notmatch))\ndestf.save('/home/pangwz/tmp/kkkk.xlsx')\nexit()\n\nfor row in srcreader:\n vid=row[0]\n user=row[1]\n ip=row[2]\n\n target=user\n ismatch=0;\n\n print(\"try for\",vid,ip,user)\n for idx in range(3,curmax+1):\n #print(\"try match %d\" %idx)\n matchcell=sheet.cell(idx,4)\n if(matchcell.value.lower()==target):\n ismatch=1\n #print(\"match %d\" %idx)\n newrow=curmax+i\n i+=1\n sheet.insert_rows(newrow)\n for srccells in sheet.iter_rows(min_row=idx,max_row=idx): #获取match 行\n for srccell in srccells:\n sheet.cell(newrow,srccell.column,srccell.value)\n\n sheet.cell(newrow,4,vid)\n sheet.cell(newrow,14,vid)\n sheet.cell(newrow,18,ip)\n break\n\n if(ismatch == 0):\n print(\"not match for user:%s\" %user)\n\ndestf.save('./kkkk.xlsx')\nexit()\nrows=sheet.iter_rows(min_row=3,min_col=4,max_col=4)\nfor row in rows:\n cell=row[0]\n if(cell.value.lower()==target):\n print(cell.row)\n sheet.insert_rows(cell.row+1)\n for srccells in sheet.iter_rows(min_row=cell.row,max_row=cell.row):\n print(srccells)\n for srccell in srccells:\n sheet.cell(cell.row+1,srccell.column,srccell.value)\n\n sheet.cell(cell.row+1,4,\"kkkkk\")\n sheet.cell(cell.row+1,18,\"192.168.2.111\")\n\ndestf.save('./kkk.xlsx')\nexit()\n\nfor i in range(3,5):\n cell=sheet.cell(i,3)\n print(type(cell.value))\n print(cell.encoding)\n print(cell.data_type)\n print(cell.value)\n tmp=cell.value.encode('utf8')\n print(tmp)\n print(type(tmp))\n str=tmp.decode('utf8')\n print(type(str))\n\nexit()\n", "sub_path": "python/excel/merge/merge.py", "file_name": "merge.py", "file_ext": "py", "file_size_in_byte": 3874, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "csv.reader", "line_number": 9, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "73572893", "text": "import matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn import metrics, svm\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\nfrom market_place import MarketPlace\nfrom repository import save_in_csv\nfrom utils import constansts\n\n\"\"\"\nHere we predict the num of active installs based on average price\nwith three algorithms random forest, SVM(linear) and linear regression\nand at the end, we compare their results\n\"\"\"\n\nresult_sdf = pd.DataFrame()\n\n\ndef get_data() -> pd.DataFrame:\n \"\"\"\n :return the data frame that we want process on it\n \"\"\"\n m = MarketPlace()\n df = m.df[[\"active_installs\"]].copy()\n\n df[\"price\"] = m.retrieve_avg_price().copy()\n return df[(df['price'] >= 0) & (df['active_installs'] >= 0)]\n\n\ndef evaluation_matrix(y_true, y_predict):\n \"\"\"\n For evaluation of error term\n \"\"\"\n print('Mean Squared Error: ' + str(metrics.mean_squared_error(y_true, y_predict)))\n print('Mean absolute Error: ' + str(metrics.mean_absolute_error(y_true, y_predict)))\n\n\ndef evaluation_matrix_dict(y_true, y_predict, name='Linear'):\n \"\"\"\n To add into results_index for evaluation of error term\n \"\"\"\n dict_matrix = {\n 'Series Name': name,\n 'Mean Squared Error': metrics.mean_squared_error(y_true, y_predict),\n 'Mean Absolute Error': metrics.mean_absolute_error(y_true, y_predict)\n # 'Mean Squared Log Error': metrics.mean_squared_log_error(y_true, y_predict)\n }\n return dict_matrix\n\n\ndef linear_regression_learn():\n \"\"\"\n Learn data and predict installs base price via linear regression\n \"\"\"\n df = get_data()\n # Integer encoding\n x = df.drop(labels=['price'], axis=1)\n y = df['active_installs']\n\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30)\n model = LinearRegression()\n model.fit(x_train, y_train)\n results = model.predict(x_test)\n\n # Creation of results data frame and addition of first entry\n global result_sdf\n result_sdf = result_sdf.append(evaluation_matrix_dict(y_test, results, name='Linear_regression'),\n ignore_index=True)\n print(\"-------------------------------------------------\")\n print(\"linear regression results:\")\n print('Actual mean of installs:' + str(y.mean()))\n print('Predicted installs(mean) :' + str(results.mean()))\n print('Predicted installs(std) :' + str(results.std()))\n print(\"-------------------------------------------------\")\n\n plt.figure(figsize=(12, 7))\n sns.regplot(x=results, y=y_test, color='teal', label='Price', marker='x')\n plt.legend()\n plt.title('linear regression learn # installs from avg price')\n plt.xlabel('Predicted installs')\n plt.ylabel('Actual installs')\n plt.show()\n\n\ndef random_forest_learn():\n \"\"\"\n Learn data and predict installs base price via random forest algorithm\n and plot its result\n \"\"\"\n\n df = get_data()\n x = df.drop(labels=['price'], axis=1)\n y = df['active_installs']\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30)\n\n model = RandomForestRegressor()\n model.fit(x_train, y_train)\n results = model.predict(x_test)\n\n # evaluation\n global result_sdf\n result_sdf = result_sdf.append(evaluation_matrix_dict(y_test, results, name='Random forest'),\n ignore_index=True)\n print(\"-------------------------------------------------\")\n print(\"random forest results:\")\n print('Actual mean of installs:' + str(y.mean()))\n print('Predicted installs(mean) :' + str(results.mean()))\n print('Predicted installs(std) :' + str(results.std()))\n print(\"-------------------------------------------------\")\n\n plt.figure(figsize=(12, 7))\n sns.regplot(x=results, y=y_test, color='teal', label='Price', marker='x')\n plt.legend()\n plt.title('Random forest learn # installs from avg price')\n plt.xlabel('Predicted installs')\n plt.ylabel('Actual installs')\n plt.show()\n\n\ndef svm_learn():\n # Integer encoding\n df = get_data()\n x = df.drop(labels=['price'], axis=1)\n y = df['active_installs']\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30)\n\n model = svm.LinearSVR()\n model.fit(x_train, y_train)\n\n results = model.predict(x_test)\n\n global result_sdf\n result_sdf = result_sdf.append(evaluation_matrix_dict(y_test, results, name='SVM-linear'),\n ignore_index=True)\n\n print('Actual mean of installs:' + str(y.mean()))\n print('Predicted installs(mean) :' + str(results.mean()))\n print('Predicted installs(std) :' + str(results.std()))\n\n plt.figure(figsize=(12, 7))\n sns.regplot(x=results, y=y_test, color='teal', label='Price', marker='x')\n plt.legend()\n plt.title('SVM learn # installs from avg price')\n plt.xlabel('Predicted installs')\n plt.ylabel('Actual installs')\n plt.show()\n\n\ndef compare_learners():\n \"\"\"\n Compare two algorithms linear regression and random forest results and show it\n and plot its result\n \"\"\"\n\n global result_sdf\n linear_regression_learn()\n svm_learn()\n random_forest_learn()\n\n # print errors together\n with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n print(result_sdf)\n\n # save errors to a csv file\n save_in_csv(\"log/errors.csv\", result_sdf)\n\n # plot errors to compare them\n result_sdf.set_index('Series Name', inplace=True)\n\n plt.subplot(2, 1, 1)\n result_sdf['Mean Squared Error'].sort_values(ascending=False).plot(kind='barh', color=constansts.green,\n title='Mean Squared Error')\n plt.subplot(2, 1, 2)\n result_sdf['Mean Absolute Error'].sort_values(ascending=False).plot(kind='barh', color=constansts.orange,\n title='Mean Absolute Error')\n plt.show()\n\n\nif __name__ == \"__main__\":\n compare_learners()\n", "sub_path": "learner.py", "file_name": "learner.py", "file_ext": "py", "file_size_in_byte": 6105, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.DataFrame", "line_number": 19, "usage_type": "call"}, {"api_name": "market_place.MarketPlace", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 22, "usage_type": "attribute"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 37, "usage_type": "name"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 38, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 38, "usage_type": "name"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 47, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 47, "usage_type": "name"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 48, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 48, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 63, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "seaborn.regplot", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestRegressor", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "seaborn.regplot", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 128, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVR", "line_number": 130, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "seaborn.regplot", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 148, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 148, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "pandas.option_context", "line_number": 164, "usage_type": "call"}, {"api_name": "repository.save_in_csv", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "utils.constansts.green", "line_number": 174, "usage_type": "attribute"}, {"api_name": "utils.constansts", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "utils.constansts.orange", "line_number": 177, "usage_type": "attribute"}, {"api_name": "utils.constansts", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}]} +{"seq_id": "471825507", "text": "import numpy as np\nimport h5py\nimport csv\nimport os.path\nimport sys\nimport csv\nimport tensorflow as tf\nfrom pathlib import Path\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom alignment_GX import project\nfrom dgp_rff_ldmk_evaluation import evaluation\n\n# sys.path.append('/nas/home/xiaoguo/working_directory/DP_autoencoder/deep_gp_random_features\\\n# /code/experiments')\n# sys.path.append('/nas/home/xiaoguo/working_directory/dummy_COW/')\n\nif len(sys.argv) < 2:\n\tprint (\"please entering the image_path before running code. Exit.\")\n\tsys.exit()\nelse:\n\tdirectory = str(sys.argv[1])\n\tprint (\"using images from the directory : \", directory)\n\ndef normalization(image_path):\n landmarks = project(image_path)\n distance_vector = (landmarks[:][15] - landmarks[:][1]) ** 2 \n length = np.sqrt( np.sum(distance_vector) )\n vector = landmarks[:] - np.mean(landmarks[:], axis = 0)\n return vector / length\n\nmodel_path = '../pretrained_model/'\ncsv_file_name = './CAH_result_file.csv'\npathlist = Path(directory).glob('*.png')\nprint (\"loading pretrained model from {}\".format(model_path))\n\nif os.path.exists(csv_file_name):\n\tprint (\"file {} exists.\".format(csv_file_name))\nelse:\n\twith open('CAH_result_file.csv', mode='w') as csv_file:\n\t\twriter = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\t\twriter.writerow(['Image ID', 'Error result'])\n\tprint (\"creating file {} for the results.\".format(csv_file_name))\n\ncsv_file = open(csv_file_name, mode='a')\nwriter = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\nfor path in pathlist:\n\timage_path = str(path)\n\tif \"lnds\" not in image_path:\n\t\ttf.reset_default_graph()\n\n\t\tID = (image_path.split('/')[-1]).split('.')[0]\t\t\n\t\tnew_landmarks = normalization(image_path)\n\t\terror_result = evaluation(new_landmarks)\n\n\t\tprint (\"The error of image {} is {:.4}\".format(ID, error_result))\n\n\t\tcsv_list = [ID, error_result]\n\t\twriter.writerow(csv_list)\n\ncsv_file.close()\n", "sub_path": "deep_gp_random_features/code/experiments/DGAE_testing.py", "file_name": "DGAE_testing.py", "file_ext": "py", "file_size_in_byte": 1969, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 22, "usage_type": "attribute"}, {"api_name": "alignment_GX.project", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 29, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.path.exists", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 37, "usage_type": "name"}, {"api_name": "csv.writer", "line_number": 41, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 41, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 46, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tensorflow.reset_default_graph", "line_number": 51, "usage_type": "call"}, {"api_name": "dgp_rff_ldmk_evaluation.evaluation", "line_number": 55, "usage_type": "call"}]} +{"seq_id": "432171471", "text": "import numpy as np\nimport torch\nfrom .base_model import BaseModel\nfrom . import networks\nfrom .patchnce import PatchNCELoss\nimport util.util as util\nfrom models.augment import AugmentPipe\nimport util.training_stats as training_stats \nfrom util import dnnlib\nfrom util import misc\nimport cv2\nimport os\n\n\nclass CUTADAFPNModel(BaseModel):\n \"\"\" This class implements CUT and FastCUT model, described in the paper\n Contrastive Learning for Unpaired Image-to-Image Translation\n Taesung Park, Alexei A. Efros, Richard Zhang, Jun-Yan Zhu\n ECCV, 2020\n\n The code borrows heavily from the PyTorch implementation of CycleGAN\n https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\n \"\"\"\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n \"\"\" Configures options specific for CUT model\n \"\"\"\n parser.add_argument('--CUT_mode', type=str, default=\"CUT\", choices='(CUT, cut, FastCUT, fastcut)')\n\n parser.add_argument('--lambda_GAN', type=float, default=1.0, help='weight for GAN loss: GAN(G(X))')\n parser.add_argument('--lambda_NCE', type=float, default=1.0, help='weight for NCE loss: NCE(G(X), X)')\n parser.add_argument('--nce_idt', type=util.str2bool, nargs='?', const=True, default=False, help='use NCE loss for identity mapping: NCE(G(Y), Y))')\n parser.add_argument('--nce_layers', type=str, default='0,4,8,12,16', help='compute NCE loss on which layers')\n parser.add_argument('--nce_includes_all_negatives_from_minibatch',\n type=util.str2bool, nargs='?', const=True, default=False,\n help='(used for single image translation) If True, include the negatives from the other samples of the minibatch when computing the contrastive loss. Please see models/patchnce.py for more details.')\n parser.add_argument('--netF', type=str, default='mlp_sample', choices=['sample', 'reshape', 'mlp_sample', 'strided_conv'], help='how to downsample the feature map')\n parser.add_argument('--netF_nc', type=int, default=256)\n parser.add_argument('--nce_T', type=float, default=0.07, help='temperature for NCE loss')\n parser.add_argument('--num_patches', type=int, default=256, help='number of patches per layer')\n parser.add_argument('--flip_equivariance',\n type=util.str2bool, nargs='?', const=True, default=False,\n help=\"Enforce flip-equivariance as additional regularization. It's used by FastCUT, but not CUT\")\n parser.set_defaults(pool_size=0) # no image pooling\n\n opt, _ = parser.parse_known_args()\n\n # Set default parameters for CUT and FastCUT\n if opt.CUT_mode.lower() == \"cut\":\n parser.set_defaults(nce_idt=True, lambda_NCE=1.0)\n elif opt.CUT_mode.lower() == \"fastcut\":\n parser.set_defaults(\n nce_idt=False, lambda_NCE=10.0, flip_equivariance=True,\n n_epochs=150, n_epochs_decay=50\n )\n else:\n raise ValueError(opt.CUT_mode)\n\n return parser\n\n def __init__(self, opt):\n BaseModel.__init__(self, opt)\n\n # parameter initialize\n self.opt = opt\n self.parameter_initialize(opt)\n\n # specify the training losses you want to print out.\n # The training/test scripts will call \n self.loss_names = ['G_GAN', 'D_real', 'D_fake', 'G', 'NCE']\n self.visual_names = ['real_A', 'fake_B', 'real_B']\n self.nce_layers = [int(i) for i in self.opt.nce_layers.split(',')]\n\n if opt.nce_idt and self.isTrain:\n self.loss_names += ['NCE_Y']\n self.loss_names += ['extend_NCE']\n self.visual_names += ['idt_B']\n\n if self.isTrain:\n self.model_names = ['G', 'F', 'D']\n else: # during test time, only load G\n self.model_names = ['G']\n\n # define networks (both generator and discriminator)\n self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.normG, not opt.no_dropout, opt.init_type, opt.init_gain, opt.no_antialias, opt.no_antialias_up, self.gpu_ids, opt)\n self.netF = networks.define_F(opt.input_nc, opt.netF, opt.normG, not opt.no_dropout, opt.init_type, opt.init_gain, opt.no_antialias, self.gpu_ids, opt)\n\n if self.isTrain:\n self.netD = networks.define_D(opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.normD, opt.init_type, opt.init_gain, opt.no_antialias, self.gpu_ids, opt)\n\n # define loss functions\n self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)\n self.criterionNCE = []\n self.criterionConsistency = torch.nn.L1Loss()\n for nce_layer in self.nce_layers:\n self.criterionNCE.append(PatchNCELoss(opt).to(self.device))\n\n self.criterionIdt = torch.nn.L1Loss().to(self.device)\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, opt.beta2))\n self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr, betas=(opt.beta1, opt.beta2))\n self.optimizers.append(self.optimizer_G)\n self.optimizers.append(self.optimizer_D)\n\n # Setup augmentation\n self.augment_pipe = None\n self.ada_stats = None\n self.augment_pipe = AugmentPipe()\n for key, value in self.augment_kwargs.items():\n setattr(self.augment_pipe, key, value)\n self.augment_pipe = self.augment_pipe.train().requires_grad_(False).to(self.device)\n self.augment_pipe.p.copy_(torch.as_tensor(opt.ada_initial_p))\n self.ada_stats = training_stats.Collector(regex='Loss/signs/real')\n\n def parameter_initialize(self, opt):\n self.cur_nimg = 0\n self.batch_idx = 0\n self.batch_size = opt.batch_size\n\n self.ada_target = opt.ada_target\n aug = opt.aug\n self.ada_interval = opt.ada_interval\n augpipe_specs = {\n 'bl': dict(xflip=1, xint=1),\n 'blit': dict(xflip=1, rotate90=1, xint=1),\n 'geom': dict(scale=1, rotate=1, aniso=1, xfrac=1),\n 'color': dict(brightness=1, contrast=1, lumaflip=1, hue=1, saturation=1),\n 'filter': dict(imgfilter=1),\n 'noise': dict(noise=1),\n 'cutout': dict(cutout=1),\n 'bg': dict(xflip=1, rotate90=1, xint=1, scale=1, rotate=1, aniso=1, xfrac=1),\n 'bgc': dict(xflip=1, rotate90=1, xint=1, scale=1, rotate=1, aniso=1, xfrac=1, brightness=1, contrast=1, lumaflip=1, hue=1, saturation=1),\n 'bgcf': dict(xflip=1, rotate90=1, xint=1, scale=1, rotate=1, aniso=1, xfrac=1, brightness=1, contrast=1, lumaflip=1, hue=1, saturation=1, imgfilter=1),\n 'bgcfn': dict(xflip=1, rotate90=1, xint=1, scale=1, rotate=1, aniso=1, xfrac=1, brightness=1, contrast=1, lumaflip=1, hue=1, saturation=1, imgfilter=1, noise=1),\n 'bgcfnc': dict(xflip=1, rotate90=1, xint=1, scale=1, rotate=1, aniso=1, xfrac=1, brightness=1, contrast=1, lumaflip=1, hue=1, saturation=1, imgfilter=1, noise=1, cutout=1),\n }\n assert aug in augpipe_specs\n self.augment_kwargs = augpipe_specs[aug]\n \n\n\n def data_dependent_initialize(self, data):\n \"\"\"\n The feature network netF is defined in terms of the shape of the intermediate, extracted\n features of the encoder portion of netG. Because of this, the weights of netF are\n initialized at the first feedforward pass with some input images.\n Please also see PatchSampleF.create_mlp(), which is called at the first forward() call.\n \"\"\"\n self.set_input(data)\n bs_per_gpu = self.real_A.size(0) // max(len(self.opt.gpu_ids), 1)\n self.real_A = self.real_A[:bs_per_gpu]\n self.real_B = self.real_B[:bs_per_gpu]\n self.forward() # compute fake images: G(A)\n if self.opt.isTrain:\n self.compute_D_loss().backward() # calculate gradients for D\n self.compute_G_loss().backward() # calculate graidents for G\n if self.opt.lambda_NCE > 0.0:\n self.optimizer_F = torch.optim.Adam(self.netF.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, self.opt.beta2))\n self.optimizers.append(self.optimizer_F)\n\n def optimize_parameters(self):\n # forward\n self.forward()\n\n # update D\n self.set_requires_grad(self.netD, True)\n self.optimizer_D.zero_grad()\n self.loss_D = self.compute_D_loss()\n self.loss_D.backward()\n self.optimizer_D.step()\n\n # update G\n self.set_requires_grad(self.netD, False)\n self.optimizer_G.zero_grad()\n if self.opt.netF == 'mlp_sample':\n self.optimizer_F.zero_grad()\n self.loss_G = self.compute_G_loss()\n self.loss_G.backward()\n self.optimizer_G.step()\n if self.opt.netF == 'mlp_sample':\n self.optimizer_F.step()\n\n #update state\n self.cur_nimg += self.batch_size\n self.batch_idx += 1\n\n # Execute ADA heuristic\n if self.batch_idx % self.ada_interval == 0:\n self.ada_stats.update()\n adjust = np.sign(self.ada_stats['Loss/signs/real'] - self.ada_target) * (self.batch_size * self.ada_interval) / (self.dataset_size*(self.opt.n_epochs + self.opt.n_epochs_decay))\n self.augment_pipe.p.copy_((self.augment_pipe.p + adjust).max(misc.constant(0, device=self.device)))\n\n\n def set_input(self, input):\n \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n Parameters:\n input (dict): include the data itself and its metadata information.\n The option 'direction' can be used to swap domain A and domain B.\n \"\"\"\n AtoB = self.opt.direction == 'AtoB'\n self.real_A = input['A' if AtoB else 'B'].to(self.device)\n self.real_B = input['B' if AtoB else 'A'].to(self.device)\n self.image_paths = input['A_paths' if AtoB else 'B_paths']\n # For FPN\n self.real_A_extend = []\n if 'A_extend' in input:\n for i in range(len(input['A_extend'])):\n self.real_A_extend.append(input['A_extend'][i].to(self.device))\n\n def forward(self):\n \"\"\"Run forward pass; called by both functions and .\"\"\"\n self.real = torch.cat((self.real_A, self.real_B), dim=0) if self.opt.nce_idt and self.opt.isTrain else self.real_A\n if self.opt.flip_equivariance:\n self.flipped_for_equivariance = self.opt.isTrain and (np.random.random() < 0.5)\n if self.flipped_for_equivariance:\n self.real = torch.flip(self.real, [3])\n\n self.horizontal_flip = np.random.random() < self.opt.hflip and self.opt.isTrain\n self.vertical_flip = np.random.random() < self.opt.vflip and self.opt.isTrain\n if self.horizontal_flip and self.vertical_flip:\n self.real = torch.cat((self.real, torch.flip(self.real[:self.real_A.size(0)].detach(), (2,3)).to(self.device)), dim=0)\n elif self.horizontal_flip:\n self.real = torch.cat((self.real, torch.flip(self.real[:self.real_A.size(0)].detach(), (3,)).to(self.device)), dim=0)\n elif self.vertical_flip:\n self.real = torch.cat((self.real, torch.flip(self.real[:self.real_A.size(0)].detach(), (2,)).to(self.device)), dim=0)\n\n self.fake = self.netG(self.real)\n # Identical B\n self.fake_B = self.fake[:self.real_A.size(0)]\n if self.opt.nce_idt:\n self.idt_B = self.fake[self.real_A.size(0):self.real_A.size(0)+self.real_B.size(0)]\n \n # Horizontal and Vertical Flip\n self.flip_fake = None\n if self.vertical_flip and self.horizontal_flip:\n # Flip back to calculate loss\n self.flip_fake = torch.flip(self.fake[-self.real_A.size(0):], (2,3))\n elif self.vertical_flip:\n self.flip_fake = torch.flip(self.fake[-self.real_A.size(0):], (2,))\n elif self.horizontal_flip:\n self.flip_fake = torch.flip(self.fake[-self.real_A.size(0):], (3,))\n\n # Different Scales\n self.extend_fakes = []\n for extend_A in self.real_A_extend:\n self.extend_fakes.append(self.netG(extend_A))\n\n def compute_D_loss(self):\n \"\"\"Calculate GAN loss for the discriminator\"\"\"\n fake = self.fake_B.detach()\n # Augment\n if self.augment_pipe is not None:\n fake = self.augment_pipe(fake)\n # Fake; stop backprop to the generator by detaching fake_B\n pred_fake = self.netD(fake)\n self.loss_D_fake = self.criterionGAN(pred_fake, False).mean()\n \n # Fake flip\n if self.vertical_flip or self.horizontal_flip:\n flip_fake = self.flip_fake.detach()\n pred_flip_fake = self.netD(flip_fake)\n self.loss_D_flip_fake = self.criterionGAN(pred_flip_fake, False).mean()\n \n # Real\n if self.augment_pipe is not None:\n real_B_tmp = self.real_B.detach().requires_grad_(True)\n aug_real = self.augment_pipe(real_B_tmp)\n self.pred_real = self.netD(aug_real)#self.real_B)\n loss_D_real = self.criterionGAN(self.pred_real, True)\n self.loss_D_real = loss_D_real.mean()\n training_stats.report('Loss/signs/real', self.pred_real.sign())\n\n # combine loss and calculate gradients\n if not (self.vertical_flip or self.horizontal_flip):\n self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5\n else:\n self.loss_D = (self.loss_D_fake + self.loss_D_real + self.loss_D_flip_fake) / 3.0\n return self.loss_D\n\n def compute_G_loss(self):\n \"\"\"Calculate GAN and NCE loss for the generator\"\"\"\n fake = self.fake_B\n # First, augment fake image\n if self.augment_pipe is not None:\n aug_fake = self.augment_pipe(fake)\n # G(A) should fake the discriminator\n if self.opt.lambda_GAN > 0.0:\n pred_fake = self.netD(aug_fake)\n self.loss_G_GAN = self.criterionGAN(pred_fake, True).mean() * self.opt.lambda_GAN\n else:\n self.loss_G_GAN = 0.0\n\n # NCE loss\n if self.opt.lambda_NCE > 0.0:\n self.loss_NCE = self.calculate_NCE_loss(self.real_A, self.fake_B)\n self.loss_extend_NCE = 0\n for extend_real, extend_fake in zip(self.real_A_extend, self.extend_fakes):\n self.loss_extend_NCE += self.calculate_NCE_loss(extend_real, extend_fake)\n else:\n self.loss_NCE, self.loss_NCE_bd = 0.0, 0.0\n\n # Flip Consistency Loss\n flip_fake = self.flip_fake\n if self.vertical_flip or self.horizontal_flip:\n pred_flip_fake = self.netD(flip_fake)\n self.loss_G_flip_GAN = self.criterionGAN(pred_flip_fake, True).mean() * self.opt.lambda_GAN\n self.loss_fake_consistent = self.criterionConsistency(self.flip_fake, self.fake_B)\n if self.opt.lambda_NCE > 0.0:\n self.loss_flip_NCE = self.calculate_NCE_loss(self.real_A, self.flip_fake)\n else:\n self.loss_G_flip_GAN = 0.0\n self.loss_flip_NCE = 0.0\n \n # Sum all the loss\n loss_NCE_both = torch.tensor(0.0, requires_grad=True).to(self.device)\n if self.opt.nce_idt and self.opt.lambda_NCE > 0.0:\n self.loss_NCE_Y = self.calculate_NCE_loss(self.real_B, self.idt_B)\n loss_NCE_both += self.loss_NCE_Y\n \n if getattr(self, 'loss_extend_NCE', None) is not None:\n loss_NCE_both += self.loss_extend_NCE\n\n if (self.vertical_flip or self.horizontal_flip) and self.opt.lambda_NCE > 0.0:\n loss_NCE_both += self.loss_flip_NCE\n \n loss_NCE_both += self.loss_NCE\n\n self.loss_G = self.loss_G_GAN + loss_NCE_both\n if self.vertical_flip or self.horizontal_flip:\n self.loss_G += self.loss_G_flip_GAN + self.loss_fake_consistent\n return self.loss_G\n\n def calculate_NCE_loss(self, src, tgt):\n n_layers = len(self.nce_layers)\n feat_q = self.netG(tgt, self.nce_layers, encode_only=True)\n\n if self.opt.flip_equivariance and self.flipped_for_equivariance:\n feat_q = [torch.flip(fq, [3]) for fq in feat_q]\n\n feat_k = self.netG(src, self.nce_layers, encode_only=True)\n feat_k_pool, sample_ids = self.netF(feat_k, self.opt.num_patches, None)\n feat_q_pool, _ = self.netF(feat_q, self.opt.num_patches, sample_ids)\n\n total_nce_loss = 0.0\n for f_q, f_k, crit, nce_layer in zip(feat_q_pool, feat_k_pool, self.criterionNCE, self.nce_layers):\n loss = crit(f_q, f_k) * self.opt.lambda_NCE\n total_nce_loss += loss.mean()\n\n return total_nce_loss / n_layers", "sub_path": "models/cut_ada_fpn_model.py", "file_name": "cut_ada_fpn_model.py", "file_ext": "py", "file_size_in_byte": 16937, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "base_model.BaseModel", "line_number": 15, "usage_type": "name"}, {"api_name": "util.util.str2bool", "line_number": 32, "usage_type": "attribute"}, {"api_name": "util.util", "line_number": 32, "usage_type": "name"}, {"api_name": "util.util.str2bool", "line_number": 35, "usage_type": "attribute"}, {"api_name": "util.util", "line_number": 35, "usage_type": "name"}, {"api_name": "util.util.str2bool", "line_number": 42, "usage_type": "attribute"}, {"api_name": "util.util", "line_number": 42, "usage_type": "name"}, {"api_name": "base_model.BaseModel.__init__", "line_number": 62, "usage_type": "call"}, {"api_name": "base_model.BaseModel", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.nn.L1Loss", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "attribute"}, {"api_name": "patchnce.PatchNCELoss", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn.L1Loss", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 98, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 100, "usage_type": "attribute"}, {"api_name": "models.augment.AugmentPipe", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 111, "usage_type": "call"}, {"api_name": "util.training_stats.Collector", "line_number": 112, "usage_type": "call"}, {"api_name": "util.training_stats", "line_number": 112, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 157, "usage_type": "attribute"}, {"api_name": "numpy.sign", "line_number": 189, "usage_type": "call"}, {"api_name": "util.misc.constant", "line_number": 190, "usage_type": "call"}, {"api_name": "util.misc", "line_number": 190, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 213, "usage_type": "attribute"}, {"api_name": "torch.flip", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 217, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 218, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 218, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 220, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 220, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 236, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 238, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 240, "usage_type": "call"}, {"api_name": "util.training_stats.report", "line_number": 270, "usage_type": "call"}, {"api_name": "util.training_stats", "line_number": 270, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 314, "usage_type": "call"}, {"api_name": "torch.flip", "line_number": 337, "usage_type": "call"}]} +{"seq_id": "451703839", "text": "# encoding: utf-8\nfrom django.shortcuts import redirect, get_object_or_404\nfrom annoying.decorators import render_to\nfrom django.contrib.auth import *\nfrom django.contrib.auth.forms import *\nfrom django.contrib.auth.models import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import requires_csrf_token\nfrom accounts.forms import *\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse \n\nfrom django.contrib.sessions.models import Session\n\n@render_to('registration/register.html') \ndef register(request):\n form = RegisterForm(request.POST or None)\n if form.is_valid():\n data = form.cleaned_data\n profile, created = UserProfile.objects.get_or_create(\n user = data['user'], # user - is model, not a string\n )\n return { 'form': form }\n\n@render_to('registration/view_profile.html')\n@login_required\ndef my_profile(request ):\n user = request.user\n request.session['u_id'] = user\n u_id = request.session['u_id'] \n return { \"user\": user, \"u_id\": u_id }\n\ndef page_not_found(request):\n message_404_err = 'Page http://'+request.get_host()+request.path+' not found'\n message_404 = u'Ой, это страница 404...\\nКотэ приветствует тебя!\\n'+\\\n u'\"Как я сюда попал?\"\\nУ котэ есть несколько вариантов:'+\\\n u'\\n- Вы попытались открыть страницу, которой не существует\\n'+\\\n u'- Введенный вами URL адрес неправильный\\n- Вам нравятся странички 404\\n'+\\\n u'- Вы просто захотели увидеть котэ \\n (котэ рад и польщен ^__^)'\n message_404=message_404.split('\\n')\n response = HttpResponse(status=404, content=render_to_string('404.html', { 'message_404_err' : message_404_err, 'message_404': message_404 }))\n return response\n \n@requires_csrf_token\ndef server_error(request):\n message_500 = \"There's been an error. It's been reported to the site administrators via e-mail and should be fixed shortly. Thanks for your patience.\"\n response = HttpResponse(status=500, content=render_to_string('500.html', { 'message_500' : message_500 }))\n return response", "sub_path": "accounts/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2373, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "annoying.decorators.render_to", "line_number": 15, "usage_type": "call"}, {"api_name": "annoying.decorators.render_to", "line_number": 25, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 26, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 41, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 41, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 47, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 47, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.requires_csrf_token", "line_number": 44, "usage_type": "name"}]} +{"seq_id": "168907241", "text": "# -*- coding: utf-8 -*-\n\nfrom odoo import api, fields, models, tools, _\nfrom datetime import datetime\n\n\nclass Workorder(models.Model):\n _inherit = 'mrp.workorder'\n\n # SHOULD BE RELATED TO JOB IN MANUFACTURING ORDER FROM OLD STUDIo production_id.x_studio_job\n # ssi_job_id = fields.Many2one(\n # 'ssi_jobs', string='Job')\n ssi_job_id = fields.Many2one(\n 'ssi_jobs', related='production_id.ssi_job_id', string='Job', store=True)\n duration_expected_hours = fields.Float(\n 'Expected Hours',\n compute='_compute_expected_hours',\n readonly=True, store=True,\n help=\"Expected duration (in hours)\")\n duration_hours = fields.Float(\n 'Real Hours', compute='_compute_duration_hours',\n readonly=True, store=True)\n job_urgency = fields.Selection(related='ssi_job_id.urgency', string=\"Urgency\", store=True, readonly=True)\n job_deadline = fields.Datetime(related='ssi_job_id.deadline_date', string=\"Deadline\", store=True, readonly=True)\n job_stage = fields.Many2one('ssi_jobs_stage', related='ssi_job_id.stage_id', string=\"Job Stage\", store=True, readonly=True)\n hide_in_kiosk = fields.Boolean(related='operation_id.hide_in_kiosk', string=\"Hide in Kiosk\", store=True, readonly=True)\n\n @api.depends('duration_expected')\n def _compute_expected_hours(self):\n for record in self:\n record.duration_expected_hours = record.duration_expected / 60\n\n @api.depends('duration')\n def _compute_duration_hours(self):\n for record in self:\n record.duration_hours = record.duration / 60\n\n @api.multi\n def name_get(self):\n return [(wo.id, \"%s(%s) %s\" % (wo.ssi_job_id.name, wo.production_id.name, wo.name)) for wo in self]\n# return [(wo.id, \"%s - %s - %s\" % (wo.production_id.name, wo.product_id.name, wo.name)) for wo in self]\n\n @api.multi\n def button_start(self):\n self.ensure_one()\n # As button_start is automatically called in the new view\n if self.state in ('done', 'cancel'):\n return True\n\n # Need a loss in case of the real time exceeding the expected\n# timeline = self.env['mrp.workcenter.productivity']\n# if self.duration < self.duration_expected:\n# loss_id = self.env['mrp.workcenter.productivity.loss'].search([('loss_type','=','productive')], limit=1)\n# if not len(loss_id):\n# raise UserError(_(\"You need to define at least one productivity loss in the category 'Productivity'. Create one from the Manufacturing app, menu: Configuration / Productivity Losses.\"))\n# else:\n# loss_id = self.env['mrp.workcenter.productivity.loss'].search([('loss_type','=','performance')], limit=1)\n# if not len(loss_id):\n# raise UserError(_(\"You need to define at least one productivity loss in the category 'Performance'. Create one from the Manufacturing app, menu: Configuration / Productivity Losses.\"))\n for workorder in self:\n if workorder.production_id.state != 'progress':\n workorder.production_id.write({\n 'state': 'progress',\n 'date_start': datetime.now(),\n })\n# timeline.create({\n# 'workorder_id': workorder.id,\n# 'workcenter_id': workorder.workcenter_id.id,\n# 'description': _('Time Tracking: ')+self.env.user.name,\n# 'loss_id': loss_id[0].id,\n# 'date_start': datetime.now(),\n# 'user_id': self.env.user.id\n# })\n return self.write({'state': 'progress',\n 'date_start': datetime.now(),\n })\n \n \nclass Workcenter(models.Model):\n _inherit = 'mrp.workcenter.productivity'\n\n ssi_job_id = fields.Many2one('ssi_jobs', related='workorder_id.ssi_job_id', string='Job', store=True)\n# ssi_job_id = fields.Many2one(\n# 'workorder_id.ssi_job_id', string='Job')\n # ssi_job_id = fields.Many2one(\n # related='workorder_id.ssi_job_id', relation=\"ssi_jobs.ssi_jobs\", string='Job', domain=[])\n \nclass Produciton(models.Model):\n _inherit = 'mrp.production'\n\n ssi_job_id = fields.Many2one('ssi_jobs', string='Job')\n job_stage = fields.Many2one('ssi_jobs_stage', related='ssi_job_id.stage_id', string=\"Job Stage\", store=True, readonly=True)\n product_category = fields.Many2one('product.category', related='product_id.categ_id', string=\"Product Category\", store=True, readonly=True)\n \nclass Routing(models.Model):\n _inherit = 'mrp.routing.workcenter'\n\n time_cycle_hours = fields.Float(\n 'Hour Duration', compute='_compute_cycle_hours',\n help=\"Time in hours.\")\n time_cycle_manual_hours = fields.Float(\n 'Manual Hour Duration', compute='_compute_cycle_manual_hours',\n help=\"Time in hours.\")\n hide_in_kiosk = fields.Boolean(default=False, string=\"Hide in Kiosk\")\n\n @api.depends('time_cycle')\n def _compute_cycle_hours(self):\n for record in self:\n record.time_cycle_hours = record.time_cycle / 60\n\n @api.depends('time_cycle_manual')\n def _compute_cycle_manual_hours(self):\n for record in self:\n record.time_cycle_manual_hours = record.time_cycle_manual / 60\n\n", "sub_path": "ssi_jobs/models/mrp.py", "file_name": "mrp.py", "file_ext": "py", "file_size_in_byte": 5278, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "odoo.models.Model", "line_number": 7, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 7, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 13, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 13, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 15, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 15, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 20, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 20, "usage_type": "name"}, {"api_name": "odoo.fields.Selection", "line_number": 23, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 23, "usage_type": "name"}, {"api_name": "odoo.fields.Datetime", "line_number": 24, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 24, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 25, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 25, "usage_type": "name"}, {"api_name": "odoo.fields.Boolean", "line_number": 26, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 26, "usage_type": "name"}, {"api_name": "odoo.api.depends", "line_number": 28, "usage_type": "call"}, {"api_name": "odoo.api", "line_number": 28, "usage_type": "name"}, {"api_name": "odoo.api.depends", "line_number": 33, "usage_type": "call"}, {"api_name": "odoo.api", "line_number": 33, "usage_type": "name"}, {"api_name": "odoo.api.multi", "line_number": 38, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "name"}, {"api_name": "odoo.api.multi", "line_number": 43, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 43, "usage_type": "name"}, {"api_name": "odoo.models.Model", "line_number": 79, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 79, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 82, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 82, "usage_type": "name"}, {"api_name": "odoo.models.Model", "line_number": 88, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 88, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 91, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 91, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 92, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 92, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 93, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 93, "usage_type": "name"}, {"api_name": "odoo.models.Model", "line_number": 95, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 95, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 98, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 98, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 101, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 101, "usage_type": "name"}, {"api_name": "odoo.fields.Boolean", "line_number": 104, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 104, "usage_type": "name"}, {"api_name": "odoo.api.depends", "line_number": 106, "usage_type": "call"}, {"api_name": "odoo.api", "line_number": 106, "usage_type": "name"}, {"api_name": "odoo.api.depends", "line_number": 111, "usage_type": "call"}, {"api_name": "odoo.api", "line_number": 111, "usage_type": "name"}]} +{"seq_id": "530068524", "text": "from django.shortcuts import HttpResponse\nfrom django.http import JsonResponse \nfrom .models import Post\nfrom .serializers import PostSerializer\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom django.core.cache import cache\nfrom rest_framework.exceptions import ValidationError\n\n\n@api_view(['GET','POST'])\n@permission_classes([AllowAny])\ndef post_list(request):\n if request.method == 'GET':\n posts = Post.objects.all()\n serializer = PostSerializer(posts, many=True)\n return JsonResponse(serializer.data, safe=False)\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = PostSerializer(data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n \n@api_view(['GET','PUT','DELETE'])\n@permission_classes([AllowAny])\ndef post_detail(request, pk):\n try:\n posts = Post.objects.get(pk=pk)\n except Post.DoesNotExist:\n return HttpResponse(status=404)\n if request.method == 'GET':\n serializer = PostSerializer(posts)\n return JsonResponse(serializer.data, safe=False)\n elif request.method == 'PUT':\n data = JSONParser.parse(request)\n serializer = PostSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n elif request.method == 'DELETE':\n posts.delete()\n return HttpResponse(status=204)\n # else ?\n\n\n@api_view(['GET','POST'])\n@permission_classes([AllowAny])\ndef like_post(request, pk):\n try:\n posts = Post.objects.get(pk=pk)\n except Post.DoesNotExist:\n return HttpResponse(status=404)\n ip = request.META.get(\"HTTP_REMOTE_ADDR\")\n model_name = \"like\"\n key = '%s_%s' % (model_name, ip)\n if not cache.get(key) == pk:\n cache.set(key, pk, 2)\n Post.objects.get(pk=pk).like()\n return HttpResponse(status=201)\n return HttpResponse(status=400)\n\n@api_view(['GET','POST'])\n@permission_classes([AllowAny]) \ndef dislike_post(request, pk):\n try:\n posts = Post.objects.get(pk=pk)\n except Post.DoesNotExist:\n return HttpResponse(status=404)\n ip = request.META.get(\"HTTP_REMOTE_ADDR\")\n model_name = \"dislike\"\n key = '%s_%s' % (model_name, ip)\n if not cache.get(key) == pk:\n cache.set(key, pk, 2)\n Post.objects.get(pk=pk).dislike()\n return HttpResponse(status=201)\n return HttpResponse(status=400)\n\n@api_view(['GET','POST'])\n@permission_classes([AllowAny])\ndef visit_count(request, pk):\n try:\n posts = Post.objects.get(pk=pk)\n except Post.DoesNotExist:\n return HttpResponse(status=404)\n ip = request.META.get(\"HTTP_REMOTE_ADDR\")\n model_name = \"view\"\n key = '%s_%s' % (model_name, ip)\n if not cache.get(key) == pk:\n cache.set(key, pk, 2)\n Post.objects.get(pk=pk).view()\n return HttpResponse(status=201)\n return HttpResponse(status=400)\n\n@api_view(['GET','PUT','DELETE'])\n@permission_classes([AllowAny])\ndef score(request, pk): \n try:\n post = Post.objects.get(pk=pk)\n except Post.DoesNotExist:\n return HttpResponse(status=404)\n ip = request.META.get(\"HTTP_REMOTE_ADDR\")\n model_name = \"score\"\n value = int(request.GET['value'])\n key = '%s_%s' % (model_name, ip)\n if not cache.get(key) == pk:\n cache.set(key, pk, 2)\n post.calculate_score(value)\n return HttpResponse(status=201)\n return HttpResponse(status=400)\n", "sub_path": "blog/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3828, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "models.Post.objects.all", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 18, "usage_type": "name"}, {"api_name": "serializers.PostSerializer", "line_number": 19, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.parsers.JSONParser", "line_number": 22, "usage_type": "call"}, {"api_name": "serializers.PostSerializer", "line_number": 23, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 26, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 15, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 33, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 33, "usage_type": "name"}, {"api_name": "models.Post.DoesNotExist", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 34, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 35, "usage_type": "call"}, {"api_name": "serializers.PostSerializer", "line_number": 37, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 38, "usage_type": "call"}, {"api_name": "rest_framework.parsers.JSONParser.parse", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.parsers.JSONParser", "line_number": 40, "usage_type": "name"}, {"api_name": "serializers.PostSerializer", "line_number": 41, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 44, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 45, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 30, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 30, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 56, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 56, "usage_type": "name"}, {"api_name": "models.Post.DoesNotExist", "line_number": 57, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 57, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 58, "usage_type": "call"}, {"api_name": "django.core.cache.cache.get", "line_number": 62, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 62, "usage_type": "name"}, {"api_name": "django.core.cache.cache.set", "line_number": 63, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 63, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 64, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 64, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 64, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 65, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 53, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 72, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 72, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 72, "usage_type": "name"}, {"api_name": "models.Post.DoesNotExist", "line_number": 73, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 73, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 74, "usage_type": "call"}, {"api_name": "django.core.cache.cache.get", "line_number": 78, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 78, "usage_type": "name"}, {"api_name": "django.core.cache.cache.set", "line_number": 79, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 79, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 80, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 80, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 80, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 81, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 82, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 68, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 69, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 69, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 88, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 88, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 88, "usage_type": "name"}, {"api_name": "models.Post.DoesNotExist", "line_number": 89, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 89, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 90, "usage_type": "call"}, {"api_name": "django.core.cache.cache.get", "line_number": 94, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 94, "usage_type": "name"}, {"api_name": "django.core.cache.cache.set", "line_number": 95, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 95, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 96, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 96, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 97, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 98, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 84, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 85, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 85, "usage_type": "name"}, {"api_name": "models.Post.objects.get", "line_number": 104, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 104, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 104, "usage_type": "name"}, {"api_name": "models.Post.DoesNotExist", "line_number": 105, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 105, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 106, "usage_type": "call"}, {"api_name": "django.core.cache.cache.get", "line_number": 111, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 111, "usage_type": "name"}, {"api_name": "django.core.cache.cache.set", "line_number": 112, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 112, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 114, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 115, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 100, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 101, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 101, "usage_type": "name"}]} +{"seq_id": "60306132", "text": "import os as os\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport sys\nfrom util import *\nfrom config import *\nfrom data_loader import *\nfrom localizer import *\n\ndef main(config):\n if config.operation_mode == 'Train':\n train(config)\n elif config.operation_mode == 'Test':\n print('Test')\n else:\n assert False, 'Invalid operation mode : {}'.format(config.operation_mode)\n\ndef train(config):\n\n if not os.path.exists(config.localizer_log):\n os.makedirs(config.localizer_log)\n if not os.path.exists(config.localizer_log + config.localizer_checkpoint):\n os.makedirs(config.localizer_log + config.localizer_checkpoint)\n if not os.path.exists(config.localizer_log + config.localizer_result):\n os.makedirs(config.localizer_log + config.localizer_result)\n if not os.path.exists(config.checkpoint_repository):\n os.makedirs(config.checkpoint_repository)\n\n tensor_config = tf.ConfigProto(log_device_placement=config.log_gpu_info,\n device_count={'GPU': 1})\n tensor_config.gpu_options.allow_growth = True\n\n train_mode_list = parse_train_mode(config.train_mode)\n if 'Localize' in train_mode_list:\n train_localize(config, tensor_config)\n if 'Align' in train_mode_list:\n print('[Not Implemented] Align - Train')\n if 'Classify' in train_mode_list:\n print('[Not Implemented] Classify - Train')\n\ndef train_localize(config, tensor_config):\n #init data loader\n data_loader = DataLoader(config, 'train_localize',\n config.localize_image_resize_w, config.localize_image_resize_h)\n with tf.Session(config=tensor_config) as sess:\n localizer = Localizer(\n sess = sess,\n data_loader = data_loader,\n ensemble_size= config.localize_ensemble_size,\n input_size=(config.localize_image_resize_w, config.localize_image_resize_h),\n minibatch_size=config.localize_minibatch_size,\n base_lr=config.localize_base_lr,\n log_path=config.localizer_log,\n checkpoint_path=config.localizer_checkpoint\n )\n localizer.do_train()\n\nif __name__ == \"__main__\":\n config, unparsed = get_config()\n sys.exit(main(config))", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2268, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "config.operation_mode", "line_number": 12, "usage_type": "attribute"}, {"api_name": "config.operation_mode", "line_number": 14, "usage_type": "attribute"}, {"api_name": "config.operation_mode", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "config.localizer_log", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 22, "usage_type": "call"}, {"api_name": "config.localizer_log", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "config.localizer_log", "line_number": 23, "usage_type": "attribute"}, {"api_name": "config.localizer_checkpoint", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 24, "usage_type": "call"}, {"api_name": "config.localizer_log", "line_number": 24, "usage_type": "attribute"}, {"api_name": "config.localizer_checkpoint", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "config.localizer_log", "line_number": 25, "usage_type": "attribute"}, {"api_name": "config.localizer_result", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 26, "usage_type": "call"}, {"api_name": "config.localizer_log", "line_number": 26, "usage_type": "attribute"}, {"api_name": "config.localizer_result", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "config.checkpoint_repository", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 28, "usage_type": "call"}, {"api_name": "config.checkpoint_repository", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.ConfigProto", "line_number": 30, "usage_type": "call"}, {"api_name": "config.log_gpu_info", "line_number": 30, "usage_type": "attribute"}, {"api_name": "config.train_mode", "line_number": 34, "usage_type": "attribute"}, {"api_name": "config.localize_image_resize_w", "line_number": 45, "usage_type": "attribute"}, {"api_name": "config.localize_image_resize_h", "line_number": 45, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 46, "usage_type": "call"}, {"api_name": "config.localize_ensemble_size", "line_number": 50, "usage_type": "attribute"}, {"api_name": "config.localize_image_resize_w", "line_number": 51, "usage_type": "attribute"}, {"api_name": "config.localize_image_resize_h", "line_number": 51, "usage_type": "attribute"}, {"api_name": "config.localize_minibatch_size", "line_number": 52, "usage_type": "attribute"}, {"api_name": "config.localize_base_lr", "line_number": 53, "usage_type": "attribute"}, {"api_name": "config.localizer_log", "line_number": 54, "usage_type": "attribute"}, {"api_name": "config.localizer_checkpoint", "line_number": 55, "usage_type": "attribute"}, {"api_name": "localizer.do_train", "line_number": 57, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "367679280", "text": "import numpy as np\nfrom enum import Enum\nfrom .closed_eyes_detector import EyesState\nfrom ._eye_utils import EyeUtils\n\n\nclass HorzGazeDirection(Enum):\n Forward = 0\n Left = 1\n Right = 2\n\n def __str__(self):\n return {\n HorzGazeDirection.Left: 'left',\n HorzGazeDirection.Forward: 'forward',\n HorzGazeDirection.Right: 'right'\n }[self]\n\n\nclass VertGazeDirection(Enum):\n Forward = 0\n Up = 1\n Down = 2\n\n def __str__(self):\n return {\n VertGazeDirection.Up: 'up',\n VertGazeDirection.Forward: 'forward',\n VertGazeDirection.Down: 'down'\n }[self]\n\n\nEYE_POINTS = 24\nPUPIL_POINTS = 9\nHORZ_FACTOR = 0.5\nVERT_FACTOR = 0.5\n\n\nclass EyeGazeDirectionDetector:\n def __init__(self):\n self._prev_result = HorzGazeDirection.Forward, VertGazeDirection.Forward\n\n def __call__(self, context, result):\n state = context.get('eyes_state', EyesState.Opened)\n if state == EyesState.Closed:\n result['eyes_gaze_direction'] = self._prev_result\n else:\n face_keypoints = context['face_keypoints']\n face_basis_rotated = context['face_basis_rotated']\n\n pupil = context['left_eye_pupil']\n pupil = face_basis_rotated.to_basis(pupil)\n values = face_keypoints['left_eye'].values()\n points = [face_basis_rotated.to_basis(v).as_tuple() for v in values]\n x1, y1, x2, y2 = EyeUtils.get_eye_box(points, axis=0)\n\n left_result = self.eye_gaze_detector(pupil.as_tuple(), (x1, x2), (y1, y2))\n\n pupil = context['right_eye_pupil']\n pupil = face_basis_rotated.to_basis(pupil)\n values = face_keypoints['right_eye'].values()\n points = [face_basis_rotated.to_basis(v).as_tuple() for v in values]\n x1, y1, x2, y2 = EyeUtils.get_eye_box(points, axis=0)\n\n right_result = self.eye_gaze_detector(pupil.as_tuple(), (x1, x2), (y1, y2))\n\n gaze_direction = self.mean_gaze_direction(left_result, right_result)\n\n if gaze_direction[0] < 0:\n horz = HorzGazeDirection.Right\n elif gaze_direction[0] > 0:\n horz = HorzGazeDirection.Left\n else:\n horz = HorzGazeDirection.Forward\n\n if gaze_direction[1] < 0:\n vert = VertGazeDirection.Up\n elif gaze_direction[1] > 0:\n vert = VertGazeDirection.Down\n else:\n vert = VertGazeDirection.Forward\n\n result['eyes_gaze_direction'] = horz, vert\n self._prev_result = result['eyes_gaze_direction']\n\n return context\n\n @staticmethod\n def get_diff(pupil_proj, width, factor):\n index = int(round((pupil_proj / width) * EYE_POINTS))\n\n left = index - int(PUPIL_POINTS / 2)\n right = index + int(PUPIL_POINTS / 2)\n\n line = [1] * EYE_POINTS\n\n line[left:right] = [0] * PUPIL_POINTS\n left_sum = sum(line[:index])\n right_sum = sum(line[index + 1:])\n\n if abs(left_sum - right_sum) > PUPIL_POINTS * factor:\n if left_sum > right_sum:\n return left_sum - right_sum\n else:\n return left_sum - right_sum\n else:\n return 0\n\n def eye_gaze_detector(self, pupil, horz_points, vert_points):\n pupil_x, pupil_y = pupil\n\n x1, x2 = horz_points\n\n horz_width = x2 - x1\n pupil_proj = pupil_x - x1\n\n horz_direction = self.get_diff(pupil_proj, horz_width, HORZ_FACTOR)\n\n y1, y2 = vert_points\n\n vert_width = y2 - y1\n pupil_proj = pupil_y - y1\n\n vert_direction = self.get_diff(pupil_proj, vert_width, VERT_FACTOR)\n\n return horz_direction, vert_direction\n\n @staticmethod\n def mean_gaze_direction(left_direction_result, right_direction_result):\n result = np.mean([list(left_direction_result), list(right_direction_result)], axis=0)\n\n horz_direction, vert_direction = 0, 0\n if abs(result[0]) > PUPIL_POINTS * HORZ_FACTOR:\n horz_direction = 1 * np.sign(result[0])\n if abs(result[1]) > PUPIL_POINTS * VERT_FACTOR:\n vert_direction = 1 * np.sign(result[1])\n\n return horz_direction, vert_direction\n", "sub_path": "api/video_processing/agency/extraction/base_features/eyes_gaze_detector.py", "file_name": "eyes_gaze_detector.py", "file_ext": "py", "file_size_in_byte": 4293, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "enum.Enum", "line_number": 7, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 20, "usage_type": "name"}, {"api_name": "closed_eyes_detector.EyesState.Opened", "line_number": 44, "usage_type": "attribute"}, {"api_name": "closed_eyes_detector.EyesState", "line_number": 44, "usage_type": "name"}, {"api_name": "closed_eyes_detector.EyesState.Closed", "line_number": 45, "usage_type": "attribute"}, {"api_name": "closed_eyes_detector.EyesState", "line_number": 45, "usage_type": "name"}, {"api_name": "_eye_utils.EyeUtils.get_eye_box", "line_number": 55, "usage_type": "call"}, {"api_name": "_eye_utils.EyeUtils", "line_number": 55, "usage_type": "name"}, {"api_name": "_eye_utils.EyeUtils.get_eye_box", "line_number": 63, "usage_type": "call"}, {"api_name": "_eye_utils.EyeUtils", "line_number": 63, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 136, "usage_type": "call"}]} +{"seq_id": "57984612", "text": "import requests\nimport os\nimport signal\nfrom monitor import Monitor\nimport multiprocessing\nimport chart\nimport time\n# import trades\nimport tradingview\nfrom tinydb import TinyDB, Query\nfrom creds import bot_token\n\nALERTS = \"/var/www/outputs/alerts.txt\"\nBOT_URL = \"https://api.telegram.org/bot{}/\".format(bot_token)\n\ndb_state = multiprocessing.Value('i')\n\n\ndef handle_update(update):\n\n text = update[\"message\"][\"text\"].lower()\n chat = update[\"message\"][\"chat\"][\"id\"]\n try:\n request = text.split(\" \")\n command = request[0]\n\n if command == \"/users\":\n db = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n users = db.all()\n text = \"USERS: \"\n for user in users:\n text += str(user[\"id\"]) + \"\\n\"\n\n if command == \"/chart\":\n ticker = request[1].upper()\n try:\n chart.make_graph(ticker, 10, 30)\n except Exception as e:\n send_message(\"Error parsing data. Invalid ticker or API timeout\\n\"+str(e), chat)\n return\n\n # command for parsing tradingview website\n elif command == \"/ideas\":\n pages = int(request[1])\n hours = int(request[2])\n if pages > 20 or pages < 1:\n send_message(\"Max number of pages is 20\", chat)\n return\n elif hours < 1:\n send_message(\"Please input positive number of hours\", chat)\n return\n else:\n try:\n text = \"Parsing {} pages of tradingview.com in the last {} hours...\".format(str(pages), str(hours))\n send_message(text, chat)\n text = tradingview.sort_and_order(tradingview.parse(pages, hours))\n except Exception as e:\n send_message(\"Error parsing tradingview\\n\"+str(e), chat)\n\n # command for current bids/trades\n # elif command == \"trades\":\n # text = trades.calculate(coins)\n\n elif command == \"/help\":\n text = \"/ideas *pages* *hours* - parse ideas from #pages of tradingview.com in the last #hours\\n\" + \\\n \"/monitor - begin monitoring crossovers of rsi, macd and volume above daily average\\n\" + \\\n \"/stop - stop monitoring\\n\" + \\\n \"/chart *ticker* - get a 24 hour graph of selected currency from poloniex\\n\"\n\n # command for setting up alarm notifications\n elif command == \"/monitor\":\n db = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n User = Query()\n\n if db.search(User.id == chat):\n text = \"Already subscribed\"\n db.close()\n\n else:\n if not db.all():\n db_state.value = 0\n monitor_d = multiprocessing.Process(target=monitor_daemon, args=[db_state])\n monitor_d.daemon = True\n monitor_d.start()\n text = \"Monitoring process with PID {} is created\".format(str(monitor_d.pid))\n\n # write PID to textfile\n try:\n with open(ALERTS, 'w') as alerts:\n alerts.write(str(monitor_d.pid))\n\n except Exception as e:\n text = \"Failed to write pid to file\"\n send_message(str(e) + text, chat)\n return\n\n db.insert({\"id\": chat})\n db.close()\n db_state.value = 1\n\n elif command == \"/stop\":\n db = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n User = Query()\n db.remove(User.id == chat)\n db_state.value = 1\n\n try:\n if not db.all():\n with open(ALERTS, 'r') as alerts:\n pid = int(alerts.read())\n os.kill(pid, signal.SIGKILL)\n text = \"Price monitoring stopped\\n\"\n db.close()\n except Exception as e:\n text = \"Processes were not stopped\\n\" + str(e)\n\n elif command == \"/purge\":\n db = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n db.purge()\n with open(ALERTS, 'r') as alerts:\n pid = int(alerts.read())\n os.kill(pid, signal.SIGKILL)\n text = \"Price monitoring stopped for all users\\n\"\n db.close()\n\n if request[0] == \"/chart\":\n send_photo(chat)\n else:\n send_message(text, chat)\n\n except Exception as e:\n print(e)\n send_message(str(e) + \"\\n in handle_update\", chat)\n\n\ndef monitor_daemon(db_update):\n interval = 120\n\n def update_users():\n database = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n users_upd = database.all()\n database.close()\n print(\"updated users\")\n return users_upd\n\n monitor = Monitor()\n\n db = TinyDB(os.path.join(os.path.dirname(__file__), 'db.json'))\n users = db.all()\n db.close()\n\n while True:\n try:\n if db_update.value:\n users = update_users()\n db_update.value = 0\n\n text = monitor.monitor()\n if text:\n for user in users:\n send_message(text, user[\"id\"])\n time.sleep(interval)\n\n except Exception as e:\n print(\"Exception in main loop \" + str(e))\n return\n\n\ndef send_message(text, chat_id):\n url = BOT_URL+\"sendMessage\"\n data = {'chat_id': chat_id, 'text': text}\n request = requests.post(url, data=data)\n\n\ndef send_photo(chat_id):\n url = BOT_URL+\"sendPhoto\"\n files = {'photo': open(os.path.join(os.path.dirname(__file__), \"example.png\"), 'rb')}\n data = {'chat_id': chat_id}\n request = requests.post(url, data=data, files=files)\n\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n", "sub_path": "telegram.py", "file_name": "telegram.py", "file_ext": "py", "file_size_in_byte": 6035, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "creds.bot_token", "line_number": 14, "usage_type": "argument"}, {"api_name": "multiprocessing.Value", "line_number": 16, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 28, "usage_type": "call"}, {"api_name": "chart.make_graph", "line_number": 37, "usage_type": "call"}, {"api_name": "tradingview.sort_and_order", "line_number": 56, "usage_type": "call"}, {"api_name": "tradingview.parse", "line_number": 56, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 72, "usage_type": "call"}, {"api_name": "tinydb.Query", "line_number": 73, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 82, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 102, "usage_type": "call"}, {"api_name": "tinydb.Query", "line_number": 103, "usage_type": "call"}, {"api_name": "os.kill", "line_number": 111, "usage_type": "call"}, {"api_name": "signal.SIGKILL", "line_number": 111, "usage_type": "attribute"}, {"api_name": "tinydb.TinyDB", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path", "line_number": 118, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 118, "usage_type": "call"}, {"api_name": "os.kill", "line_number": 122, "usage_type": "call"}, {"api_name": "signal.SIGKILL", "line_number": 122, "usage_type": "attribute"}, {"api_name": "tinydb.TinyDB", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 140, "usage_type": "call"}, {"api_name": "monitor.Monitor", "line_number": 146, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path", "line_number": 148, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 148, "usage_type": "call"}, {"api_name": "monitor.monitor", "line_number": 158, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 162, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 177, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 179, "usage_type": "call"}]} +{"seq_id": "129690543", "text": "import os\nimport ROOT\nfrom ROOT import RooFit as rf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\n\n\ndef array2hist(counts, hist):\n for iBin in range(1, hist.GetNbinsX() + 1):\n hist.SetBinContent(iBin, counts[iBin-1])\n hist.SetBinError(iBin, np.sqrt(counts[iBin-1]))\n\n\ndef ndarray2roo(ndarray, var):\n if isinstance(ndarray, ROOT.RooDataSet):\n print('Already a RooDataSet')\n return ndarray\n\n assert isinstance(ndarray, np.ndarray), 'Did not receive NumPy array'\n assert len(ndarray.shape) == 1, 'Can only handle 1d array'\n\n name = var.GetName()\n x = np.zeros(1, dtype=np.float64)\n\n tree = ROOT.TTree('tree', 'tree')\n tree.Branch(f'{name}', x, f'{name}/D')\n\n for i in ndarray:\n x[0] = i\n tree.Fill()\n\n array_roo = ROOT.RooDataSet(\n 'data', 'dataset from tree', tree, ROOT.RooArgSet(var))\n return array_roo\n\n\ndef significance_error(signal, background, signal_error=None, background_error=None):\n\n if not signal_error:\n signal_error = np.sqrt(signal + 1e-10)\n if not background_error:\n background_error = np.sqrt(background + 1e-10)\n sb = signal + background + 1e-10\n sb_sqrt = np.sqrt(sb)\n\n s_propag = (sb_sqrt + signal / (2 * sb_sqrt))/sb * signal_error\n b_propag = signal / (2 * sb_sqrt)/sb * background_error\n\n if signal+background == 0:\n return 0\n\n return np.sqrt(s_propag * s_propag + b_propag * b_propag)\n\n\ndef unbinned_mass_fit(data, eff, bkg_model, output_dir, bkg_dir, cent_class, pt_range, ct_range, split, cent_string = '', bins=38, ws_name=''):\n\n # define working variable\n mass = ROOT.RooRealVar('m', 'm_{^{3}He+#pi}', 2.96, 3.04, 'GeV/c^{2}')\n\n # define signal parameters\n hyp_mass = ROOT.RooRealVar(\n 'hyp_mass', 'hypertriton mass', 2.96, 3.04, 'GeV/c^{2}')\n width = ROOT.RooRealVar('width', 'hypertriton width',\n 0.001, 0.003, 'GeV/c^{2}')\n\n # define signal component\n signal = ROOT.RooGaussian(\n 'signal', 'signal component pdf', mass, hyp_mass, width)\n\n # define background parameters\n slope = ROOT.RooRealVar('slope', 'exponential slope', -100., 100.)\n\n c0 = ROOT.RooRealVar('c0', 'constant c0', -2,2)\n c1 = ROOT.RooRealVar('c1', 'constant c1', -2, 2)\n c2 = ROOT.RooRealVar('c2', 'constant c2', -2, 2)\n\n # define background component depending on background model required\n if bkg_model == 'pol0':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol0 bkg', mass, ROOT.RooArgList(c0))\n\n if bkg_model == 'pol1':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol1 bkg', mass, ROOT.RooArgList(c0, c1))\n\n if bkg_model == 'pol2':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol2 for bkg', mass, ROOT.RooArgList(c0, c1, c2))\n\n if bkg_model == 'expo':\n background = ROOT.RooExponential('bkg', 'expo for bkg', mass, slope)\n\n # define signal and background normalization\n n_sig = ROOT.RooRealVar('n_sig', 'n_sig', 0., 1000, 'GeV')\n n_bkg = ROOT.RooRealVar('n_bkg', 'n_bkg', 0., 1000, 'GeV')\n\n\n\n # define the fit funciton -> signal component + background component\n fit_function = ROOT.RooAddPdf('model', 'signal + background',\n ROOT.RooArgList(signal, background), ROOT.RooArgList(n_sig, n_bkg))\n\n # convert data to RooData\n roo_data = ndarray2roo(data, mass)\n\n # fit data\n fit_function.fitTo(roo_data, rf.Range(\n 2.96, 3.04))\n\n # plot the fit\n frame = mass.frame(bins)\n frame.SetTitle(\"\")\n\n roo_data.plotOn(frame)\n fit_function.plotOn(frame, rf.LineColor(ROOT.kBlue))\n #fit_function.plotOn(frame, rf.Components('signal'), rf.LineStyle(ROOT.kDotted), rf.LineColor(ROOT.kRed))\n fit_function.plotOn(frame, rf.Components(\n 'bkg'), rf.LineStyle(ROOT.kDashed), rf.LineColor(ROOT.kRed))\n\n # add info to plot\n nsigma = 3\n mu = hyp_mass.getVal()\n mu_error = hyp_mass.getError()\n sigma = width.getVal()\n sigma_error = width.getError()\n\n # compute significance\n mass.setRange('signal region', mu -\n (nsigma * sigma), mu + (nsigma * sigma))\n \n range_lower = mu - (nsigma * sigma)\n range_upper = mu + (nsigma * sigma)\n \n n_sig_val = n_sig.getVal()\n n_bkg_val = n_bkg.getVal()\n \n\n\n signal_counts = signal.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_sig_val\n signal_error = signal.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * (n_sig.getError())\n \n\n background_counts = background.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_bkg_val\n background_error = background.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * (n_bkg.getError())\n\n\n signif = signal_counts / np.sqrt(signal_counts + background_counts + 1e-10)\n signif_error = significance_error(signal_counts, background_counts, signal_error, background_error)\n\n pinfo = ROOT.TPaveText(0.537, 0.474, 0.937, 0.875, 'NDC')\n pinfo.SetBorderSize(0)\n pinfo.SetFillStyle(0)\n pinfo.SetTextAlign(30+3)\n pinfo.SetTextFont(42)\n # pinfo.SetTextSize(12)\n\n decay_label = {\n '': '{}^{3}_{#Lambda}H#rightarrow ^{3}He #pi^{-} + c.c.',\n '_matter': '{}^{3}_{#Lambda}H#rightarrow ^{3}He #pi^{-}',\n '_antimatter': '{}^{3}_{#bar{#Lambda}}#bar{H}#rightarrow ^{3}#bar{He}#pi^{+}',\n }\n\n string_list = []\n\n string_list.append(f'ALICE Internal, p-Pb 2016 + 2013, {cent_class[0]}-{cent_class[1]}%')\n string_list.append(\n decay_label[split] + ' %i #leq #it{p}_{T} < %i GeV/#it{c} ' % (pt_range[0], pt_range[1]))\n string_list.append(f'#mu = {mu*1000:.2f} #pm {mu_error*1000:.2f} ' + 'MeV/#it{c}^{2}')\n string_list.append(f'#sigma = {sigma*1000:.2f} #pm {sigma_error*1000:.2f} ' + 'MeV/#it{c}^{2}')\n\n if roo_data.sumEntries() > 0:\n string_list.append('#chi^{2} / NDF = ' + f'{frame.chiSquare(4):.2f}')\n\n string_list.append(f'Significance ({nsigma:.0f}#sigma) = {signif:.1f} #pm {signif_error:.1f}')\n string_list.append(f'S ({nsigma:.0f}#sigma) = {signal_counts:.1f} #pm {signal_error:.1f}')\n string_list.append(f'B ({nsigma:.0f}#sigma) = {background_counts:.1f} #pm {background_error:.1f}')\n\n if background_counts > 0:\n\n ratio = signal_counts / background_counts\n string_list.append(f'S/B ({nsigma:.0f}#sigma) = {ratio:.2f}')\n\n for s in string_list:\n pinfo.AddText(s)\n\n frame.addObject(pinfo)\n if output_dir != '':\n output_dir.cd()\n binning = 1000*((3.04-2.96)/bins)\n stry= f\"Events/({binning:.2f}\"\n stry += \"MeV/#it{c}^{2})\"\n frame.SetYTitle(stry)\n cv = ROOT.TCanvas(f\"cv_gaus_{round(eff,2)}_{cent_string}\")\n frame.Draw()\n if output_dir != '':\n cv.Write()\n \n if ws_name != '':\n w = ROOT.RooWorkspace(ws_name)\n mc = ROOT.RooStats.ModelConfig(\"ModelConfig\",w)\n mc.SetPdf(fit_function)\n mc.SetParametersOfInterest(ROOT.RooArgSet(n_sig))\n mc.SetObservables(ROOT.RooArgSet(mass))\n if bkg_model=='pol1':\n w.defineSet(\"nuisParams\",\"n_bkg,c0,c1\")\n mc.SetNuisanceParameters(w.set('nuisParams'))\n if bkg_model=='expo':\n w.defineSet(\"nuisParams\",\"slope\")\n mc.SetNuisanceParameters(w.set('nuisParams'))\n getattr(w,'import')(mc)\n getattr(w,'import')(roo_data)\n if not os.path.exists('../Utils/Workspaces'):\n os.makedirs('../Utils/Workspaces')\n w.writeToFile(f'../Utils/Workspaces/{ws_name}.root', True)\n\n\n # bkg_dir.cd()\n # background.SetName(f\"bkg_pdf_{round(eff,2)}_{cent_string}\")\n # background.SetTitle(f\"bkg_pdf_{round(eff,2)}_{cent_string}\")\n # background.Write()\n\n return signal_counts, signal_error, signif, signif_error, mu, mu_error, sigma, sigma_error, range_lower, range_upper\n\n\ndef unbinned_mass_fit_mc(data, eff, bkg_model, signal_hist, output_dir, bkg_dir, cent_class, pt_range, ct_range, split, cent_string = '', bins=38, sign_range = [2.96,3.04]):\n\n # define working variable\n mass = ROOT.RooRealVar('m', 'm_{^{3}He+#pi}', 2.96, 3.04, 'GeV/c^{2}')\n\n\n # define signal component\n hist_signal = ROOT.RooDataHist('signal_hist', 'signal_hist', ROOT.RooArgList(mass), signal_hist)\n signal = ROOT.RooHistPdf(\"histpdf1\", \"histpdf1\", ROOT.RooArgSet(mass), hist_signal, 0)\n\n\n slope = ROOT.RooRealVar('slope', 'exponential slope', -100., 100.)\n c0 = ROOT.RooRealVar('c0', 'constant c0', -2,2)\n c1 = ROOT.RooRealVar('c1', 'constant c1', -2, 2)\n c2 = ROOT.RooRealVar('c2', 'constant c2', -2, 2)\n\n # define background component depending on background model required\n if bkg_model == 'pol0':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol0 bkg', mass, ROOT.RooArgList())\n\n if bkg_model == 'pol1':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol1 bkg', mass, ROOT.RooArgList(c0, c1))\n\n if bkg_model == 'pol2':\n background = ROOT.RooPolynomial(\n 'bkg', 'pol2 for bkg', mass, ROOT.RooArgList(c0, c1, c2))\n\n if bkg_model == 'expo':\n background = ROOT.RooExponential('bkg', 'expo for bkg', mass, slope)\n\n\n # define signal and background normalization\n n1 = ROOT.RooRealVar('n1', 'n1 const', 0., 1, 'GeV')\n\n\n\n # define the fit funciton -> signal component + background component\n fit_function = ROOT.RooAddPdf('model', 'signal + background', ROOT.RooArgList(signal, background), ROOT.RooArgList(n1))\n\n # convert data to RooData\n roo_data = ndarray2roo(data, mass)\n\n # fit data\n fit_function.fitTo(roo_data, rf.Range(\n 2.96, 3.04))\n\n # plot the fit\n frame = mass.frame(bins)\n frame.SetTitle(\"\")\n\n roo_data.plotOn(frame)\n fit_function.plotOn(frame, rf.LineColor(ROOT.kBlue))\n #fit_function.plotOn(frame, rf.Components('signal'), rf.LineStyle(ROOT.kDotted), rf.LineColor(ROOT.kRed))\n fit_function.plotOn(frame, rf.Components(\n 'bkg'), rf.LineStyle(ROOT.kDashed), rf.LineColor(ROOT.kRed))\n\n # add info to plot\n \n signal_counts = len(data)*n1.getVal()\n signal_error = signal_counts*(n1.getError()/n1.getVal())\n background_counts = len(data) - signal_counts\n background_error = background_counts*(n1.getError()/n1.getVal())\n\n mass.setRange('signal region', sign_range[0], sign_range[1])\n \n \n n_sig = signal_counts\n n_bkg = background_counts\n\n rel_err = n1.getError()/n1.getVal()\n n_sig_err = n_sig*rel_err\n n_bkg_err = n_bkg*rel_err\n\n signal_counts = signal.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_sig\n signal_error = signal.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_sig *rel_err\n \n\n background_counts = background.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_bkg\n background_error = background.createIntegral(ROOT.RooArgSet(\n mass), ROOT.RooArgSet(mass), 'signal region').getVal() * n_bkg *rel_err\n\n signif = signal_counts / np.sqrt(signal_counts + background_counts + 1e-10)\n signif_error = significance_error(signal_counts, background_counts, signal_error, background_error)\n\n pinfo = ROOT.TPaveText(0.537, 0.474, 0.937, 0.875, 'NDC')\n pinfo.SetBorderSize(0)\n pinfo.SetFillStyle(0)\n pinfo.SetTextAlign(30+3)\n pinfo.SetTextFont(42)\n\n\n decay_label = {\n '': '{}^{3}_{#Lambda}H#rightarrow ^{3}He #pi^{-} + c.c.',\n '_matter': '{}^{3}_{#Lambda}H#rightarrow ^{3}He #pi^{-}',\n '_antimatter': '{}^{3}_{#bar{#Lambda}}#bar{H}#rightarrow ^{3}#bar{He}#pi^{+}',\n }\n\n string_list = []\n string_list.append(f'Signal = {n_sig:.1f} #pm {n_sig_err:.1f}') \n string_list.append(f'Significance ({3:.0f}#sigma) = {signif:.1f} #pm {signif_error:.1f}')\n\n if roo_data.sumEntries() > 0:\n string_list.append('#chi^{2} / NDF = ' + f'{frame.chiSquare(4):.2f}')\n\n if background_counts > 0:\n\n ratio = signal_counts / background_counts\n string_list.append(f'S/B ({3:.0f}#sigma) = {ratio:.2f}')\n\n for s in string_list:\n pinfo.AddText(s)\n\n frame.addObject(pinfo)\n if output_dir != '':\n output_dir.cd()\n binning = 1000*((3.04-2.96)/bins)\n stry= f\"Events/({binning:.2f}\"\n stry += \"MeV/#it{c}^{2})\"\n frame.SetYTitle(stry)\n cv = ROOT.TCanvas(f\"cv_templ_{round(eff,2)}_{bkg_model}_{cent_string}\")\n frame.Draw()\n\n if output_dir != '':\n cv.Write()\n if bkg_dir != '':\n bkg_dir.cd()\n background.SetName(f\"bkg_pdf_{round(eff,2)}_{cent_string}\")\n background.SetTitle(f\"bkg_pdf_{round(eff,2)}_{cent_string}\")\n background.Write()\n\n return n_sig, n_sig_err, n1\n\n\n\ndef computeAverage(Vals, breakVal = 100):\n Mean = 0\n Stat = 0\n Sys1 = 0\n Sys2 = 0\n weight = 0\n for Bin in Vals:\n w = Bin[\"bin\"][1] - Bin[\"bin\"][0]\n if Bin[\"bin\"][0] >= breakVal:\n break\n weight = weight + w\n Mean = Mean + (Bin[\"measure\"][0] * w)\n Stat = np.hypot(Stat, Bin[\"measure\"][1] * w)\n Sys1 = Sys1 + (Bin[\"measure\"][2] * w)\n Sys2 = Sys2 + (Bin[\"measure\"][3] * w)\n return [Mean / weight, Stat / weight, Sys1 / weight, Sys2 / weight]\n\ndef myHypot(x, y, z=0, w=0):\n return np.sqrt(x**2 + y**2 + z**2 + w**2)\n\n\ndef significance_scan(eff_cut, cut_array, dataH, eff_presel, working_point=None, syst_range=0.05):\n\n hyp_mass = 2.991\n sigma = 0.0015\n m_min = hyp_mass - 3*sigma\n m_max = hyp_mass + 3*sigma\n\n pol_degree = 0\n bins = 36\n bin_width = (3.04-2.96)/bins\n s_exp = 4.2*85.1*0.25*2*eff_presel\n\n significance_array = []\n significance_error_array = []\n\n for i, (bdt_eff, cut) in enumerate(zip(eff_cut, cut_array)):\n \n selected_data_hndl = dataH.get_subset(f\"model_output>{cut}\")\n counts, bin_edges = np.histogram(selected_data_hndl.get_data_frame()[\"m\"], bins=bins, range=[2.96, 3.04])\n\n bin_centers = (bin_edges[:-1] + bin_edges[1:])/2.\n side_map = np.logical_or(bin_centers < m_min, bin_centers > m_max)\n mass_map = np.logical_not(side_map)\n bin_side = bin_centers[side_map]\n bin_mass = bin_centers[mass_map]\n counts_side = counts[side_map]\n counts_mass = counts[mass_map]\n\n coeff = np.polyfit(bin_side, counts_side, pol_degree)\n data_array = np.arange(2.96, 3.04, bin_width)\n\n coeff_int = [coeff[0], 0]\n B = (np.polyval(coeff_int, m_max) - np.polyval(coeff_int, m_min))/bin_width\n s = s_exp\n\n significance_array.append(s/np.sqrt(s+B))\n significance_error_array.append(significance_error(s, B))\n\n significance = np.asarray(significance_array)\n error_array = np.asarray(significance_error_array)\n\n significance = significance*eff_cut\n error_array = error_array*eff_cut\n\n low_limit = significance - error_array\n up_limit = significance + error_array\n fig = plt.figure()\n plt.plot(eff_cut, significance, 'b', label='Expected Significance')\n plt.fill_between(eff_cut, low_limit, up_limit,\n facecolor='deepskyblue', label=r'$ \\pm 1\\sigma$', alpha=0.3)\n\n if(working_point==None):\n plt.legend(loc=\"lower center\")\n else:\n plt.plot([working_point, working_point],[-1,5.3],linestyle = \"--\", color = \"r\", label = \"Working Point\")\n plt.plot([working_point - syst_range, working_point - syst_range],[-1,5.3],linestyle = \"--\", color = \"g\", label = \"Systematic variation range\")\n plt.plot([working_point + syst_range, working_point + syst_range],[-1,5.3],linestyle = \"--\", color = \"g\")\n\n handles, labels = fig.gca().get_legend_handles_labels()\n order = [0,3,1,2]\n plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order], loc='lower left')\n\n plt.xlabel(\"BDT Efficiency\")\n plt.ylabel(\"Significance x BDT Efficiency\")\n plt.xlim(0.5,0.98)\n plt.ylim(0.3, 5.3)\n return fig\n\n\n\n\ndef plotData(variable, data_hist, model, has_bkg, title, left_limit, right_limit, frame_name):\n fit_results = model.fitTo(data_hist, rf.Extended(), rf.Verbose(\n False), rf.PrintEvalErrors(-1), rf.PrintLevel(-1), rf.Range(left_limit, right_limit), rf.Save())\n frame = variable.frame(left_limit, right_limit)\n frame.SetTitle(title)\n frame.SetName(frame_name)\n data_hist.plotOn(frame, rf.Name('data'), rf.DrawOption('pz'))\n model.plotOn(frame, rf.Components('signal'), rf.Name('signalArea'), rf.FillStyle(\n 3002), rf.FillColor(ROOT.kGreen-2), rf.DrawOption('B'), rf.VLines(), rf.Precision(1.E-6))\n if has_bkg > 0:\n model.plotOn(frame, rf.Components('bkg0'), rf.Name('bkg0Area'), rf.FillStyle(\n 3002), rf.FillColor(ROOT.kRed), rf.DrawOption('B'), rf.VLines(), rf.Precision(1.E-6))\n if has_bkg > 1:\n model.plotOn(frame, rf.Components('bkg1'), rf.Name('bkg1Area'), rf.FillStyle(\n 3002), rf.FillColor(ROOT.kAzure+1), rf.DrawOption('B'), rf.VLines(), rf.Precision(1.E-6))\n if has_bkg > 2:\n model.plotOn(frame, rf.Components('bkg2'), rf.Name('bkg2Area'), rf.FillStyle(\n 3002), rf.FillColor(ROOT.kViolet-2), rf.DrawOption('B'), rf.VLines(), rf.Precision(1.E-6))\n model.plotOn(frame, rf.Components('signal'), rf.LineStyle(\n ROOT.kDashed), rf.LineColor(ROOT.kGreen-2), rf.Name('signal'))\n if has_bkg > 0:\n model.plotOn(frame, rf.Components('bkg0'), rf.LineStyle(\n ROOT.kDashed), rf.LineColor(ROOT.kRed), rf.Name('bkg0'))\n if has_bkg > 1:\n model.plotOn(frame, rf.Components('bkg1'), rf.LineStyle(\n ROOT.kDashed), rf.LineColor(ROOT.kAzure+1), rf.Name('bkg1'))\n if has_bkg > 2:\n model.plotOn(frame, rf.Components('bkg2'), rf.LineStyle(\n ROOT.kDashed), rf.LineColor(ROOT.kViolet-2), rf.Name('bkg2'))\n model.plotOn(frame, rf.DrawOption(\n ''), rf.LineColor(ROOT.kBlue), rf.Name('model'))\n chi2 = frame.chiSquare('model', 'data')\n return frame, chi2, fit_results\n \n\ndef compute_3sigma_coverage(df):\n len_df = len(df)\n sigma_prob = 0.95\n up_val = np.max(df)\n cent_val = np.mean(df)\n var_interval = np.linspace(0, (up_val - cent_val), 1000)\n for var in var_interval:\n len_part = np.sum(np.logical_and(df> cent_val - var, df< cent_val + var))\n frac= len_part/len_df\n if(frac>sigma_prob):\n return cent_val, var\n ", "sub_path": "Analysis/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 18563, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.sqrt", "line_number": 13, "usage_type": "call"}, {"api_name": "ROOT.RooDataSet", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 25, "usage_type": "attribute"}, {"api_name": "ROOT.TTree", "line_number": 27, "usage_type": "call"}, {"api_name": "ROOT.RooDataSet", "line_number": 34, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 54, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 60, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 63, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 65, "usage_type": "call"}, {"api_name": "ROOT.RooGaussian", "line_number": 69, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 73, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 75, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 76, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 77, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 81, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 82, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 85, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 86, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 89, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 90, "usage_type": "call"}, {"api_name": "ROOT.RooExponential", "line_number": 93, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 96, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 97, "usage_type": "call"}, {"api_name": "ROOT.RooAddPdf", "line_number": 102, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 103, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Range", "line_number": 109, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 109, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 117, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 117, "usage_type": "name"}, {"api_name": "ROOT.kBlue", "line_number": 117, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Components", "line_number": 119, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 119, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 120, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 120, "usage_type": "name"}, {"api_name": "ROOT.kDashed", "line_number": 120, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 120, "usage_type": "call"}, {"api_name": "ROOT.kRed", "line_number": 120, "usage_type": "attribute"}, {"api_name": "ROOT.RooArgSet", "line_number": 141, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 142, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 143, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 144, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 147, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 148, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 149, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 153, "usage_type": "call"}, {"api_name": "ROOT.TPaveText", "line_number": 156, "usage_type": "call"}, {"api_name": "ROOT.TCanvas", "line_number": 199, "usage_type": "call"}, {"api_name": "ROOT.RooWorkspace", "line_number": 205, "usage_type": "call"}, {"api_name": "ROOT.RooStats.ModelConfig", "line_number": 206, "usage_type": "call"}, {"api_name": "ROOT.RooStats", "line_number": 206, "usage_type": "attribute"}, {"api_name": "ROOT.RooArgSet", "line_number": 208, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 209, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path", "line_number": 218, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 219, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 234, "usage_type": "call"}, {"api_name": "ROOT.RooDataHist", "line_number": 238, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 238, "usage_type": "call"}, {"api_name": "ROOT.RooHistPdf", "line_number": 239, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 239, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 242, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 243, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 244, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 245, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 249, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 250, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 253, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 254, "usage_type": "call"}, {"api_name": "ROOT.RooPolynomial", "line_number": 257, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 258, "usage_type": "call"}, {"api_name": "ROOT.RooExponential", "line_number": 261, "usage_type": "call"}, {"api_name": "ROOT.RooRealVar", "line_number": 265, "usage_type": "call"}, {"api_name": "ROOT.RooAddPdf", "line_number": 270, "usage_type": "call"}, {"api_name": "ROOT.RooArgList", "line_number": 270, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Range", "line_number": 276, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 276, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 284, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 284, "usage_type": "name"}, {"api_name": "ROOT.kBlue", "line_number": 284, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Components", "line_number": 286, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 286, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 287, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 287, "usage_type": "name"}, {"api_name": "ROOT.kDashed", "line_number": 287, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 287, "usage_type": "call"}, {"api_name": "ROOT.kRed", "line_number": 287, "usage_type": "attribute"}, {"api_name": "ROOT.RooArgSet", "line_number": 306, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 307, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 308, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 309, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 312, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 313, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 314, "usage_type": "call"}, {"api_name": "ROOT.RooArgSet", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 317, "usage_type": "call"}, {"api_name": "ROOT.TPaveText", "line_number": 320, "usage_type": "call"}, {"api_name": "ROOT.TCanvas", "line_number": 355, "usage_type": "call"}, {"api_name": "numpy.hypot", "line_number": 382, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 409, "usage_type": "call"}, {"api_name": "numpy.logical_or", "line_number": 412, "usage_type": "call"}, {"api_name": "numpy.logical_not", "line_number": 413, "usage_type": "call"}, {"api_name": "numpy.polyfit", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 420, "usage_type": "call"}, {"api_name": "numpy.polyval", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 429, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 430, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 437, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 437, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 438, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 438, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.fill_between", "line_number": 439, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 439, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 443, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 443, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 445, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 445, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 446, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 446, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 447, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 447, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 451, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 451, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 453, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 453, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 454, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 454, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 455, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 455, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Extended", "line_number": 463, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 463, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Verbose", "line_number": 463, "usage_type": "call"}, {"api_name": "ROOT.RooFit.PrintEvalErrors", "line_number": 464, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 464, "usage_type": "name"}, {"api_name": "ROOT.RooFit.PrintLevel", "line_number": 464, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Range", "line_number": 464, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Save", "line_number": 464, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Name", "line_number": 468, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 468, "usage_type": "name"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 468, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 469, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 469, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Name", "line_number": 469, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillStyle", "line_number": 469, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillColor", "line_number": 470, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 470, "usage_type": "name"}, {"api_name": "ROOT.kGreen", "line_number": 470, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 470, "usage_type": "call"}, {"api_name": "ROOT.RooFit.VLines", "line_number": 470, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Precision", "line_number": 470, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 472, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 472, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Name", "line_number": 472, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillStyle", "line_number": 472, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillColor", "line_number": 473, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 473, "usage_type": "name"}, {"api_name": "ROOT.kRed", "line_number": 473, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 473, "usage_type": "call"}, {"api_name": "ROOT.RooFit.VLines", "line_number": 473, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Precision", "line_number": 473, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 475, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 475, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Name", "line_number": 475, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillStyle", "line_number": 475, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillColor", "line_number": 476, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 476, "usage_type": "name"}, {"api_name": "ROOT.kAzure", "line_number": 476, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 476, "usage_type": "call"}, {"api_name": "ROOT.RooFit.VLines", "line_number": 476, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Precision", "line_number": 476, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 478, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 478, "usage_type": "name"}, {"api_name": "ROOT.RooFit.Name", "line_number": 478, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillStyle", "line_number": 478, "usage_type": "call"}, {"api_name": "ROOT.RooFit.FillColor", "line_number": 479, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 479, "usage_type": "name"}, {"api_name": "ROOT.kViolet", "line_number": 479, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 479, "usage_type": "call"}, {"api_name": "ROOT.RooFit.VLines", "line_number": 479, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Precision", "line_number": 479, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 480, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 480, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 480, "usage_type": "call"}, {"api_name": "ROOT.kDashed", "line_number": 481, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 481, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 481, "usage_type": "name"}, {"api_name": "ROOT.kGreen", "line_number": 481, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Name", "line_number": 481, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 483, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 483, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 483, "usage_type": "call"}, {"api_name": "ROOT.kDashed", "line_number": 484, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 484, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 484, "usage_type": "name"}, {"api_name": "ROOT.kRed", "line_number": 484, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Name", "line_number": 484, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 486, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 486, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 486, "usage_type": "call"}, {"api_name": "ROOT.kDashed", "line_number": 487, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 487, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 487, "usage_type": "name"}, {"api_name": "ROOT.kAzure", "line_number": 487, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Name", "line_number": 487, "usage_type": "call"}, {"api_name": "ROOT.RooFit.Components", "line_number": 489, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 489, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineStyle", "line_number": 489, "usage_type": "call"}, {"api_name": "ROOT.kDashed", "line_number": 490, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 490, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 490, "usage_type": "name"}, {"api_name": "ROOT.kViolet", "line_number": 490, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Name", "line_number": 490, "usage_type": "call"}, {"api_name": "ROOT.RooFit.DrawOption", "line_number": 491, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 491, "usage_type": "name"}, {"api_name": "ROOT.RooFit.LineColor", "line_number": 492, "usage_type": "call"}, {"api_name": "ROOT.RooFit", "line_number": 492, "usage_type": "name"}, {"api_name": "ROOT.kBlue", "line_number": 492, "usage_type": "attribute"}, {"api_name": "ROOT.RooFit.Name", "line_number": 492, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 500, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 501, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 502, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 504, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 504, "usage_type": "call"}]} +{"seq_id": "38755912", "text": "# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, print_function\n\nimport itertools\nimport os\nimport random\nimport sys\n\nimport click\nimport click.testing\nimport pytest\nimport vistir\n\nimport pythonfinder\n\n\n# def pytest_generate_tests(metafunc):\n# idlist = []\n# argvalues = []\n# for python in PYTHON_VERSIONS:\n# idlist.append(python.path.as_posix())\n# argnames = [\"python\",]\n# argvalues.append(([python,]))\n# metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"function\")\n\n\n# @pytest.fixture(params=PYTHON_VERSIONS)\n# def python(request):\n# return request.params\n\n\n\nSTACKLESS = [\n \"stackless-{0}\".format(v)\n for v in (\n [\n \"dev\",\n \"2.7-dev\",\n \"2.7.2\",\n \"2.7.3\",\n \"2.7.4\",\n \"2.7.5\",\n \"2.7.6\",\n \"2.7.7\",\n \"2.7.8\",\n \"2.7.9\",\n \"2.7.10\",\n \"2.7.11\",\n \"2.7.12\",\n \"2.7.14\",\n \"3.2.2\",\n \"3.2.5\",\n \"3.3.5\",\n \"3.3.7\",\n \"3.4-dev\",\n \"3.4.1\",\n \"3.4.2\",\n \"3.4.7\",\n \"3.5.4\",\n ]\n )\n]\nPYPY = [\n \"pypy3-2.3.1\",\n \"pypy3-2.4.0-src\",\n \"pypy3-2.4.0\",\n \"pypy2-5.6.0\",\n \"pypy2.7-5.10.0\",\n \"pypy2.7-6.0.0\",\n \"pypy-5.3.1\",\n \"pypy3.5-5.10.1\",\n \"pypy3.5-6.0.0-src\",\n \"pypy3.5-6.0.0\",\n]\nPYSTON = [\"pyston-0.5.1\", \"pyston-0.6.0\", \"pyston-0.6.1\"]\nMINICONDA = [\n \"miniconda-2.2.2\",\n \"miniconda-3.0.0\",\n \"miniconda-3.0.4\",\n \"miniconda-3.0.5\",\n \"miniconda-3.3.0\",\n \"miniconda-3.4.2\",\n \"miniconda3-3.18.3\",\n \"miniconda3-3.19.0\",\n \"miniconda3-4.0.5\",\n \"miniconda3-4.1.11\",\n \"miniconda3-4.3.27\",\n \"miniconda3-4.3.30\",\n]\nMICROPYTHON = [\"micropython-1.9.3\", \"micropython-1.9.4\"]\nJYTHON = [\n \"jython-2.5-dev\",\n \"jython-2.5.1\",\n \"jython-2.5.2\",\n \"jython-2.5.3\",\n \"jython-2.5.4-rc1\",\n \"jython-2.7.0\",\n \"jython-2.7.1\",\n]\nANACONDA = [\n \"anaconda2-2.4.1\",\n \"anaconda2-2.5.0\",\n \"anaconda2-4.0.0\",\n \"anaconda2-4.1.0\",\n \"anaconda2-4.1.1\",\n \"anaconda2-4.2.0\",\n \"anaconda2-4.3.0\",\n \"anaconda2-4.3.1\",\n \"anaconda2-4.4.0\",\n \"anaconda3-4.1.1\",\n \"anaconda3-4.2.0\",\n \"anaconda3-4.3.0\",\n \"anaconda3-4.3.1\",\n \"anaconda3-4.4.0\",\n \"anaconda3-5.0.0\",\n \"anaconda3-5.0.1\",\n \"anaconda3-5.1.0\",\n \"anaconda3-5.2.0\",\n \"anaconda3-5.3.0\",\n]\nIRONPYTHON = [\n \"ironpython-dev\",\n \"ironpython-2.7.4\",\n \"ironpython-2.7.5\",\n \"ironpython-2.7.6.3\",\n \"ironpython-2.7.7\",\n]\nACTIVEPYTHON = [\"activepython-2.7.14\", \"activepython-3.5.4\", \"activepython-3.6.0\"]\nPYTHON = [\n \"2.7.11\",\n \"2.7.12\",\n \"2.7.13\",\n \"2.7.14\",\n \"2.7.14rc1\",\n \"2.7.15\",\n \"3.6.6\",\n \"3.6.7\",\n \"3.7.0\",\n \"3.7-dev\",\n \"3.7.1\",\n \"3.8-dev\",\n]\n\n\n@pytest.fixture\ndef setup_pythons(tmpdir):\n runner = click.testing.CliRunner()\n fake_root_path = tmpdir.join(\"root\")\n fake_root_path.mkdir()\n fake_root = fake_root_path.strpath\n with runner.isolated_filesystem(), vistir.contextmanagers.temp_environ():\n home_dir = pythonfinder.utils.normalize_path(os.curdir)\n # This is pip's isolation approach, swipe it for now for time savings\n if sys.platform == \"win32\":\n home_drive, home_path = os.path.splitdrive(home_dir)\n os.environ.update(\n {\n \"USERPROFILE\": home_dir,\n \"HOMEDRIVE\": home_drive,\n \"HOMEPATH\": home_path,\n }\n )\n for env_var, sub_path in (\n (\"APPDATA\", \"AppData/Roaming\"),\n (\"LOCALAPPDATA\", \"AppData/Local\"),\n ):\n path = os.path.join(home_dir, *sub_path.split(\"/\"))\n os.environ[env_var] = path\n vistir.path.mkdir_p(path)\n else:\n os.environ[\"HOME\"] = home_dir\n os.environ[\"XDG_DATA_HOME\"] = os.path.join(home_dir, \".local\", \"share\")\n os.environ[\"XDG_CONFIG_HOME\"] = os.path.join(home_dir, \".config\")\n os.environ[\"XDG_CACHE_HOME\"] = os.path.join(home_dir, \".cache\")\n os.environ[\"XDG_RUNTIME_DIR\"] = os.path.join(home_dir, \".runtime\")\n vistir.path.mkdir_p(os.path.join(home_dir, \".cache\"))\n vistir.path.mkdir_p(os.path.join(home_dir, \".config\"))\n vistir.path.mkdir_p(os.path.join(home_dir, \".local\", \"share\"))\n vistir.path.mkdir_p(os.path.join(fake_root, \"usr\", \"local\", \"share\"))\n vistir.path.mkdir_p(os.path.join(fake_root, \"usr\", \"share\"))\n os.environ[\"XDG_DATA_DIRS\"] = \":\".join(\n [\n os.path.join(fake_root, \"usr\", \"local\", \"share\"),\n os.path.join(fake_root, \"usr\", \"share\"),\n ]\n )\n pyenv_dir = os.path.join(home_dir, \".pyenv\")\n asdf_dir = os.path.join(home_dir, \".asdf\")\n pyenv_shim_dir = os.path.join(pyenv_dir, \"shims\")\n asdf_shim_dir = os.path.join(asdf_dir, \"shims\")\n vistir.path.mkdir_p(pyenv_shim_dir)\n vistir.path.mkdir_p(asdf_shim_dir)\n env_path = os.pathsep.join([pyenv_shim_dir, asdf_shim_dir, os.defpath])\n os.environ[\"PATH\"] = env_path\n all_versions = {}\n for python in itertools.chain(\n STACKLESS,\n PYPY,\n PYSTON,\n MINICONDA,\n MICROPYTHON,\n JYTHON,\n ANACONDA,\n IRONPYTHON,\n ACTIVEPYTHON,\n PYTHON,\n ):\n pyenv_bin = os.path.join(pyenv_dir, \"versions\", python, \"bin\")\n asdf_bin = os.path.join(asdf_dir, \"installs\", \"python\", python, \"bin\")\n vistir.path.mkdir_p(pyenv_bin)\n vistir.path.mkdir_p(asdf_bin)\n python_version = random.choice([\"python3.7m\", \"python3.6m\", \"python2.7\"])\n all_versions[python] = os.path.join(pyenv_bin, python_version)\n for exe in [\"python\", python_version, python]:\n os.link(sys.executable, os.path.join(pyenv_bin, exe))\n os.link(sys.executable, os.path.join(asdf_bin, exe))\n os.symlink(\n os.path.join(pyenv_bin, python), os.path.join(pyenv_shim_dir, python)\n )\n os.symlink(\n os.path.join(asdf_bin, python), os.path.join(asdf_shim_dir, python)\n )\n os.environ[\"PYENV_ROOT\"] = pyenv_dir\n os.environ[\"ASDF_DIR\"] = asdf_dir\n os.environ[\"ASDF_DATA_DIR\"] = asdf_dir\n try:\n yield all_versions\n finally:\n pass\n\n\n@pytest.fixture\ndef special_character_python(tmpdir):\n finder = pythonfinder.Finder(\n global_search=True, system=False, ignore_unsupported=True\n )\n python = finder.find_python_version(\"2\")\n python_name = \"{0}+\".format(python.name)\n python_folder = tmpdir.mkdir(python_name)\n bin_dir = python_folder.mkdir(\"bin\")\n python_path = bin_dir.join(\"python\")\n os.link(python.path.as_posix(), python_path.strpath)\n return python_path\n\n\n@pytest.fixture(autouse=True)\ndef setup_env():\n with vistir.contextmanagers.temp_environ():\n os.environ[\"ANSI_COLORS_DISABLED\"] = str(\"1\")\n", "sub_path": "tests/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 7248, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "click.testing.CliRunner", "line_number": 147, "usage_type": "call"}, {"api_name": "click.testing", "line_number": 147, "usage_type": "attribute"}, {"api_name": "vistir.contextmanagers.temp_environ", "line_number": 151, "usage_type": "call"}, {"api_name": "vistir.contextmanagers", "line_number": 151, "usage_type": "attribute"}, {"api_name": "pythonfinder.utils.normalize_path", "line_number": 152, "usage_type": "call"}, {"api_name": "pythonfinder.utils", "line_number": 152, "usage_type": "attribute"}, {"api_name": "os.curdir", "line_number": 152, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 154, "usage_type": "attribute"}, {"api_name": "os.path.splitdrive", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path", "line_number": 155, "usage_type": "attribute"}, {"api_name": "os.environ.update", "line_number": 156, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 156, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 167, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 168, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 169, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 169, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 171, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 172, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path", "line_number": 172, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 173, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 174, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 175, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 176, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 176, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path", "line_number": 176, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 177, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 178, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 179, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 179, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 179, "usage_type": "call"}, {"api_name": "os.path", "line_number": 179, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 180, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 180, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 181, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 183, "usage_type": "call"}, {"api_name": "os.path", "line_number": 183, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 184, "usage_type": "call"}, {"api_name": "os.path", "line_number": 184, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 188, "usage_type": "call"}, {"api_name": "os.path", "line_number": 188, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 189, "usage_type": "call"}, {"api_name": "os.path", "line_number": 189, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 190, "usage_type": "call"}, {"api_name": "os.path", "line_number": 190, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 191, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 191, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 192, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "os.pathsep.join", "line_number": 193, "usage_type": "call"}, {"api_name": "os.pathsep", "line_number": 193, "usage_type": "attribute"}, {"api_name": "os.defpath", "line_number": 193, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 194, "usage_type": "attribute"}, {"api_name": "itertools.chain", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 209, "usage_type": "call"}, {"api_name": "os.path", "line_number": 209, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 210, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "vistir.path.mkdir_p", "line_number": 211, "usage_type": "call"}, {"api_name": "vistir.path", "line_number": 211, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 212, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path", "line_number": 213, "usage_type": "attribute"}, {"api_name": "os.link", "line_number": 215, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 215, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "os.link", "line_number": 216, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 216, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path", "line_number": 216, "usage_type": "attribute"}, {"api_name": "os.symlink", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path", "line_number": 218, "usage_type": "attribute"}, {"api_name": "os.symlink", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path", "line_number": 221, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 223, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 224, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 225, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 145, "usage_type": "attribute"}, {"api_name": "pythonfinder.Finder", "line_number": 234, "usage_type": "call"}, {"api_name": "os.link", "line_number": 242, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 232, "usage_type": "attribute"}, {"api_name": "vistir.contextmanagers.temp_environ", "line_number": 248, "usage_type": "call"}, {"api_name": "vistir.contextmanagers", "line_number": 248, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 249, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 246, "usage_type": "call"}]} +{"seq_id": "197863077", "text": "import matplotlib\r\nmatplotlib.use('Agg')\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport numpy as np\r\n\r\n\r\ndef boostrap(sample, sample_size, iterations):\r\n\tper = 95\r\n\tdata_mean = []\r\n\tfor _ in range(iterations):\r\n\t\tidxs = np.random.randint(sample_size, size=sample_size)\r\n\t\tdata = [sample[idx] for idx in idxs]\r\n\t\tmean = sum(data)/len(data)\r\n\t\tdata_mean.append(mean)\r\n\ttotal = iterations\r\n\tremove_per = int(((100 - per)/100 * total)/2)\r\n\tdata_mean = data_mean[remove_per:-remove_per]\r\n\r\n\tlower = min(data_mean)\r\n\tupper = max(data_mean)\r\n\tdata_mean = sum(data_mean)/len(data_mean)\r\n\treturn data_mean, lower, upper\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t# df = pd.read_csv('./data/salaries.csv')\r\n\r\n\t# data = df.values.T[1]\r\n\t# boots = []\r\n\t# for i in range(100, 100000, 1000):\r\n\t# \tboot = boostrap(data, data.shape[0], i)\r\n\t# \tboots.append([i, boot[0], \"mean\"])\r\n\t# \tboots.append([i, boot[1], \"lower\"])\r\n\t# \tboots.append([i, boot[2], \"upper\"])\r\n\r\n\t# df_boot = pd.DataFrame(boots, columns=['Boostrap Iterations', 'Mean', \"Value\"])\r\n\t# sns_plot = sns.lmplot(df_boot.columns[0], df_boot.columns[1], data=df_boot, fit_reg=False, hue=\"Value\")\r\n\r\n\t# sns_plot.axes[0, 0].set_ylim(0,)\r\n\t# sns_plot.axes[0, 0].set_xlim(0, 100000)\r\n\r\n\t# sns_plot.savefig(\"./png/bootstrap_confidence.png\", bbox_inches='tight')\r\n\t# sns_plot.savefig(\"./pdf/bootstrap_confidence.pdf\", bbox_inches='tight')\r\n\r\n\r\n\t#print (\"Mean: %f\")%(np.mean(data))\r\n\t#print (\"Var: %f\")%(np.var(data))\r\n\r\n\t# Exercise 2\r\n\tdf = pd.read_csv('./data/vehicles.csv')\r\n\r\n\tcurr_data = df.values.T[0]\r\n\tdf = df.dropna()\r\n\tnew_data = df.values.T[1]\r\n\r\n\tprint (len(curr_data))\r\n\tprint (len(new_data))\r\n\tprint (np.mean(curr_data))\r\n\tprint (np.mean(new_data))\r\n\r\n\tboots = []\r\n\r\n\tfor i in range(100, 100000, 1000):\r\n\t\tcurr_boot = boostrap(curr_data, curr_data.shape[0], i)\r\n\t\tnew_boot = boostrap(new_data, new_data.shape[0], i)\r\n\r\n\t\tboots.append([i, curr_boot[0], \"curr-mean\"])\r\n\t\tboots.append([i, curr_boot[1], \"curr-lower\"])\r\n\t\tboots.append([i, curr_boot[2], \"curr-upper\"])\r\n\t\tboots.append([i, new_boot[0], \"new-mean\"])\r\n\t\tboots.append([i, new_boot[1], \"new-lower\"])\r\n\t\tboots.append([i, new_boot[2], \"new-upper\"])\r\n\r\n\tdf_boot = pd.DataFrame(boots, columns=['Boostrap Iterations', 'Mean', \"Value\"])\r\n\tsns_plot = sns.lmplot(df_boot.columns[0], df_boot.columns[1], data=df_boot, fit_reg=True, hue=\"Value\")\r\n\r\n\tsns_plot.axes[0, 0].set_ylim(0,)\r\n\tsns_plot.axes[0, 0].set_xlim(0, 100000)\r\n\r\n\tsns_plot.savefig(\"./png/bootstrap_vehicles.png\", bbox_inches='tight')\r\n\tsns_plot.savefig(\"./pdf/bootstrap_vehicles.pdf\", bbox_inches='tight')\r\n\t\t", "sub_path": "labs/lab2/bootstrap.py", "file_name": "bootstrap.py", "file_ext": "py", "file_size_in_byte": 2567, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.use", "line_number": 2, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 75, "usage_type": "call"}, {"api_name": "seaborn.lmplot", "line_number": 76, "usage_type": "call"}]} +{"seq_id": "465772802", "text": "############################################################\n# -*- coding: utf-8 -*-\n#\n# # # # # # #\n# ## ## # ## # #\n# # # # # # # # # # #\n# # ## # ## ## ######\n# # # # # # #\n#\n# Python-based Tool for interaction with the 10micron mounts\n# GUI with PyQT5 for python\n# Python v3.7.5\n#\n# Michael Würtenberger\n# (c) 2019\n#\n# Licence APL2.0\n#\n###########################################################\n# standard libraries\nfrom unittest import mock\nimport time\nimport pytest\nimport logging\n\n# external packages\n\n# local import\nfrom mw4.base import loggerMW\n\n\n@pytest.fixture(autouse=True, scope='function')\ndef module_setup_teardown():\n global app\n logger = logging.getLogger(__name__)\n app = loggerMW.CustomLogger(logger, {})\n yield\n del app\n\n\ndef test_setupLogging():\n suc = loggerMW.setupLogging()\n assert suc\n\n\ndef test_setCustomLoggingLevel():\n suc = loggerMW.setCustomLoggingLevel()\n assert suc\n\n\ndef test_process():\n val, kwargs = app.process('test', '10')\n assert val == 'test'\n assert kwargs == '10'\n\n", "sub_path": "mw4/test/test_new/base/test_loggerMW.py", "file_name": "test_loggerMW.py", "file_ext": "py", "file_size_in_byte": 1108, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 35, "usage_type": "call"}, {"api_name": "mw4.base.loggerMW.CustomLogger", "line_number": 36, "usage_type": "call"}, {"api_name": "mw4.base.loggerMW", "line_number": 36, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 32, "usage_type": "call"}, {"api_name": "mw4.base.loggerMW.setupLogging", "line_number": 42, "usage_type": "call"}, {"api_name": "mw4.base.loggerMW", "line_number": 42, "usage_type": "name"}, {"api_name": "mw4.base.loggerMW.setCustomLoggingLevel", "line_number": 47, "usage_type": "call"}, {"api_name": "mw4.base.loggerMW", "line_number": 47, "usage_type": "name"}]} +{"seq_id": "482987412", "text": "import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nurl = [\n 'https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive'\n]\n# Get the downloaded credentials from oAuth\ncreds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', url)\n\n# Authorize request\ngc = gspread.authorize(creds)\n\n# Open a worksheet from spreadsheet with one shot\nwks = gc.open(\"Test\").sheet1\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 441, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name", "line_number": 9, "usage_type": "call"}, {"api_name": "oauth2client.service_account.ServiceAccountCredentials", "line_number": 9, "usage_type": "name"}, {"api_name": "gspread.authorize", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "313343690", "text": "# edit-mode: -*- python -*-\nimport paddle.v2 as paddle\n\n\ndef conv_bn_layer(input,\n filter_size,\n num_filters,\n stride,\n padding,\n channels=None,\n num_groups=1,\n active_type=paddle.activation.Relu(),\n layer_type=None):\n \"\"\"\n A wrapper for conv layer with batch normalization layers.\n Note:\n conv layer has no activation.\n \"\"\"\n tmp = paddle.layer.img_conv(\n input=input,\n filter_size=filter_size,\n num_channels=channels,\n num_filters=num_filters,\n stride=stride,\n padding=padding,\n groups=num_groups,\n # !!! the act in the network with batch norm\n # is paddle.activation.Linear()\n act=active_type,\n # !!! the bias_attr in origin network is False\n bias_attr=True,\n layer_type=layer_type)\n\n # !!! we have deleted the batch_norm layer here.\n return tmp\n\n\ndef depthwise_separable(input, num_filters1, num_filters2, num_groups, stride,\n scale):\n \"\"\"\n \"\"\"\n tmp = conv_bn_layer(\n input=input,\n filter_size=3,\n num_filters=int(num_filters1 * scale),\n stride=stride,\n padding=1,\n num_groups=int(num_groups * scale),\n layer_type='exconv')\n\n tmp = conv_bn_layer(\n input=tmp,\n filter_size=1,\n num_filters=int(num_filters2 * scale),\n stride=1,\n padding=0)\n return tmp\n\n\ndef mobile_net(img_size, class_num, scale=1.0):\n\n img = paddle.layer.data(\n name=\"image\", type=paddle.data_type.dense_vector(img_size))\n\n # conv1: 112x112\n tmp = conv_bn_layer(\n img,\n filter_size=3,\n channels=3,\n num_filters=int(32 * scale),\n stride=2,\n padding=1)\n\n # 56x56\n tmp = depthwise_separable(\n tmp,\n num_filters1=32,\n num_filters2=64,\n num_groups=32,\n stride=1,\n scale=scale)\n tmp = depthwise_separable(\n tmp,\n num_filters1=64,\n num_filters2=128,\n num_groups=64,\n stride=2,\n scale=scale)\n # 28x28\n tmp = depthwise_separable(\n tmp,\n num_filters1=128,\n num_filters2=128,\n num_groups=128,\n stride=1,\n scale=scale)\n tmp = depthwise_separable(\n tmp,\n num_filters1=128,\n num_filters2=256,\n num_groups=128,\n stride=2,\n scale=scale)\n # 14x14\n tmp = depthwise_separable(\n tmp,\n num_filters1=256,\n num_filters2=256,\n num_groups=256,\n stride=1,\n scale=scale)\n tmp = depthwise_separable(\n tmp,\n num_filters1=256,\n num_filters2=512,\n num_groups=256,\n stride=2,\n scale=scale)\n # 14x14\n for i in range(5):\n tmp = depthwise_separable(\n tmp,\n num_filters1=512,\n num_filters2=512,\n num_groups=512,\n stride=1,\n scale=scale)\n # 7x7\n tmp = depthwise_separable(\n tmp,\n num_filters1=512,\n num_filters2=1024,\n num_groups=512,\n stride=2,\n scale=scale)\n tmp = depthwise_separable(\n tmp,\n num_filters1=1024,\n num_filters2=1024,\n num_groups=1024,\n stride=1,\n scale=scale)\n\n tmp = paddle.layer.img_pool(\n input=tmp, pool_size=7, stride=1, pool_type=paddle.pooling.Avg())\n out = paddle.layer.fc(\n input=tmp, size=class_num, act=paddle.activation.Softmax())\n\n return out\n\n\nif __name__ == '__main__':\n img_size = 3 * 224 * 224\n data_dim = 102\n out = mobile_net(img_size, data_dim, 1.0)\n", "sub_path": "deployment/model/merge_batch_normalization/demo/mobilenet_without_bn.py", "file_name": "mobilenet_without_bn.py", "file_ext": "py", "file_size_in_byte": 3733, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "paddle.v2.activation.Relu", "line_number": 12, "usage_type": "call"}, {"api_name": "paddle.v2.activation", "line_number": 12, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 12, "usage_type": "name"}, {"api_name": "paddle.v2.layer.img_conv", "line_number": 19, "usage_type": "call"}, {"api_name": "paddle.v2.layer", "line_number": 19, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 19, "usage_type": "name"}, {"api_name": "paddle.v2.layer.data", "line_number": 62, "usage_type": "call"}, {"api_name": "paddle.v2.layer", "line_number": 62, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 62, "usage_type": "name"}, {"api_name": "paddle.v2.data_type.dense_vector", "line_number": 63, "usage_type": "call"}, {"api_name": "paddle.v2.data_type", "line_number": 63, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 63, "usage_type": "name"}, {"api_name": "paddle.v2.layer.img_pool", "line_number": 144, "usage_type": "call"}, {"api_name": "paddle.v2.layer", "line_number": 144, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 144, "usage_type": "name"}, {"api_name": "paddle.v2.pooling.Avg", "line_number": 145, "usage_type": "call"}, {"api_name": "paddle.v2.pooling", "line_number": 145, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 145, "usage_type": "name"}, {"api_name": "paddle.v2.layer.fc", "line_number": 146, "usage_type": "call"}, {"api_name": "paddle.v2.layer", "line_number": 146, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 146, "usage_type": "name"}, {"api_name": "paddle.v2.activation.Softmax", "line_number": 147, "usage_type": "call"}, {"api_name": "paddle.v2.activation", "line_number": 147, "usage_type": "attribute"}, {"api_name": "paddle.v2", "line_number": 147, "usage_type": "name"}]} +{"seq_id": "16983443", "text": "#!/usr/bin/python3\nimport argparse\nimport os\nimport tqdm\n\nimport torch\nimport torch.optim as optim\nimport numpy as np\n\nfrom networks.faceid.sphereface import sphere20a\n\nimport torchvision\nfrom torchvision import transforms\n\nfrom loss import AngleLoss\n\nfrom utils import printoneline, dt, freeze_model, unfreeze_model\nfrom common import CKPT_DIR, LOGS_DIR\n\ndef save_model(model, ckpt_path):\n torch.save(model.state_dict(), ckpt_path)\n\nstop_flag = False\ndef handler(signum, frame):\n print(\"Shutting down at \" + dt() + \" ...\")\n global stop_flag\n stop_flag = True\n\nimport signal\nsignal.signal(signal.SIGTERM, handler)\nsignal.signal(signal.SIGINT, handler)\n\n\ndef global_forward(sample, batch_idx, optimizer, total, correct, total_loss, train_loss_arr):\n optimizer.zero_grad()\n imgs, labels = sample\n imgs, labels = imgs.cuda(non_blocking=True), labels.cuda(non_blocking=True)\n\n imgs = (imgs*255 - 127.5)/128\n # compute output\n optimizer.zero_grad()\n outputs = faceid(imgs)\n loss = faceid_criterion(outputs, labels)\n loss.backward()\n \n# torch.nn.utils.clip_grad.clip_grad_norm_(faceid.parameters(), 10)\n# torch.nn.utils.clip_grad.clip_grad_norm_(denoiser.parameters(), 10)\n \n optimizer.step()\n\n cur_loss = loss.data.cpu().numpy().item()\n train_loss_arr.append(cur_loss)\n total_loss += cur_loss\n\n outputs = outputs[0] # 0=cos_theta 1=phi_theta\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += predicted.eq(labels.data).sum().cpu().item()\n\n grads = []\n for idx, p in enumerate(list(filter(lambda p: p.grad is not None, faceid.parameters()))):\n grads.append([idx, p.grad.data.norm(2).item()])\n cur_grad_norm = np.sum(grads)\n\n printoneline(dt(),'Te=%d TLoss=%.4f batch=%d | acc: %.4f%% faceid: %.4f grad: %.4f' % \n (epoch, total_loss/(batch_idx+1), batch_idx, 100. * correct/total, cur_loss, \n cur_grad_norm))\n\n return loss, total, correct, total_loss\n \ndef train_epoch(dataloader, optimizer, total, correct, total_loss, train_loss_arr):\n for batch_idx, sample in enumerate(dataloader):\n if stop_flag:\n break\n loss, total, correct, total_loss = global_forward(sample, batch_idx, optimizer, total, correct, total_loss, train_loss_arr)\n\n return total, correct, total_loss\n\nimport torch.nn as nn\nimport math\nimport torch\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\nModule = nn.Module\nimport collections\nfrom itertools import repeat\n\ndef _ntuple(n):\n def parse(x):\n if isinstance(x, collections.Iterable):\n return x\n return tuple(repeat(x, n))\n return parse\n\n_single = _ntuple(1)\n_pair = _ntuple(2)\n_triple = _ntuple(3)\n_quadruple = _ntuple(4)\n\nunfold = F.unfold\n\ndef conv2d_local(input, weight, bias=None, padding=0, stride=1, dilation=1):\n if input.dim() != 4:\n raise NotImplementedError(\"Input Error: Only 4D input Tensors supported (got {}D)\".format(input.dim()))\n if weight.dim() != 6:\n # outH x outW x outC x inC x kH x kW\n raise NotImplementedError(\"Input Error: Only 6D weight Tensors supported (got {}D)\".format(weight.dim()))\n \n outH, outW, outC, inC, kH, kW = weight.size()\n kernel_size = (kH, kW)\n \n # N x [inC * kH * kW] x [outH * outW]\n cols = unfold(input, kernel_size, dilation=dilation, padding=padding, stride=stride)\n cols = cols.view(cols.size(0), cols.size(1), cols.size(2), 1).permute(0, 2, 3, 1)\n \n out = torch.matmul(cols, weight.view(outH * outW, outC, inC * kH * kW).permute(0, 2, 1))\n out = out.view(cols.size(0), outH, outW, outC).permute(0, 3, 1, 2)\n \n if bias is not None:\n out = out + bias.expand_as(out)\n return out\n\n\nclass Conv2dLocal(Module):\n \n def __init__(self, in_height, in_width, in_channels, out_channels,\n kernel_size, stride=1, padding=0, bias=True, dilation=1):\n super(Conv2dLocal, self).__init__()\n \n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = _pair(kernel_size)\n self.stride = _pair(stride)\n self.padding = _pair(padding)\n self.dilation = _pair(dilation)\n \n self.in_height = in_height\n self.in_width = in_width\n self.out_height = int(math.floor(\n (in_height + 2 * self.padding[0] - self.dilation[0] * (self.kernel_size[0] - 1) - 1) / self.stride[0] + 1))\n self.out_width = int(math.floor(\n (in_width + 2 * self.padding[1] - self.dilation[1] * (self.kernel_size[1] - 1) - 1) / self.stride[1] + 1))\n self.weight = Parameter(torch.Tensor(\n self.out_height, self.out_width,\n out_channels, in_channels, *self.kernel_size))\n if bias:\n self.bias = Parameter(torch.Tensor(\n out_channels, self.out_height, self.out_width))\n else:\n self.register_parameter('bias', None)\n \n self.reset_parameters()\n \n def reset_parameters(self):\n n = self.in_channels\n for k in self.kernel_size:\n n *= k\n stdv = 1. / math.sqrt(n)\n self.weight.data.uniform_(-stdv, stdv)\n if self.bias is not None:\n self.bias.data.uniform_(-stdv, stdv)\n \n def __repr__(self):\n s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}'\n ', stride={stride}')\n if self.padding != (0,) * len(self.padding):\n s += ', padding={padding}'\n if self.dilation != (1,) * len(self.dilation):\n s += ', dilation={dilation}'\n if self.bias is None:\n s += ', bias=False'\n s += ')'\n return s.format(name=self.__class__.__name__, **self.__dict__)\n \n def forward(self, input):\n return conv2d_local(\n input, self.weight, self.bias, stride=self.stride,\n padding=self.padding, dilation=self.dilation)\n\n \nclass FeatureDenoiser(nn.Module):\n def __init__(self, n_features=512, n_channels=10):\n super(FeatureDenoiser, self).__init__()\n self.conv1 = Conv2dLocal(n_features, 1, 1, n_channels, 1, 1, 0)\n self.prelu_1 = nn.PReLU(n_channels)\n self.conv2 = Conv2dLocal(n_features, 1, n_channels, n_channels, 1, 1, 0)\n self.prelu_2 = nn.PReLU(n_channels)\n self.conv3 = Conv2dLocal(n_features, 1, n_channels, 1, 1, 1, 0)\n self.n_channels = n_channels\n \n def forward(self, x):\n x = x.view(x.size()[0], 1, x.size()[1], 1)\n x = x + self.conv3(self.prelu_2(self.conv2(self.prelu_1(self.conv1(x)))))\n x = x.view(x.size()[0],-1)\n return x\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Training script')\n parser.add_argument('-r', '--resume', default=None, type=str,\n help='path to latest checkpoint (default: None)')\n parser.add_argument('-n', '--name', type=str, required=True,\n help='name of the experiment')\n parser.add_argument('-d', '--device', type=str, required=True,\n help='indices of GPUs to enable (default: all)')\n parser.add_argument('-e', '--epochs', type=int, default=100,\n help='number of epochs (default: 100)')\n parser.add_argument('-b', '--batch_size', type=int, default=32,\n help='batch_size (default: 32)')\n args = parser.parse_args()\n \n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \n os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.device\n \n train_data_dir = \"/tmp/1st_udnet7pa_input/\"\n# train_data_dir = \"/tmp/CASIA-WebFace-sphereface/\"\n transform = transforms.Compose([\n# transforms.RandomCrop((112, 96)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()\n ])\n dataset_train = torchvision.datasets.ImageFolder(train_data_dir, transform=transform)\n dataloader_train = torch.utils.data.dataloader.DataLoader(dataset_train, shuffle=True, batch_size=args.batch_size, pin_memory=True, num_workers=14)\n \n fdn = FeatureDenoiser(n_channels = 3)\n faceid = sphere20a(dn_block=fdn)\n# faceid_ckpt_path = \"/home/safin/FaceReID/ckpt/01.01_sphere20a_20.pth\" #trained for high noise\n# faceid_ckpt_path = \"/home/safin/FaceReID/ckpt/faceid_joint_3stages_20.01_8\"\n# faceid_ckpt_path = \"/home/safin/sphereface_pytorch/sphere20a_19.pth\"\n# faceid_ckpt_path = \"ckpt/1stage_udnet_fixed_sphereface_27.01/faceid/faceid_1stage_udnet_fixed_sphereface_27.01_30\"\n\n# faceid_ckpt_path = \"/home/safin/sphereface_pytorch/sphere20a_19.pth\"\n# faceid_ckpt_path = \"/home/safin/FaceReID/ckpt/joint_07.02_fixed/faceid/weights_74\"\n# faceid_ckpt_path = \"ckpt/1stage_udnet_sphereface_08.02_finetune/faceid/weights_\"+str(n_ckpt)\n# faceid_ckpt_path = \"ckpt/joint_07.02_finetune_08.02/faceid/weights_\"+str(n_ckpt)\n# faceid_ckpt_path = \"/home/safin/sphereface_pytorch/sphere20a_19.pth\"\n# faceid_ckpt_path = \"/home/safin/FaceReID/ckpt/sphereface_13.02/faceid/weights_10\"\n faceid_ckpt_path = \"/home/safin/ckpt/sphereface_clean/sphere20a_19.pth\"\n faceid.load_state_dict(torch.load(faceid_ckpt_path), strict=False)\n faceid = faceid.cuda()\n# freeze_model(faceid)\n# unfreeze_model(faceid.dn_block)\n# unfreeze_model(faceid.fc6)\n# faceid.dn_block.train()\n \n \n\n# optimizer = optim.Adam(itertools.chain(denoiser.parameters(), faceid.parameters()), lr=0.0001)\n# optimizer = optim.Adam(faceid.parameters(), lr=0.001)\n\n# criterion = nn.MSELoss().cuda()\n# denoise_criterion = nn.L1Loss().cuda()\n faceid_criterion = AngleLoss().cuda()\n \n cur_logs_path = os.path.join(LOGS_DIR, args.name)\n os.makedirs(cur_logs_path, exist_ok=True)\n \n cur_ckpt_path = os.path.join(CKPT_DIR, args.name)\n os.makedirs(cur_ckpt_path, exist_ok=True)\n faceid_ckpt_path = os.path.join(cur_ckpt_path, \"faceid\")\n os.makedirs(faceid_ckpt_path, exist_ok=True)\n \n total_train_loss_arr = []\n total_train_acc_arr = []\n\n lr_milstones = [5, 10, 20, 40]\n# scheduler = MultiStepLR(optimizer, lr_milstones, gamma=0.9)\n lr = 0.01\n for epoch in range(args.epochs):\n total = 0\n correct = 0\n train_loss_arr = []\n total_loss = 0\n# faceid_w = 1\n# denoise_w = 0\n# if epoch >= 1:\n# faceid_w = 1\n# else:\n# faceid_w = 0\n# scheduler.step()\n if epoch in [0,10,15,18,30]:\n if epoch!=0: lr *= 0.5\n optimizer = optim.SGD(faceid.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)\n total, correct, total_loss = train_epoch(dataloader_train, optimizer, total, correct, total_loss, train_loss_arr)\n \n save_model(faceid, os.path.join(faceid_ckpt_path, \"weights_%d\" % epoch))\n# torch.save(denoiser.state_dict(), os.path.join(denoiser_ckpt_path, \"weights_%d\" % epoch))\n \n total_train_loss_arr.append(np.mean(train_loss_arr))\n np.save(os.path.join(cur_logs_path,\"train_loss_\" + args.name), np.asarray(total_train_loss_arr))\n \n total_train_acc_arr.append(100. * correct/total)\n np.save(os.path.join(cur_logs_path,\"train_faceid_acc_\" + args.name), np.asarray(total_train_acc_arr))\n\n grads = []\n for idx, p in enumerate(list(filter(lambda p: p.grad is not None, faceid.parameters()))):\n grads.append([idx, p.grad.data.norm(2).item()])\n np.save(os.path.join(cur_logs_path,\"train_grads_\" + args.name + \"_%d\" % epoch), np.asarray(grads))\n print(\"\\n\")\n \n# total = 0\n# correct = 0\n# train_loss_arr = []\n# total_loss = 0\n# train_epoch(dataloader_val, None, total, correct, total_loss, train_loss_arr)\n# print(\"\\n\")\n# torch.save(denoiser.state_dict(), ckpt_path + \"denoiser_\" + args.name + \"_%d\" % epoch)\n# np.save(\"train_loss_\" + args.name + \"_%d\" % epoch, np.asarray(train_loss_arr))\n\n \n if stop_flag:\n break\n #for l1, l2 in zip(parameters_start,list(model.parameters())):\n # print(np.array_equal(l1.data.numpy(), l2.data.numpy()))\n print(\"Done.\")", "sub_path": "train_sphereface_on_noised.py", "file_name": "train_sphereface_on_noised.py", "file_ext": "py", "file_size_in_byte": 12238, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.save", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.dt", "line_number": 25, "usage_type": "call"}, {"api_name": "signal.signal", "line_number": 30, "usage_type": "call"}, {"api_name": "signal.SIGTERM", "line_number": 30, "usage_type": "attribute"}, {"api_name": "signal.signal", "line_number": 31, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 31, "usage_type": "attribute"}, {"api_name": "loss.backward", "line_number": 44, "usage_type": "call"}, {"api_name": "loss.data.cpu", "line_number": 51, "usage_type": "call"}, {"api_name": "loss.data", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.max", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 63, "usage_type": "call"}, {"api_name": "utils.printoneline", "line_number": 65, "usage_type": "call"}, {"api_name": "utils.dt", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 84, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "collections.Iterable", "line_number": 90, "usage_type": "attribute"}, {"api_name": "itertools.repeat", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn.functional.unfold", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.nn.functional", "line_number": 100, "usage_type": "name"}, {"api_name": "torch.matmul", "line_number": 116, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 139, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.nn.parameter.Parameter", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.nn.parameter.Parameter", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 147, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 181, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 181, "usage_type": "name"}, {"api_name": "torch.nn.PReLU", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 185, "usage_type": "name"}, {"api_name": "torch.nn.PReLU", "line_number": 187, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 187, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 199, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 212, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 213, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 217, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 217, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 219, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 219, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 220, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 220, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 222, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 222, "usage_type": "attribute"}, {"api_name": "torch.utils.data.dataloader.DataLoader", "line_number": 223, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 223, "usage_type": "attribute"}, {"api_name": "networks.faceid.sphereface.sphere20a", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 239, "usage_type": "call"}, {"api_name": "loss.AngleLoss", "line_number": 253, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 255, "usage_type": "call"}, {"api_name": "common.LOGS_DIR", "line_number": 255, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 255, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 256, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 258, "usage_type": "call"}, {"api_name": "common.CKPT_DIR", "line_number": 258, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 258, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 260, "usage_type": "call"}, {"api_name": "os.path", "line_number": 260, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 261, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 283, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 286, "usage_type": "call"}, {"api_name": "os.path", "line_number": 286, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 290, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 290, "usage_type": "call"}, {"api_name": "os.path", "line_number": 290, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 290, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 293, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 293, "usage_type": "call"}, {"api_name": "os.path", "line_number": 293, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 298, "usage_type": "call"}]} +{"seq_id": "598693003", "text": "import pandas as pd\nimport numpy as np\nimport sys\nimport arff\nimport weka.core.jvm as jvm #Bayes net and other weka classifiers and functions\njvm.start(system_cp=True, packages=True, max_heap_size=\"512m\") #Remember to initialize this CLASSPATH env var\n\nsys.path.append('code/') #Folder with the scripts, working directory the main directory\nfrom VIC_fun import VIC #Our created VIC function\n\n#EXAMPLE: Creation of the clusters to validate\ndataset=pd.read_csv('data/FULL_DATABASE.csv').drop(columns='Unnamed: 0')\ndataset.insert(column='cluster_id', value=0, loc=len(dataset.columns))\n\n##Running the validity index in 50 different partitions\nnp.random.seed(2500)\nkgroups=10 #Number of folds to do k-fold cross-validation\nn_jobs=4 #Multithread parameter\nr=np.random.choice(range(kgroups+1,199-kgroups),50, replace=False) #Generates an array of valid positions to divide the top 200 universities in to groups\n\n#Calling my classifiers, and setting their parameters\nclassifiers_parameters={\n 'naive_bayes':{},\n 'RandomForest':{\n 'n_estimators':100\n },\n 'svm':{\n 'kernel':'linear',\n 'C':1,\n 'degree':2,\n 'gamma':'auto'\n },\n 'BayesianNet':{},\n 'LDA':{}\n}\nclassifiers=['svm','naive_bayes','LDA','RandomForest', 'BayesianNet']\nresults_VIC=[] #Empyty list to store the results\natt_arff=[(i, 'REAL') for i in dataset.columns.values[1:-1]]\natt_arff.append(('cluster_id',['-1','1']))\nfor cut in r:\n dataset.loc[:,'cluster_id'].iloc[:(cut+1)]=-1\n dataset.loc[:,'cluster_id'].iloc[(cut+1):]=1\n X=dataset.iloc[:,1:-1].values\n y=dataset.iloc[:,-1].values\n missing_indexes= [(i[0],i[1])for i in np.argwhere(np.isnan(X))]\n for mis in missing_indexes:\n X[mis]=0 #Los unicos missing son numeros de documentos, por tanto quiere decir que no hay documentos registrados\n\n np.random.seed(1000)\n train_indexes=np.random.choice(range(200),200, replace=False)\n X_train=X[train_indexes]\n y_train=y[train_indexes]\n if any([i=='BayesianNet' for i in classifiers]):\n to_arffdump={'relation':'all_data', 'attributes':att_arff,'data':list(np.column_stack((X,np.array([str(j) for j in y]))))}\n #to_arffdump={'relation':'all_data', 'attributes':att_arff,'data':list(X)}\n with open('data/datatobayes.arff','w') as farff:\n arff.dump(to_arffdump,farff) \n temp=[item for item in VIC(X_train,y_train,classifiers,kgroups,metric='roc_auc',n_jobs=n_jobs,**classifiers_parameters)]\n temp.insert(0,cut)\n results_VIC.append(temp)\njvm.stop()", "sub_path": "code/example.py", "file_name": "example.py", "file_ext": "py", "file_size_in_byte": 2530, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "weka.core.jvm.start", "line_number": 6, "usage_type": "call"}, {"api_name": "weka.core.jvm", "line_number": 6, "usage_type": "name"}, {"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.argwhere", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.column_stack", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "arff.dump", "line_number": 57, "usage_type": "call"}, {"api_name": "VIC_fun.VIC", "line_number": 58, "usage_type": "call"}, {"api_name": "weka.core.jvm.stop", "line_number": 61, "usage_type": "call"}, {"api_name": "weka.core.jvm", "line_number": 61, "usage_type": "name"}]} +{"seq_id": "16184456", "text": "# encoding: utf-8\n\"\"\"\nSimulation script for the Brunel (2000) network model as described in NineML.\n\nThis script imports a Python lib9ml network description from\n\"brunel_network_alpha.py\", exports it as XML, and then\nruns a simulation using the pyNN.nineml module with the NEURON\nbackend.\n\n\"\"\"\n\nfrom __future__ import division\nimport sys\nimport numpy as np\nfrom neo import AnalogSignal\nfrom quantities import ms, dimensionless\nimport pyNN.neuron as sim\nfrom pyNN.nineml.read import Network\nfrom pyNN.utility import SimulationProgressBar\nfrom pyNN.utility.plotting import Figure, Panel\nfrom brunel_network_alpha import build_model\n\ncase = sys.argv[1]\nplot_figure = False\n\nparameters = {\n \"SR\": {\"g\": 3, \"eta\": 2},\n \"SR2\": {\"g\": 2, \"eta\": 2},\n \"SR3\": {\"g\": 0, \"eta\": 2},\n \"SIfast\": {\"g\": 6, \"eta\": 4},\n \"AI\": {\"g\": 5, \"eta\": 2},\n \"SIslow\": {\"g\": 4.5, \"eta\": 0.9},\n \"SIslow\": {\"g\": 4.5, \"eta\": 0.95}\n}\n\nplot_limits = (900, 1200)\n\n\nmodel = build_model(**parameters[case])\n\nxml_file = \"brunel_network_alpha_%s.xml\" % case\nmodel.write(xml_file)\n\nsim.setup()\n\nprint(\"Building network\")\nnet = Network(sim, xml_file)\n\nif plot_figure:\n stim = net.populations[\"Ext\"]\n stim[:100].record('spikes')\n exc = net.populations[\"Exc\"]\n exc.sample(50).record(\"spikes\")\n exc.sample(3).record([\"nrn_V\", \"syn_A\"])\n inh = net.populations[\"Inh\"]\n inh.sample(50).record(\"spikes\")\n inh.sample(3).record([\"nrn_V\", \"syn_A\"])\nelse:\n all = net.assemblies[\"All neurons\"]\n #all.sample(50).record(\"spikes\")\n all.record(\"spikes\")\n\nprint(\"Running simulation\")\nt_stop = plot_limits[1]\npb = SimulationProgressBar(t_stop/80, t_stop)\n\nsim.run(t_stop, callbacks=[pb])\n\nprint(\"Handling data\")\nif plot_figure:\n stim_data = stim.get_data().segments[0]\n exc_data = exc.get_data().segments[0]\n inh_data = inh.get_data().segments[0]\nelse:\n all.write_data(\"brunel_network_alpha_%s.h5\" % case)\n\nsim.end()\n\n\ndef instantaneous_firing_rate(segment, begin, end):\n \"\"\"Computed in bins of 0.1 ms \"\"\"\n bins = np.arange(begin, end, 0.1)\n hist, _ = np.histogram(segment.spiketrains[0].time_slice(begin, end), bins)\n for st in segment.spiketrains[1:]:\n h, _ = np.histogram(st.time_slice(begin, end), bins)\n hist += h\n return AnalogSignal(hist, sampling_period=0.1*ms, units=dimensionless,\n channel_index=0, name=\"Spike count\")\n\nif plot_figure:\n Figure(\n Panel(stim_data.spiketrains, markersize=0.2, xlim=plot_limits),\n Panel(exc_data.analogsignalarrays[0], yticks=True, xlim=plot_limits),\n Panel(exc_data.analogsignalarrays[1], yticks=True, xlim=plot_limits),\n Panel(exc_data.spiketrains[:100], markersize=0.5, xlim=plot_limits),\n Panel(instantaneous_firing_rate(exc_data, *plot_limits), yticks=True),\n Panel(inh_data.analogsignalarrays[0], yticks=True, xlim=plot_limits),\n Panel(inh_data.analogsignalarrays[1], yticks=True, xlim=plot_limits),\n Panel(inh_data.spiketrains[:100], markersize=0.5, xlim=plot_limits),\n Panel(instantaneous_firing_rate(inh_data, *plot_limits), xticks=True, xlabel=\"Time (ms)\", yticks=True),\n ).save(\"brunel_network_alpha.png\")\n", "sub_path": "lib9ml/python/nineml/examples/Brunel2000/run_brunel_network_alpha.py", "file_name": "run_brunel_network_alpha.py", "file_ext": "py", "file_size_in_byte": 3182, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 23, "usage_type": "attribute"}, {"api_name": "brunel_network_alpha.build_model", "line_number": 39, "usage_type": "call"}, {"api_name": "pyNN.neuron.setup", "line_number": 44, "usage_type": "call"}, {"api_name": "pyNN.neuron", "line_number": 44, "usage_type": "name"}, {"api_name": "pyNN.nineml.read.Network", "line_number": 47, "usage_type": "call"}, {"api_name": "pyNN.neuron", "line_number": 47, "usage_type": "argument"}, {"api_name": "pyNN.utility.SimulationProgressBar", "line_number": 65, "usage_type": "call"}, {"api_name": "pyNN.neuron.run", "line_number": 67, "usage_type": "call"}, {"api_name": "pyNN.neuron", "line_number": 67, "usage_type": "name"}, {"api_name": "pyNN.neuron.end", "line_number": 77, "usage_type": "call"}, {"api_name": "pyNN.neuron", "line_number": 77, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 85, "usage_type": "call"}, {"api_name": "neo.AnalogSignal", "line_number": 87, "usage_type": "call"}, {"api_name": "quantities.ms", "line_number": 87, "usage_type": "name"}, {"api_name": "quantities.dimensionless", "line_number": 87, "usage_type": "name"}, {"api_name": "pyNN.utility.plotting.Figure", "line_number": 91, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 92, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 93, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 94, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 95, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 96, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 97, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 98, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 99, "usage_type": "call"}, {"api_name": "pyNN.utility.plotting.Panel", "line_number": 100, "usage_type": "call"}]} +{"seq_id": "253450187", "text": "from dataclasses import dataclass\nfrom dataclasses import field\n\nimport numpy as np\nfrom .complex_watson import ComplexWatsonParameters, ComplexWatson\n\nfrom dc_integration.utils import (\n get_power_spectral_density_matrix,\n get_pca,\n)\nfrom dc_integration.distribution.utils import (\n _unit_norm,\n _Parameter,\n)\n\n\n@dataclass\nclass ComplexWatsonMixtureModelParameters(_Parameter):\n complex_watson: ComplexWatsonParameters \\\n = field(default_factory=ComplexWatsonParameters)\n mixture_weights: np.array = None\n affiliation: np.array = None\n\n eps: float = 1e-10\n\n def _predict(self, Y, source_activity_mask=None):\n \"\"\"Predict class affiliation posteriors from given model.\n\n Args:\n Y: Normalized mix with shape (..., T, D).\n Returns: Affiliations with shape (..., K, T).\n \"\"\"\n affiliation = self.mixture_weights[..., None] * ComplexWatson.pdf(\n Y[..., None, :, :],\n np.ascontiguousarray(self.complex_watson.mode[..., None, :]),\n self.complex_watson.concentration[..., None]\n )\n if source_activity_mask is not None:\n affiliation *= source_activity_mask\n affiliation /= np.maximum(\n np.sum(affiliation, axis=-2, keepdims=True),\n self.eps,\n )\n affiliation = np.maximum(affiliation, self.eps)\n return np.ascontiguousarray(affiliation)\n\n def predict(self, Y):\n\n *independent, T, D = Y.shape\n assert D < 20, (D, 'Sure?')\n\n Y = _unit_norm(\n Y,\n axis=-1,\n eps=1e-10,\n eps_style='where'\n )\n\n return self._predict(Y)\n\n\nclass ComplexWatsonMixtureModel:\n \"\"\"Collects all functions related to the cWMM.\"\"\"\n # unit_norm = staticmethod(_unit_norm)\n # phase_norm = staticmethod(_phase_norm)\n # frequency_norm = staticmethod(_frequency_norm)\n\n Parameters = staticmethod(ComplexWatsonMixtureModelParameters)\n\n def __init__(self, eps=1e-10, pbar=False):\n \"\"\"\n \"\"\"\n self.pbar = pbar\n self.eps = eps\n\n def fit(\n self,\n Y,\n initialization,\n source_activity_mask=None,\n iterations=100,\n max_concentration=100,\n ) -> ComplexWatsonMixtureModelParameters:\n \"\"\" EM for CWMMs with any number of independent dimensions.\n\n Does not support sequence lengths.\n Can later be extended to accept more initializations, but for now\n only accepts affiliations (masks) as initialization.\n\n Args:\n Y_normalized: Mix with shape (..., T, D).\n initialization: Shape (..., K, T)\n iterations: Most of the time 10 iterations are acceptable.\n max_concentration: For numerical stability reasons.\n \"\"\"\n\n *independent, T, D = Y.shape\n independent = tuple(independent)\n\n assert D < 20, (D, 'Sure?')\n\n if isinstance(initialization, self.Parameters):\n K = initialization.mixture_weights.shape[-1]\n assert K < 20, (K, 'Sure?')\n else:\n K = initialization.shape[-2]\n assert K < 20, (K, 'Sure?')\n assert initialization.shape[-1] == T, (initialization.shape, T)\n assert initialization.shape[:-2] == independent, (initialization.shape, independent)\n\n Y = _unit_norm(\n Y,\n axis=-1,\n eps=1e-10,\n eps_style='where'\n )\n\n Y_normalized_for_pdf = np.ascontiguousarray(Y)\n Y_normalized_for_psd = np.ascontiguousarray(np.swapaxes(Y, -2, -1))\n\n if isinstance(initialization, self.Parameters):\n params = initialization\n else:\n params = self.Parameters(eps=self.eps)\n params.affiliation = np.copy(initialization) # Shape (..., K, T)\n\n cw = ComplexWatson(D, max_concentration=max_concentration)\n\n if isinstance(initialization, self.Parameters):\n range_iterations = range(1, 1+iterations)\n else:\n range_iterations = range(iterations)\n\n if self.pbar:\n import tqdm\n range_iterations = tqdm.tqdm(range_iterations, 'cWMM Iteration')\n else:\n range_iterations = range_iterations\n\n for i in range_iterations:\n # E step\n if i > 0:\n params.affiliation = params._predict(\n Y_normalized_for_pdf,\n source_activity_mask=source_activity_mask,\n )\n\n # M step\n params.mixture_weights = np.mean(params.affiliation, axis=-1)\n\n Phi = get_power_spectral_density_matrix(\n Y_normalized_for_psd,\n np.maximum(params.affiliation, params.eps),\n sensor_dim=-2, source_dim=-2, time_dim=-1\n )\n\n params.complex_watson.mode, eigenvalues = get_pca(Phi)\n params.complex_watson.concentration = \\\n cw.hypergeometric_ratio_inverse(eigenvalues)\n return params\n", "sub_path": "dc_integration/distribution/cwmm.py", "file_name": "cwmm.py", "file_ext": "py", "file_size_in_byte": 5059, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "dc_integration.distribution.utils._Parameter", "line_number": 18, "usage_type": "name"}, {"api_name": "complex_watson.ComplexWatsonParameters", "line_number": 19, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 20, "usage_type": "call"}, {"api_name": "complex_watson.ComplexWatsonParameters", "line_number": 20, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "attribute"}, {"api_name": "complex_watson.ComplexWatson.pdf", "line_number": 33, "usage_type": "call"}, {"api_name": "complex_watson.ComplexWatson", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.ascontiguousarray", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.ascontiguousarray", "line_number": 45, "usage_type": "call"}, {"api_name": "dc_integration.distribution.utils._unit_norm", "line_number": 52, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 17, "usage_type": "name"}, {"api_name": "dc_integration.distribution.utils._unit_norm", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.ascontiguousarray", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.ascontiguousarray", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.swapaxes", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 125, "usage_type": "call"}, {"api_name": "complex_watson.ComplexWatson", "line_number": 127, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 149, "usage_type": "call"}, {"api_name": "dc_integration.utils.get_power_spectral_density_matrix", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 153, "usage_type": "call"}, {"api_name": "dc_integration.utils.get_pca", "line_number": 157, "usage_type": "call"}]} +{"seq_id": "197846223", "text": "#!/usr/bin/python\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom helpers import gtrends\nfrom pyculiarity.detect_ts import detect_ts\n\nKEYWORD = 'Vote'\nXLABEL='Time'\nYLABEL='Relative Interest over Time'\n\n# Get Google trend as a pandas DataFrame\ngoogle_trend_df = gtrends(keywords=[KEYWORD], timeframe='today 5-y')\n\n# Set Google hits as a time series\nts = google_trend_df[KEYWORD]\n\n# Plot data\n# Visualize time series with matplotlib (optional but useful if we're choosing between keywords)\nplt.title(KEYWORD + '- Google Trends Data')\n#plt.subtitle('United States search volume')\nplt.xlabel(XLABEL)\nplt.tick_params(axis='x', rotation=-45)\nplt.ylabel(YLABEL)\nplt.tight_layout()\nplt.autoscale()\nplt.plot(ts.index, ts.values)\nplt.savefig('../figures/election_google_trends_plot.png', bbox_inches='tight')\nplt.close()\n\n'''Anomalize\n\nReferences:\n Vallis, O., Hochenbaum, J. and Kejariwal, A., (2014) \"A Novel\n Technique for Long-Term Anomaly Detection in the Cloud\", 6th\n USENIX, Philadelphia, PA.\n\n Rosner, B., (May 1983), \"Percentage Points for a Generalized ESD\n Many-Outlier Procedure\" , Technometrics, 25(2), pp. 165-172.\n\n'''\n\n# First prepare data from truncated series\nmy_df = pd.DataFrame({'timestamp':ts.values, 'observation':ts.index})\n\nresults = detect_ts(df=my_df,\n max_anoms=0.02,\n direction=\"pos\",\n alpha=0.05,\n only_last=None,\n threshold=None,\n e_value=False,\n longterm=False,\n piecewise_median_period_weeks=2,\n plot=False,\n y_log=False,\n xlabel=XLABEL,\n ylabel=YLABEL,\n title='Google Trends Data - Twitter + IQR Method',\n verbose=False)\n\nplt.title(KEYWORD + '- Google Trends Data - Twitter + GES')\n#plt.subtitle('United States search volume')\nplt.xlabel(XLABEL)\nplt.tick_params(axis='x', rotation=-45)\nplt.ylabel(YLABEL)\nplt.tight_layout()\nplt.autoscale()\nplt.plot(ts.index, ts.values)\nplt.plot(results['anoms'].anoms, 'o')\nplt.savefig('../figures/election_x_anomalize_plot.png', bbox_inches='tight')\nplt.close()\n", "sub_path": "sample/election_example.py", "file_name": "election_example.py", "file_ext": "py", "file_size_in_byte": 2191, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "helpers.gtrends", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.autoscale", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 45, "usage_type": "call"}, {"api_name": "pyculiarity.detect_ts.detect_ts", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.autoscale", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}]} +{"seq_id": "502352832", "text": "import argparse\nimport json\nimport os\n\nimport tqdm\n\nfrom pytok import PyTok\n\ndef main(args):\n keywords = ['ukraine', 'standwithukraine', 'russia', 'nato', 'putin', 'moscow', 'zelenskyy', 'stopwar', 'stopthewar', 'ukrainewar', 'ww3' \\\n 'володимирзеленський', 'славаукраїні', 'путінхуйло🔴⚫🇺🇦', 'россия', 'війнавукраїні', 'зеленський', 'нівійні', 'війна', 'нетвойне', \\\n 'зеленский', 'путинхуйло', '%23denazification', '%23specialmilitaryoperation', '%23africansinukraine', '%23putinspeech', '%23whatshappeninginukraine']\n \n this_dir_path = os.path.dirname(os.path.abspath(__file__))\n data_dir_path = os.path.join(this_dir_path, 'data', 'searches')\n\n if not os.path.exists(data_dir_path):\n os.mkdir(data_dir_path)\n\n for keyword in keywords:\n file_path = os.path.join(data_dir_path, f\"{keyword}_videos.json\")\n if os.path.exists(file_path):\n continue\n\n video_data = []\n with PyTok(chrome_version=args.chrome_version) as api:\n for video in tqdm.tqdm(api.search(keyword).videos(count=10000), total=10000):\n video_data.append(video.info())\n\n with open(file_path, 'w') as f:\n json.dump(video_data, f)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--chrome-version')\n args = parser.parse_args()\n\n main(args)\n", "sub_path": "ukraine_tiktok/search_tiktoks.py", "file_name": "search_tiktoks.py", "file_ext": "py", "file_size_in_byte": 1485, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pytok.PyTok", "line_number": 26, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 27, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 31, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "9990790", "text": "# Copyright 2018 Red Hat, Inc. \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\n\nfrom rally_openstack.services.key_manager import barbican\nfrom tests.unit import test\n\n\nclass BarbicanServiceTestCase(test.TestCase):\n def setUp(self):\n super(BarbicanServiceTestCase, self).setUp()\n self.clients = mock.MagicMock()\n self.name_generator = mock.MagicMock()\n self.service = barbican.BarbicanService(\n self.clients,\n name_generator=self.name_generator)\n\n def atomic_actions(self):\n return self.service._atomic_actions\n\n def test__list_secrets(self):\n self.assertEqual(\n self.service.list_secrets(),\n self.service._clients.barbican().secrets.list.return_value\n )\n self._test_atomic_action_timer(self.atomic_actions(),\n \"barbican.list_secrets\")\n\n def test__create_secret(self):\n self.assertEqual(\n self.service.create_secret(),\n self.service._clients.barbican().secrets.create(\n name=\"fake_secret\", payload=\"rally_data\")\n )\n self._test_atomic_action_timer(self.atomic_actions(),\n \"barbican.create_secret\")\n\n def test__get_secret(self):\n self.service.get_secret(\"fake_secret\")\n self.service._clients.barbican().secrets.get \\\n .assert_called_once_with(\"fake_secret\")\n self._test_atomic_action_timer(self.atomic_actions(),\n \"barbican.get_secret\")\n\n def test__delete_secret(self):\n self.service.delete_secret(\"fake_secret\")\n self.service._clients.barbican().secrets.delete \\\n .assert_called_once_with(\"fake_secret\")\n self._test_atomic_action_timer(self.atomic_actions(),\n \"barbican.delete_secret\")\n", "sub_path": "tests/unit/services/barbican/test_secrets.py", "file_name": "test_secrets.py", "file_ext": "py", "file_size_in_byte": 2439, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "tests.unit.test.TestCase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "tests.unit.test", "line_number": 21, "usage_type": "name"}, {"api_name": "mock.MagicMock", "line_number": 24, "usage_type": "call"}, {"api_name": "mock.MagicMock", "line_number": 25, "usage_type": "call"}, {"api_name": "rally_openstack.services.key_manager.barbican.BarbicanService", "line_number": 26, "usage_type": "call"}, {"api_name": "rally_openstack.services.key_manager.barbican", "line_number": 26, "usage_type": "name"}]} +{"seq_id": "192501791", "text": "\"\"\" PyTorch implimentation of VAE and Super-Resolution VAE.\n\n Reposetory Author:\n Ioannis Gatopoulos, 2020\n\"\"\"\nimport logging\nimport os\nfrom datetime import datetime\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom src.train import train_model, load_and_evaluate\nfrom src.utils.args import prepare_parser\nfrom src.utils.utils import print_args, fix_random_seed, namespace2markdown\n\nif __name__ == \"__main__\":\n parser = prepare_parser()\n args = parser.parse_args()\n # Check device\n if args.device is None:\n args.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n output_folder = \"{}/{}_{}/\".format(args.output_folder, args.name_experiment,\n datetime.now().strftime(\"%d-%m-%Y_%H-%M-%S\"))\n os.makedirs(output_folder, exist_ok=True)\n args.output_folder = output_folder\n\n logger = logging.getLogger(\"VAE\")\n logger.setLevel(logging.DEBUG)\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n # add the handlers to the logger\n logger.addHandler(ch)\n\n fh = logging.FileHandler(\"{}/log.log\".format(args.output_folder))\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(formatter)\n # add the handlers to the logger\n logger.addHandler(fh)\n\n logger.info(\"Starting script\")\n\n # Print configs\n print_args(args=args, log=logger)\n\n # Control random seeds\n fix_random_seed(seed=args.seed)\n\n # Initialize TensorBoad writer (if enabled)\n logs_folder = '{}/logs/'.format(args.output_folder)\n os.makedirs(logs_folder, exist_ok=True)\n\n img_folder = '{}/images/'.format(args.output_folder)\n os.makedirs(img_folder, exist_ok=True)\n args.img_folder = img_folder\n\n writer = None\n if args.use_tb:\n writer = SummaryWriter(log_dir=logs_folder + '_' + args.model + '_' + args.tags +\n datetime.now().strftime(\"/%d-%m-%Y/%H-%M-%S\"))\n\n writer.add_text('args', namespace2markdown(args))\n\n # Train model\n train_model(writer=writer, log=logger, args=args)\n\n # Evaluate best (latest saved) model\n load_and_evaluate(model=args.model, log=logger, args=args)\n\n # End Experiment\n writer.close()\n logger.info('\\n' + 24 * '=' + ' Experiment Ended ' + 24 * '=')\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2507, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "src.utils.args.prepare_parser", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 22, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 30, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 33, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 35, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 40, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 41, "usage_type": "attribute"}, {"api_name": "src.utils.utils.print_args", "line_number": 49, "usage_type": "call"}, {"api_name": "src.utils.utils.fix_random_seed", "line_number": 52, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 56, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "name"}, {"api_name": "src.utils.utils.namespace2markdown", "line_number": 67, "usage_type": "call"}, {"api_name": "src.train.train_model", "line_number": 70, "usage_type": "call"}, {"api_name": "src.train.load_and_evaluate", "line_number": 73, "usage_type": "call"}]} +{"seq_id": "177956707", "text": "import requests\nimport json\n\n\nclass A:\n\n def run(self):\n response = requests.get('https://api.openweathermap.org/data/2.5/weather?q=Kolkata&appid=7e7c713211fd97fdac5e1330070499e9&units=metric')\n rs = json.dumps(response.json())\n js = json.loads(rs)\n print(js)\n x=js['main']\n for key, value in x.items():\n if key == \"temp\":\n str=value\n print(str)\n\n\n\n\nob = A()\nob.run()\n", "sub_path": "scripts/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 454, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 9, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "431614489", "text": "#Zed Bennett 2011\n#Kills referenced scene elements based on viewport selection \n\nimport maya.cmds as mc\n#UI Win\ndef removeRefUI(*args, **kwargs):\n if (mc.window(\"refKillWin\", ex=1)!=True):\n mc.window(\"refKillWin\", title=\"Reference Killer\", iconName='refKiller', widthHeight=(200, 40), s=0, tlb=1 )\n mc.columnLayout(rs=10)\n mc.text(label=\"Are you sure you want to kill selected references?\", align='center')\n mc.text(label=\"This cannot be undone.\", align='center')\n mc.setParent( '..' ) \n mc.rowColumnLayout( numberOfRows=1 )\n mc.button( label='No Thanks!', command=('mc.deleteUI(\\\"refKillWin\\\", window=True)'), width=100, align=\"center\" )\n mc.button( label='Kill em dead!', command=__kill, width=100, align=\"center\" )\n mc.setParent( '..' )\n mc.showWindow( \"refKillWin\" )\n else:\n mc.showWindow( \"refKillWin\" )\n#kill selected referenced elements\ndef __kill(*args, **kwargs):\n sel=mc.ls(sl=1, fl=1)\n pathList=[]\n for each in sel:\n if (mc.referenceQuery(each, inr=1)==1):\n pathList.append(mc.referenceQuery(each, f=1)) \n pathSet=set(pathList)\n for each in pathSet:\n try:\n mc.file(each, rr=1)\n except:\n pass\n \nremoveRefUI()", "sub_path": "scripts/python/maya/referencing/zb_removeReference.py", "file_name": "zb_removeReference.py", "file_ext": "py", "file_size_in_byte": 1284, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "maya.cmds.window", "line_number": 7, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 7, "usage_type": "name"}, {"api_name": "maya.cmds.window", "line_number": 8, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 8, "usage_type": "name"}, {"api_name": "maya.cmds.columnLayout", "line_number": 9, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 9, "usage_type": "name"}, {"api_name": "maya.cmds.text", "line_number": 10, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 10, "usage_type": "name"}, {"api_name": "maya.cmds.text", "line_number": 11, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 11, "usage_type": "name"}, {"api_name": "maya.cmds.setParent", "line_number": 12, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 12, "usage_type": "name"}, {"api_name": "maya.cmds.rowColumnLayout", "line_number": 13, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 13, "usage_type": "name"}, {"api_name": "maya.cmds.button", "line_number": 14, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 14, "usage_type": "name"}, {"api_name": "maya.cmds.button", "line_number": 15, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 15, "usage_type": "name"}, {"api_name": "maya.cmds.setParent", "line_number": 16, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 16, "usage_type": "name"}, {"api_name": "maya.cmds.showWindow", "line_number": 17, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 17, "usage_type": "name"}, {"api_name": "maya.cmds.showWindow", "line_number": 19, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 19, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 22, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 22, "usage_type": "name"}, {"api_name": "maya.cmds.referenceQuery", "line_number": 25, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 25, "usage_type": "name"}, {"api_name": "maya.cmds.referenceQuery", "line_number": 26, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 26, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 30, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 30, "usage_type": "name"}]} +{"seq_id": "269264590", "text": "import numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nimport keras_efficientnets\n\nimport constants\nfrom .base import BaseModel\nfrom utils.files import ClassifyH5File, NumpyFile\n\nn_cluster = 182\n\n\nclass ClassifyingImage(BaseModel):\n def __init__(self, model_path):\n load_file = ClassifyH5File(model_path)\n super(ClassifyingImage, self).__init__(load_file)\n\n def predict_class(self, image):\n image = np.array(image) / 255.\n image = np.reshape(image, (1, 80, 80, 3))\n feature = self.model.predict(image, verbose=1)\n feature /= np.linalg.norm(feature, axis=1, keepdims=True)\n dist, ind = self.neigh.kneighbors(feature, 1, True)\n return dist, ind\n\n def predict(self, image):\n return self.model.predict(image, verbose=1)\n\n\nclass ClassifyingEmbedding(BaseModel):\n\n def __init__(self, embedding_path):\n load_file = NumpyFile(embedding_path)\n super(ClassifyingEmbedding, self).__init__(load_file)\n self.neigh = KNeighborsClassifier(n_neighbors=1)\n self.neigh.fit(self.model, [i for i in range(n_cluster)])\n\n def predict(self, feature):\n return self.neigh.kneighbors(feature, 1, True)\n\n\nclass Classifying:\n\n def __init__(self, classifying_image: ClassifyingImage,\n classifying_embedding: ClassifyingEmbedding):\n self.classifying_image = classifying_image\n self.classifying_embedding = classifying_embedding\n\n def predict_class(self, image):\n image = self.preprocessing_image(image)\n feature = self.classifying_image.predict(image)\n feature /= np.linalg.norm(feature, axis=1, keepdims=True)\n return self.classifying_embedding.predict(feature)\n\n def preprocessing_image(self, image):\n image = np.array(image) / 255.\n image = np.reshape(image, (1, 80, 80, 3))\n return image\n\n\ndef get_classifying_model():\n classifying_image = ClassifyingImage(constants.CLASSIFYING_MODEL_PATH)\n classifying_embedding = ClassifyingEmbedding(constants.CLUSTER_PATH)\n return Classifying(classifying_image, classifying_embedding)\n", "sub_path": "models/classification.py", "file_name": "classification.py", "file_ext": "py", "file_size_in_byte": 2122, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "base.BaseModel", "line_number": 12, "usage_type": "name"}, {"api_name": "utils.files.ClassifyH5File", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 21, "usage_type": "attribute"}, {"api_name": "base.BaseModel", "line_number": 29, "usage_type": "name"}, {"api_name": "utils.files.NumpyFile", "line_number": 32, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 51, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 56, "usage_type": "call"}, {"api_name": "constants.CLASSIFYING_MODEL_PATH", "line_number": 61, "usage_type": "attribute"}, {"api_name": "constants.CLUSTER_PATH", "line_number": 62, "usage_type": "attribute"}]} +{"seq_id": "428908256", "text": "import pygame\r\n \r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\nBROWN = (170,50,10)\r\n \r\npygame.init()\r\n \r\nsize = (600, 600) # x, y\r\nscreen = pygame.display.set_mode(size)\r\n \r\npygame.display.set_caption(\"Draughts\")\r\n \r\ndone = False\r\n \r\nclock = pygame.time.Clock()\r\n\r\nsquare_size = 5\r\n\r\nyellow_circle = pygame.image.load(\"yellow_circle.png\") \r\n\r\nclass Blacksquare(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.Surface((75,75))\r\n self.image.fill(BLACK)\r\n self.rect = self.image.get_rect()\r\n self.rect.y = y\r\n self.rect.x = x\r\n\r\nclass Brownsquare(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.Surface((75,75))\r\n self.image.fill(BROWN)\r\n self.rect = self.image.get_rect()\r\n self.rect.y = y\r\n self.rect.x = x\r\n\r\nclass Piece(pygame.sprite.Sprite):\r\n def __init__(self,row,column):\r\n self.row = row\r\n self.column = column\r\n self.x = 0\r\n self.y = 0\r\n self.calculate_position()\r\n\r\n def calculate_position(self):\r\n self.x = square_size * self.column + square_size // 2\r\n self.y = square_size * self.row + square_size // 2\r\n \r\n def draw_white(self):\r\n radius = square_size // 2\r\n pygame.draw.circle(screen,WHITE,(self.x,self.y),radius)\r\n\r\nclass Board(pygame.sprite.Sprite):\r\n def __init__(self):\r\n self.selected_piece = None\r\n self.green_pieces_left = self_white_pieces_left = 12\r\n\r\n def draw_squares(self):\r\n board = [[1,0,1,0,1,0,1,0],\r\n [0,1,0,1,0,1,0,1],\r\n [1,0,1,0,1,0,1,0],\r\n [0,1,0,1,0,1,0,1],\r\n [1,0,1,0,1,0,1,0],\r\n [0,1,0,1,0,1,0,1],\r\n [1,0,1,0,1,0,1,0],\r\n [0,1,0,1,0,1,0,1]]\r\n \r\n for y in range(8):\r\n for x in range(8):\r\n if board[y][x] == 1:\r\n brownsquare = Brownsquare(x*75,y*75)\r\n all_sprites_list.add(brownsquare)\r\n brownsquare_list.add(brownsquare)\r\n pygame.draw.circle(screen,WHITE,(x,y),square_size)\r\n #piece = Piece(x,y)\r\n #piece.draw_white()\r\n else:\r\n blacksquare = Blacksquare(x*75,y*75)\r\n all_sprites_list.add(blacksquare)\r\n blacksquare_list.add(blacksquare)\r\n\r\nboard = Board()\r\nbrownsquare_list = pygame.sprite.Group()\r\nblacksquare_list = pygame.sprite.Group()\r\nall_sprites_list = pygame.sprite.Group()\r\n\r\nwhile not done:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n pass\r\n\r\n board.draw_squares()\r\n \r\n pygame.display.update()\r\n screen.fill(WHITE)\r\n all_sprites_list.update()\r\n all_sprites_list.draw(screen)\r\n pygame.display.flip()\r\n clock.tick(60)\r\n \r\npygame.quit()\r\n", "sub_path": "draughts.py", "file_name": "draughts.py", "file_ext": "py", "file_size_in_byte": 3069, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pygame.init", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 14, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 18, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 18, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 27, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pygame.sprite", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 79, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 88, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 89, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 89, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 90, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 93, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 97, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 102, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 106, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "633306036", "text": "from flask import Flask,render_template\n\nimport json,urllib,random\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n a = urllib.request.urlopen('https://www.boredapi.com/api/activity')\n d = json.loads(a.read())\n s = d['activity']\n darksky = urllib.request.urlopen('https://api.darksky.net/forecast/605bc9bbfcbfd2140fc5b6e638f39f6f/37.8267,-122.4233')\n d1 = json.loads(darksky.read())\n weather = d1['currently']['summary']\n temp = d1['currently']['temperature']\n\n xkcd = urllib.request.urlopen('https://xkcd.com/{}/info.0.json'.format(random.randint(0,2000)))\n d2 = json.loads(xkcd.read())\n comic = d2['img']\n alt = d2['alt']\n return render_template(\"basic_form.html\", activity = s, summary = weather + ' ' + str(temp) + 'F', comic = comic,alt=alt)\n\napp.debug = 1\napp.run()\n", "sub_path": "26_rrreeesssttt/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 818, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 8, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 9, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 11, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 12, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 16, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 16, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 20, "usage_type": "call"}]} +{"seq_id": "445506733", "text": "from pyspark.sql import SparkSession\nimport os\nfrom time import time\nfrom pyspark.sql.functions import array_contains\n\n\n\n## Create spark environment\nos.environ['PYSPARK_SUBMIT_ARGS'] = \"--conf spark.hadoop.io.compression.codecs=io.projectglow.sql.util.BGZFCodec --conf spark.sql.extensions=com.datastax.spark.connector.CassandraSparkExtensions --name 'PySparkShell' --packages 'io.projectglow:glow-spark3_2.12:0.6.0,com.datastax.spark:spark-cassandra-connector_2.12:3.0.0' pyspark-shell\"\n\n## Create spark builder\nspark = SparkSession.builder.appName(\"connector\") \\\n .master(\"local[*]\") \\\n .getOrCreate()\n\nspark.sparkContext.setLogLevel(\"OFF\")\n\n\n## Load dataframe to cassandra\nread_main_options = {\"table\": \"main\", \"keyspace\": \"genome\", \"spark.cassandra.connection.host\": \"10.168.206.98:9042, 10.168.206.98:9043, 10.168.206.98:9044, 10.168.206.98:9045\",}\nread_info_options = {\"table\": \"info\", \"keyspace\": \"genome\", \"spark.cassandra.connection.host\": \"10.168.206.98:9042, 10.168.206.98:9043, 10.168.206.98:9044, 10.168.206.98:9045\",}\nread_csq_options = {\"table\": \"csq\", \"keyspace\": \"genome\", \"spark.cassandra.connection.host\": \"10.168.206.98:9042, 10.168.206.98:9043, 10.168.206.98:9044, 10.168.206.98:9045\",}\n\ndf_main = spark.read\\\n .format(\"org.apache.spark.sql.cassandra\")\\\n .options(**read_main_options)\\\n .load()\n\ndf_info = spark.read\\\n .format(\"org.apache.spark.sql.cassandra\")\\\n .options(**read_info_options)\\\n .load()\n\ndf_csq = spark.read\\\n .format(\"org.apache.spark.sql.cassandra\")\\\n .options(**read_csq_options)\\\n .load()\n\nprint(\"Welcome to Query VCF\")\nwhile True:\n print(\"Type A to F for select query type\")\n print(\"A: Select * where chrom = 'xxx'\")\n print(\"B: Select * where chrom = 'xxx' and pos = 'xxx'\")\n print(\"C: Select * where chrom = 'xx' and pos >= 'xx' and pos <= 'xx'\")\n print(\"D: Select * where Existing_variation contains 'xxx'\")\n print(\"E: Select * where gnomADe_AF < xx and gnomADg_AF < xx\")\n print(\"F: Select * where symbol ='xxx' and consequence contains ‘xxx’\")\n print(\"Please type 'quit' to exit\")\n command = input(\"Type your command here => \")\n if command == \"quit\": break\n elif command == \"A\":\n chrom = input(\"chrom input => \")\n df_main_tmp = df_main.filter(df_main.chrom == chrom)\n df_info_tmp = df_info.filter(df_info.chrom == chrom)\n df_csq_tmp = df_csq.filter(df_csq.chrom == chrom)\n\n elif command == \"B\":\n chrom = input(\"chrom input => \")\n pos = int(input(\"pos input => \"))\n df_main_tmp = df_main.filter((df_main.chrom == chrom) & (df_main.pos == pos))\n df_info_tmp = df_info.filter((df_info.chrom == chrom) & (df_info.pos == pos))\n df_csq_tmp = df_csq.filter((df_csq.chrom == chrom) & (df_csq.pos == pos))\n elif command == \"C\":\n chrom = input(\"chrom input => \")\n pos_start = int(input(\"pos_start input => \"))\n pos_end = int(input(\"pos_start input => \"))\n df_main_tmp = df_main.filter((df_main.chrom == chrom) & (df_main.pos >= pos_start) & (df_main.pos <= pos_end))\n df_info_tmp = df_info.filter((df_info.chrom == chrom) & (df_info.pos >= pos_start) & (df_info.pos <= pos_end))\n df_csq_tmp = df_csq.filter((df_csq.chrom == chrom) & (df_csq.pos >= pos_start) & (df_csq.pos <= pos_end))\n\n elif command == \"D\":\n existing_variation = input(\"Existing_variation input => \")\n df_main_tmp = df_main\n df_info_tmp = df_info\n df_csq_tmp = df_csq.where(array_contains(\"existing_variation\", existing_variation))\n\n elif command == \"E\":\n gnomADe_AF = input(\"gonmADe_AF input => \")\n gnomADg_AF = input(\"gnomADg_AF input => \")\n df_main_tmp = df_main\n df_info_tmp = df_info\n df_csq_tmp = df_csq.filter((df_csq.gnomad_exomes_af < gnomADe_AF) & (df_csq.gnomad_genomes_af < gnomADg_AF))\n \n elif command == \"F\":\n symbol = input(\"symbol input => \")\n consequence = input(\"consequence = > \")\n df_main_tmp = df_main\n df_info_tmp = df_info\n df_csq_tmp = df_csq.filter(df_csq.symbol == symbol)\n df_csq_tmp = df_csq_tmp.where(array_contains(\"existing_variation\", existing_variation))\n \n df_main_tmp = df_main_tmp.withColumnRenamed(\"chrom\", \"chrom_main\")\\\n .withColumnRenamed(\"pos\", \"pos_main\")\n\n df_info_tmp = df_info_tmp.withColumnRenamed(\"chrom\", \"chrom_info\")\\\n .withColumnRenamed(\"pos\", \"pos_info\")\n\n df_csq_tmp = df_csq_tmp.withColumnRenamed(\"chrom\", \"chrom_csq\")\\\n .withColumnRenamed(\"pos\", \"pos_csq\")\n \n main_info_df = df_main_tmp.join(df_info_tmp, (df_main_tmp.chrom_main == df_info_tmp.chrom_info)&(df_main_tmp.pos_main == df_info_tmp.pos_info), \"inner\")\n main_info_df.drop(*[\"chrom_info\", \"pos_info\"])\n main_info_df = main_info_df.withColumnRenamed(\"chrom_main\", \"chrom\")\\\n .withColumnRenamed(\"pos_main\", \"pos\")\n \n df = df_csq_tmp.join(main_info_df, (df_csq_tmp.chrom_csq == main_info_df.chrom)&(df_csq_tmp.pos_csq == main_info_df.pos), \"left\")\n df = df.drop(*[\"chrom_csq\", \"info_csq\"])\n df.show()\n \nprint(\"Thank you for use program\")\n\n", "sub_path": "code for production/join_table.py", "file_name": "join_table.py", "file_ext": "py", "file_size_in_byte": 5202, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 12, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 12, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.array_contains", "line_number": 75, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.array_contains", "line_number": 90, "usage_type": "call"}]} +{"seq_id": "626274053", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect\nfrom .models import *\nfrom django.db.models import Count, Sum\n\n\ndef index(request):\n return render(request, \"poke/index.html\")\n\n\ndef register(request):\n valid, result = User.objects.validate_register(request.POST)\n if valid:\n messages.info(request, result)\n else:\n messages.error(request, result)\n return redirect(\"/main\")\n\n\ndef login(request):\n valid, result = User.objects.validate_login(request.POST)\n if valid:\n request.session[\"id\"] = result.id\n return redirect(\"/pokes\")\n else:\n messages.error(request, result)\n return redirect(\"/main\")\n\n\ndef pokes(request):\n if \"id\" not in request.session:\n return redirect(\"/main\")\n\n all_user_poke = PokeHistory_User.objects.filter(poked=User.objects.get(id=request.session[\"id\"])).order_by(\"-number\")\n user = User.objects.get(id=request.session[\"id\"])\n all_other_user = User.objects.all().exclude(id=request.session[\"id\"]).order_by(\"name\")\n\n ultimate_list = []\n for users in all_other_user:\n dict_1 = PokeHistory_User.objects.filter(poked=users).aggregate(Sum(\"number\"))\n if dict_1[\"number__sum\"] is None:\n dict_1[\"number__sum\"] = 0\n new_list = (dict_1, users)\n ultimate_list.append(new_list)\n\n context = {\n \"all_user_poke\": all_user_poke,\n \"user\": user,\n \"all_other_user\": all_other_user,\n \"number_of_poker\": len(all_user_poke),\n \"sum_user\": ultimate_list\n }\n\n return render(request, \"poke/pokes.html\", context)\n\n\ndef process(request, ids):\n current_user = User.objects.get(id=request.session[\"id\"])\n user2 = User.objects.get(id=ids)\n if len(PokeHistory_User.objects.filter(poker=current_user, poked=user2)) < 1:\n objects = PokeHistory_User.objects.create(poker=current_user, poked=user2, number=1)\n objects.save()\n else:\n objects = PokeHistory_User.objects.get(poker=current_user, poked=user2)\n objects.number += 1\n objects.save()\n return redirect(\"/pokes\")\n\n\ndef delete(request):\n del request.session[\"id\"]\n return redirect(\"/main\")\n\n\n\n\n\n\n", "sub_path": "apps/poke/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2261, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.shortcuts.render", "line_number": 10, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 18, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 18, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 19, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 28, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 28, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 29, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 42, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 56, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 69, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "508506625", "text": "import operator\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport Scraping\r\n\r\nwith open(\"footballdata.pickle\",'rb') as footballdata:\r\n data1 = pickle.load(footballdata)\r\nleague_data_1 = data1[0]\r\nleague_data_2 = data1[1]\r\n\r\nwith open('matchdays.pickle','rb') as matchday_tables:\r\n matchday_tables_data = pickle.load(matchday_tables)\r\nmatchday_tables_1 = matchday_tables_data[0]\r\nmatchday_tables_2 = matchday_tables_data[1]\r\n\r\nwith open('features.pickle','rb') as features:\r\n feature_data = pickle.load(features)\r\nfeatures_1 = feature_data[0]\r\nfeatures_2 = feature_data[1]\r\n\r\n#lambda fucntions \r\npoints = lambda team: team[1]\r\ndiff = lambda team: team[2]\r\n\r\ndef matchday_table(year,matchday,data):\r\n '''computes the matchday table given the year matchday and data from the first or second bundesliga.\r\n '''\r\n #add all matchdays up until the wanted matchday to a list\r\n matchdays = []\r\n for i in range(1,matchday+1):\r\n matchdays.append(data[(year,i)])\r\n #get a list of all teams\r\n teams = {}\r\n teams_and_scores = [x for game in matchdays[0] for x in game]\r\n for element in teams_and_scores:\r\n if len(element) > 4:\r\n teams[element] = [0,0,0,0,0,0,0] \r\n #for every matchday and game in those matchdays accumulate the points and goals also set the elos to 1500\r\n for element in matchdays:\r\n for game in element:\r\n points,home_goals,away_goals = calculate_game(game)\r\n home = game[0]\r\n away = game[1]\r\n status_home = teams[home]\r\n status_away = teams[away]\r\n status_home[1] += points[0]\r\n status_away[1] += points[1]\r\n status_home[2] += home_goals\r\n status_away[2] += away_goals\r\n status_home[3] += away_goals\r\n status_away[3] += home_goals\r\n status_home[4] = status_home[2] - status_home[3]\r\n status_away[4] = status_away[2] - status_away[3]\r\n status_home[5] = 1500\r\n status_away[5] = 1500\r\n #calculate the rank list and sort the teams give their rank\r\n #add the rank to each teams features\r\n rank_list = calculate_rank(teams)\r\n for i,team in enumerate(rank_list):\r\n status = teams[team]\r\n status[0] = i+1\r\n #return the dictionary of teams with their features\r\n return teams\r\n\r\ndef all_matchday_tables(data,year_input,matchday_input):\r\n matchday_dict = {}\r\n for year in range(1995,year_input):\r\n for matchday in range(1,35):\r\n matchday_dict[year,matchday] = matchday_table(year, matchday, data)\r\n for matchday in range(1,matchday_input):\r\n matchday_dict[year_input,matchday] = matchday_table(year_input, matchday, data)\r\n elo(matchday_dict, data, year_input, matchday_input)\r\n return matchday_dict\r\n\r\ndef scrape_update(year,matchday):\r\n global league_data_1, league_data_2\r\n league_data_1,league_data_2 = Scraping.scrape_update(year, matchday)\r\n return league_data_1,league_data_2\r\n\r\ndef update_matchday_data_1(year,matchday):\r\n global matchday_tables_1\r\n league_1,league_2 = scrape_update(year,matchday)\r\n matchday_data_1 = all_matchday_tables(league_data_1, year, matchday)\r\n matchday_data = [matchday_data_1,matchday_tables_2]\r\n matchday_tables_1 = matchday_data_1\r\n feat_1,feat_2 = pickle_all_features(year)\r\n pickle_matchday_data(matchday_data)\r\n return matchday_data_1,league_1,league_2,feat_1,feat_2\r\n\r\ndef update_matchday_data_2(year,matchday):\r\n global matchday_tables_2\r\n league_1,league_2 = scrape_update(year,matchday)\r\n matchday_data_2 = all_matchday_tables(league_data_2, year, matchday)\r\n matchday_data = [matchday_tables_1,matchday_data_2]\r\n matchday_tables_2 = matchday_data_2\r\n feat_1,feat_2 = pickle_all_features(year)\r\n pickle_matchday_data(matchday_data)\r\n return matchday_data_2,league_1,league_2,feat_1,feat_2\r\n\r\ndef pickle_matchday_data(data):\r\n with open('matchdays.pickle','wb') as matchday_tables:\r\n pickle.dump(data,matchday_tables)\r\n \r\ndef calculate_rank(teams):\r\n '''calculates the ranks of teams given their points goal ratios and scored goals\r\n '''\r\n temp_list = []\r\n for team in teams:\r\n temp_list.append([team,teams[team][1],teams[team][4],teams[team][2]])\r\n temp_list = sorted(temp_list,key = operator.itemgetter(1,2,3),reverse = True)\r\n return_list = []\r\n for element in temp_list:\r\n return_list.append(element[0])\r\n return return_list\r\n\r\ndef calculate_game(game):\r\n '''returns the points for home and away in form of a list [h,a] as well as the scored\r\n goals from home and away\r\n '''\r\n score = game[2]\r\n points = 0\r\n if score[1] == \":\":\r\n home_score = int(score[0])\r\n away_score = int(score[2:])\r\n else:\r\n home_score = int(score[0:1])\r\n away_score = int(score[3:])\r\n if home_score > away_score:\r\n points = [3,0]\r\n elif home_score < away_score:\r\n points = [0,3]\r\n else:\r\n points = [1,1]\r\n return points,home_score,away_score\r\n\r\ndef trans_result(score):\r\n if score[1] == \":\":\r\n home_score = int(score[0])\r\n away_score = int(score[2:])\r\n else:\r\n home_score = int(score[0:1])\r\n away_score = int(score[3:])\r\n return home_score,away_score\r\n \r\n\r\ndef winner(game):\r\n '''returns who the winner of a game is in form of a 1 hot vector\r\n '''\r\n score = game[2]\r\n win = 0\r\n home_score,away_score = trans_result(score)\r\n if home_score > away_score:\r\n win = [1,0,0]\r\n elif home_score < away_score:\r\n win = [0,0,1]\r\n else:\r\n win = [0,1,0]\r\n return win,home_score,away_score\r\n\r\n#lambda functions for elos\r\nexpected_score = lambda rating_a, rating_b: 1.0/(1.0+10**((rating_b-rating_a)/400))\r\nrating_update = lambda rating, score, expected_score: rating + 32*(score-expected_score)\r\n\r\ndef calculate_elo(rating_a,rating_b,outcome):\r\n '''calculates the new elos for 2 teams given their current rating as well as the outcome\r\n of the game out the the view of the home team\r\n '''\r\n expected_a = expected_score(rating_a,rating_b)\r\n expected_b = 1-expected_a\r\n rating_a = int(rating_update(rating_a,outcome,expected_a))\r\n rating_b = int(rating_update(rating_b,1-outcome,expected_b))\r\n return rating_a,rating_b\r\n\r\ndef home_win_elo_ratio(game):\r\n '''returns the result of a game out the view of the home team\r\n '''\r\n result,_,_ = winner(game)\r\n if result == [1,0,0]:\r\n return 1\r\n if result == [0,1,0]:\r\n return 0.5\r\n if result == [0,0,1]:\r\n return 0\r\n \r\ndef elo(matchday_tables,league_data,year_input,matchday_input):\r\n '''calculates the elos for all teams given the matchday tables of the entire data set and the\r\n league data. the elos are added to the matchday table data into the last slot [5]\r\n '''\r\n for year in range(1995,year_input):\r\n for matchday in range(1,35):\r\n #if it is the first matchday try to take the the last matchday of the previous season\r\n #if that is not possible just take the first matchday\r\n #this enables continuous elos over multiple seasons\r\n if matchday == 1:\r\n try:\r\n table_1 = matchday_tables[year-1,34]\r\n except:\r\n table_1 = matchday_tables[year,1]\r\n #if it is not the first matchday just take the previous matchday\r\n else:\r\n table_1 = matchday_tables[year,matchday-1]\r\n #also grab the current matchday\r\n table = matchday_tables[year,matchday]\r\n #for every game in that matchday obtain the result of the match and current ratings of the teams\r\n #if the ratings cannot be obtained because the team just came from a lower league just use 1500\r\n #as the elo\r\n for game in league_data[year,matchday]:\r\n home_score = home_win_elo_ratio(game)\r\n team_h = game[0]\r\n team_a = game[1]\r\n try:\r\n rating_h = table_1[team_h][5]\r\n except:\r\n rating_h = 1500\r\n try:\r\n rating_a = table_1[team_a][5]\r\n except:\r\n rating_a = 1500\r\n #calculate the new elos using the formulas and change the elos in the matchday table\r\n print('')\r\n rating_h,rating_a = calculate_elo(rating_h, rating_a, home_score)\r\n table[team_h][5] = rating_h\r\n table[team_a][5] = rating_a\r\n for matchday in range(1,matchday_input):\r\n #if it is the first matchday try to take the the last matchday of the previous season\r\n #if that is not possible just take the first matchday\r\n #this enables continuous elos over multiple seasons\r\n if matchday == 1:\r\n try:\r\n table_1 = matchday_tables[year_input-1,34]\r\n except:\r\n table_1 = matchday_tables[year_input,1]\r\n #if it is not the first matchday just take the previous matchday\r\n else:\r\n table_1 = matchday_tables[year_input,matchday-1]\r\n #also grab the current matchday\r\n table = matchday_tables[year_input,matchday]\r\n #for every game in that matchday obtain the result of the match and current ratings of the teams\r\n #if the ratings cannot be obtained because the team just came from a lower league just use 1500\r\n #as the elo\r\n for game in league_data[year_input,matchday]:\r\n home_score = home_win_elo_ratio(game)\r\n team_h = game[0]\r\n team_a = game[1]\r\n try:\r\n rating_h = table_1[team_h][5]\r\n except:\r\n rating_h = 1500\r\n try:\r\n rating_a = table_1[team_a][5]\r\n except:\r\n rating_a = 1500\r\n #calculate the new elos using the formulas and change the elos in the matchday table\r\n rating_h,rating_a = calculate_elo(rating_h, rating_a, home_score)\r\n table[team_h][5] = rating_h\r\n table[team_a][5] = rating_a\r\n\r\ndef elo_graph(team,matchday_tables):\r\n '''records the elos of a given team over all seasons and matchdays and plots them\r\n '''\r\n elos = []\r\n for year in range(1995,2016):\r\n for matchday in range(1,35):\r\n try:\r\n elos.append(matchday_tables[year,matchday][team][5])\r\n except:\r\n pass\r\n plt.plot(elos)\r\n plt.show()\r\n \r\ndef get_features_test(matchday_tables,league_data,year_input,matchday_input):\r\n '''creates feature matrix from the matchday tables of the whole season and the given game data\r\n '''\r\n train_data = []\r\n test_data = []\r\n train_labels = []\r\n test_labels = []\r\n for year in range(1995,year_input-1):\r\n for matchday in range(1,35):\r\n for game in league_data[year,matchday]:\r\n home = game[0]\r\n away = game[1]\r\n train_data.append([matchday,\r\n matchday_tables[year,matchday][home][0],\r\n matchday_tables[year,matchday][home][5],\r\n matchday_tables[year,matchday][home][2]/matchday,\r\n matchday_tables[year,matchday][home][3]/matchday,\r\n matchday_tables[year,matchday][away][0],\r\n matchday_tables[year,matchday][away][5],\r\n matchday_tables[year,matchday][away][2]/matchday,\r\n matchday_tables[year,matchday][away][3]/matchday])\r\n temp,_,_ = winner(game)\r\n train_labels.append(temp)\r\n for matchday in range(1,matchday_input+1):\r\n for game in league_data[year_input,matchday]:\r\n home = game[0]\r\n away = game[1]\r\n test_data.append([matchday,\r\n matchday_tables[year_input,matchday][home][0],\r\n matchday_tables[year_input,matchday][home][5],\r\n matchday_tables[year_input,matchday][home][2]/matchday,\r\n matchday_tables[year_input,matchday][home][3]/matchday,\r\n matchday_tables[year_input,matchday][away][0],\r\n matchday_tables[year_input,matchday][away][5],\r\n matchday_tables[year_input,matchday][away][2]/matchday,\r\n matchday_tables[year_input,matchday][away][3]/matchday])\r\n temp,_,_ = winner(game)\r\n test_labels.append(temp)\r\n train_data = np.array(train_data)\r\n train_labels = np.array(train_labels)\r\n test_data = np.array(test_data)\r\n test_labels = np.array(test_labels)\r\n return train_data,test_data,train_labels,test_labels\r\n\r\ndef get_features(matchday_tables,league_data,year_input):\r\n '''creates feature matrix from the matchday tables of the whole season and the given game data\r\n '''\r\n train_data = []\r\n train_labels = []\r\n res_labels = []\r\n res_data = []\r\n for year in range(1995,year_input):\r\n for matchday in range(5,35):\r\n for game in league_data[year,matchday]:\r\n home = game[0]\r\n away = game[1]\r\n train_data.append([matchday,\r\n matchday_tables[year,matchday][home][0],\r\n matchday_tables[year,matchday][home][5],\r\n matchday_tables[year,matchday][home][2]/matchday,\r\n matchday_tables[year,matchday][home][3]/matchday,\r\n matchday_tables[year,matchday][away][0],\r\n matchday_tables[year,matchday][away][5],\r\n matchday_tables[year,matchday][away][2]/matchday,\r\n matchday_tables[year,matchday][away][3]/matchday])\r\n res_data = train_data\r\n temp,home_score,away_score = winner(game)\r\n train_labels.append(temp)\r\n res_labels.append([home_score,away_score])\r\n train_data = np.array(train_data)\r\n train_labels = np.array(train_labels)\r\n return train_data,train_labels,res_labels,res_data\r\n\r\ndef pickle_all_features_test(year_input,matchday_input):\r\n data = [get_features_test(matchday_tables_1, league_data_1, year_input),get_features_test(matchday_tables_2, league_data_2, year_input)]\r\n with open('features.pickle','wb') as features:\r\n pickle.dump(data,features)\r\n \r\ndef pickle_all_features(year_input):\r\n global features_1\r\n global features_2\r\n data = [get_features(matchday_tables_1, league_data_1, year_input),get_features(matchday_tables_2, league_data_2, year_input)]\r\n features_1 = data[0]\r\n features_2 = data[1]\r\n with open('features.pickle','wb') as features:\r\n pickle.dump(data,features)\r\n return features_1,features_2\r\n \r\ndef current_features_prob(year_input,matchday_input,home_team,away_team,matchday_table):\r\n if matchday_input != 1:\r\n table = matchday_table[year_input,matchday_input-1]\r\n else:\r\n table = matchday_table[year_input-1,34]\r\n home = table[home_team]\r\n away = table[away_team]\r\n if matchday_input != 1:\r\n return [matchday_input-1,\r\n home[0],\r\n home[5],\r\n home[2]/(matchday_input-1),\r\n home[3]/(matchday_input-1),\r\n away[0],\r\n away[5],\r\n away[2]/(matchday_input-1),\r\n away[3]/(matchday_input-1)]\r\n else:\r\n return [matchday_input-1,\r\n home[0],\r\n home[5],\r\n home[2]/34,\r\n home[3]/34,\r\n away[0],\r\n away[5],\r\n away[2]/34,\r\n away[3]/34]\r\n \r\ndef current_features_res(year_input,matchday_input,home_team,away_team,matchday_table):\r\n if matchday_input != 1:\r\n table = matchday_table[year_input,matchday_input-1]\r\n else:\r\n table = matchday_table[year_input-1,34]\r\n home = table[home_team]\r\n away = table[away_team]\r\n if matchday_input != 1:\r\n return [matchday_input,\r\n home[0],\r\n home[5],\r\n home[2]/(matchday_input-1),\r\n home[3]/(matchday_input-1),\r\n away[0],\r\n away[5],\r\n away[2]/(matchday_input-1),\r\n away[3]/(matchday_input-1)]\r\n else:\r\n return [matchday_input,\r\n home[0],\r\n home[5],\r\n home[2]/34,\r\n home[3]/34,\r\n away[0],\r\n away[5],\r\n away[2]/34,\r\n away[3]/34]\r\n", "sub_path": "Descrpition_Methods.py", "file_name": "Descrpition_Methods.py", "file_ext": "py", "file_size_in_byte": 17130, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pickle.load", "line_number": 8, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 13, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 18, "usage_type": "call"}, {"api_name": "Scraping.scrape_update", "line_number": 78, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 103, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 342, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 348, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 357, "usage_type": "call"}]} +{"seq_id": "300349132", "text": "# -*- coding:utf-8 -*-\nfrom django import forms\nfrom django.forms import widgets\n\nfrom cadastro.models import Fornecedor\n\n\nclass FormLogin(forms.Form):\n usuario = forms.CharField(label='Usuário', required=True)\n senha = forms.CharField(label='Senha', required=True)\n\n\nclass FormLocalizaFornecedor(forms.Form):\n nome = forms.CharField(label='Nome', required=True,\n widget=forms.TextInput(attrs={'placeholder': 'Digite o nome para filtrar', 'class': 'form-control'}))\n\n\nclass FormFotoFornecedor(forms.Form):\n file = forms.FileField(label='Buscar Foto')\n\n\nclass FormFornecedor(forms.ModelForm):\n class Meta:\n model = Fornecedor\n #fields = ['nome', 'foto']\n fields = ['nome']\n\n widgets = {\n 'nome': widgets.TextInput(attrs={'class': 'form-control'}),\n }\n\n\nclass FormLancamentoFornecedor(forms.Form):\n CD = (\n ('Crédito', (\n ('CD', 'Créditar'),\n ('CE', 'Estornar Crédito'),\n )\n ),\n ('Débito', (\n ('DD', 'Débitar'),\n ('DE', 'Estornar Débito'),\n )\n )\n )\n\n cd = forms.ChoiceField(widget=forms.RadioSelect, choices=CD)\n valor = forms.DecimalField(label='Valor', max_digits=15, decimal_places=2, initial=0,\n widget=forms.TextInput(attrs={'class': 'form-control'}))", "sub_path": "loja_fornecedor/cadastro/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1400, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.forms.Form", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 9, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.Form", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 14, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 15, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 15, "usage_type": "name"}, {"api_name": "django.forms.Form", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 18, "usage_type": "name"}, {"api_name": "django.forms.FileField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 19, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 22, "usage_type": "name"}, {"api_name": "cadastro.models.Fornecedor", "line_number": 24, "usage_type": "name"}, {"api_name": "django.forms.widgets", "line_number": 28, "usage_type": "name"}, {"api_name": "django.forms.widgets.TextInput", "line_number": 29, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 29, "usage_type": "name"}, {"api_name": "django.forms.Form", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 33, "usage_type": "name"}, {"api_name": "django.forms.ChoiceField", "line_number": 47, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 47, "usage_type": "name"}, {"api_name": "django.forms.RadioSelect", "line_number": 47, "usage_type": "attribute"}, {"api_name": "django.forms.DecimalField", "line_number": 48, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 48, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 49, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 49, "usage_type": "name"}]} +{"seq_id": "68377706", "text": "#! /usr/bin/env python\nimport rospy\nimport numpy as np\n\nfrom sensor_msgs import point_cloud2\nfrom sensor_msgs.msg import PointCloud2, LaserScan, PointField\nfrom nav_msgs.msg import OccupancyGrid\nfrom laser_geometry import laser_geometry\nfrom tf import TransformListener\nimport tf.transformations\nimport ros_numpy\nimport time\n\n\nclass GridMapper:\n def __init__(self, cell_size=0.05, grid_size = [2000,2000] ):\n \"\"\"\n 1) Initialize a fixed sized map\n 2) Convert Laserscan to Pointcloud\n 3) Transform Pointcloud to odom_combined frame\n 4) Project Pointcloud into map\n 5) Publish Map\n \"\"\"\n self.cell_size = cell_size\n self.grid_size = np.array(grid_size)\n\n self.initGrid()\n\n self.tf = TransformListener()\n self.lp = laser_geometry.LaserProjection()\n self.vis_pub = rospy.Publisher('grid_map', OccupancyGrid, queue_size=1)\n self.sub = rospy.Subscriber(\"/scan\", LaserScan, self.laserCb, queue_size=1)\n self.cloudPub = rospy.Publisher(\"cloud\", PointCloud2, queue_size=1)\n self.current_time = rospy.Time.now()\n\n def initGrid(self):\n self.min_pos = -self.grid_size/2 * self.cell_size\n self.grid_map = np.ones(self.grid_size, dtype=np.int8) * -1\n\n def laserCb(self, scan_msg):\n # print('laser')\n\n start = time.time()\n \n\n src_frame = scan_msg.header.frame_id\n target_frame = 'odom_combined'\n\n # print('tf transform')\n try:\n pos, quat = self.getCurrentTransformation(target_frame, src_frame)\n except Exception as a:\n print(a)\n return\n\n # print('converting pcl')\n cloud = self.lp.projectLaser(scan_msg)\n\n xyz_array = self.pointcloud_to_numpy_array(cloud)\n \n xyz_array_transformed = self.transformPoints(xyz_array, pos, quat)\n \n # test correct transformation\n # out_cloud = self.numpy_array_to_pointcloud(xyz_array_transformed, frame_id=target_frame)\n # self.cloudPub.publish(out_cloud)\n \n xy_array_transformed = xyz_array_transformed[:,:2]\n\n\n # print('fill grid')\n self.grid_map = self.fill_grid(self.grid_map, xy_array_transformed, self.min_pos, self.cell_size, pos)\n\n oc_grid = ros_numpy.occupancy_grid.numpy_to_occupancy_grid(self.grid_map)\n\n oc_grid.header.frame_id = target_frame\n oc_grid.header.stamp = scan_msg.header.stamp\n oc_grid.info.width = self.grid_size[0]\n oc_grid.info.height = self.grid_size[1]\n oc_grid.info.resolution = self.cell_size\n oc_grid.info.origin.position.x = self.min_pos[0]\n oc_grid.info.origin.position.y = self.min_pos[1]\n \n # print('publish grid')\n self.vis_pub.publish(oc_grid)\n\n end = time.time()\n ellapsed = end - start\n\n print('ellapsed time:')\n print(ellapsed)\n\n # save map if time exceeded\n if rospy.Time.now() - self.current_time > rospy.Duration(10.0):\n \n self.save_map('map.pgm')\n self.current_time = rospy.Time.now()\n print('map saved')\n\n def save_map(self, filename):\n\n x_dim = self.grid_size[0]\n y_dim = self.grid_size[1]\n pixels = self.grid_map\n\n fout=open(filename, 'wb')\n pgmHeader = 'P2' + '\\n' + str(y_dim) + ' ' + str(x_dim) + '\\n' + str(255) + '\\n'\n fout.write(pgmHeader)\n\n for i in range(x_dim):\n line = \"\"\n for j in range(y_dim):\n \n pixel = pixels[(x_dim - 1) - i, (y_dim - 1) - j]\n pixel_out = 128\n if pixel == -1:\n pixel_out = 128\n elif pixel == 100:\n pixel_out = 0\n else:\n pixel_out = 255\n line += str(pixel_out) + \" \"\n line += \"\\n\"\n fout.write(line)\n\n fout.close()\n \n def pointcloud_to_numpy_array(self, pointcloud):\n \"\"\"\n Converting Pointcloud2 to Numpy Array (3,N)\n \"\"\"\n pointcloud2_array = ros_numpy.numpify(pointcloud)\n return ros_numpy.point_cloud2.get_xyz_points(pointcloud2_array)\n\n def numpy_array_to_pointcloud(self, numpy_array, frame_id, stamp=None):\n \"\"\"\n Converting Numpy Array (3,N) to Pointcloud2\n \"\"\"\n if stamp is None:\n stamp = rospy.Time.now()\n out_cloud = self.xyz_array_to_pointcloud2(numpy_array, frame_id=frame_id, stamp=stamp)\n return out_cloud\n\n def fill_grid(self, grid_map, xy_array_transformed, grid_min_point, grid_res, my_pos):\n \n my_coord = self.point_to_grid(my_pos, grid_min_point, grid_res)\n grid_coords = self.points_to_grid(xy_array_transformed, grid_min_point, grid_res)\n \n grid_map[my_coord[1], my_coord[0]] = 0\n \n # BresenhamLine\n \n src_x = my_coord[1]\n src_y = my_coord[0]\n\n for i in range(grid_coords.shape[0]):\n coord = grid_coords[i,:]\n\n # Draw BresenhamLine from my_coord to coord\n target_x = coord[1]\n target_y = coord[0]\n\n dx = np.abs( target_x - src_x )\n dy = np.abs( target_y - src_y )\n \n if src_x < target_x:\n sx = 1\n else:\n sx = -1\n\n if src_y < target_y:\n sy = 1\n else:\n sy = -1\n\n error = dx - dy\n x = src_x\n y = src_y\n\n while x != target_x and y != target_y:\n\n if x < 0 or y < 0:\n continue\n\n grid_map[int(x),int(y)] = 0\n e2 = 2 * error\n if e2 > -dy:\n error = error - dy\n x += sx\n \n if e2 < dx:\n error = error + dx\n y += sy\n \n # draw black line endings\n grid_map[coord[1], coord[0]] = 100\n\n return grid_map\n\n def xyz_array_to_pointcloud2(self, points, stamp=None, frame_id=None):\n '''\n Create a sensor_msgs.PointCloud2 from an array\n of points.\n '''\n msg = PointCloud2()\n if stamp:\n msg.header.stamp = stamp\n if frame_id:\n msg.header.frame_id = frame_id\n if len(points.shape) == 3:\n msg.height = points.shape[1]\n msg.width = points.shape[0]\n else:\n msg.height = 1\n msg.width = len(points)\n msg.fields = [\n PointField('x', 0, PointField.FLOAT32, 1),\n PointField('y', 4, PointField.FLOAT32, 1),\n PointField('z', 8, PointField.FLOAT32, 1)]\n msg.is_bigendian = False\n msg.point_step = 12\n msg.row_step = 12*points.shape[0]\n msg.is_dense = int(np.isfinite(points).all())\n msg.data = np.asarray(points, np.float32).tostring()\n\n return msg\n\n def getCurrentTransformation(self, src_frame, target_frame, stamp=None):\n \"\"\"\n Get Current Transformation\n \"\"\"\n t = stamp\n if t is None:\n t = self.tf.getLatestCommonTime(src_frame, target_frame)\n \n position, quaternion = self.tf.lookupTransform(src_frame, target_frame, t)\n return position, quaternion\n\n def transformPoints(self, np_points, trans, quaternion):\n \"\"\"\n Transforms points. np_points.shape == (N,3)\n \"\"\"\n pos = np.zeros((3,1))\n pos[0] = trans[0]\n pos[1] = trans[1]\n theta = tf.transformations.euler_from_quaternion(quaternion)[2]\n\n R = np.array([[np.cos(theta), -np.sin(theta), 0.0 ], \\\n [np.sin(theta), np.cos(theta), 0.0 ], \\\n [ 0.0, 0.0, 1.0 ] ])\n\n # p' = R * p + t\n np_points = R.dot(np_points.transpose())\n np_points = np.add(np_points, pos).transpose()\n return np_points\n\n def point_to_grid(self, point, grid_min_point, grid_res):\n grid_point = point[:2] - grid_min_point\n grid_coord = grid_point / grid_res\n return grid_coord.astype(int)\n\n def points_to_grid(self, xy_points, grid_min_point, grid_res):\n grid_points = xy_points - grid_min_point\n grid_coords = grid_points / grid_res\n return grid_coords.astype(int)\n \n\n\ndef node():\n rospy.init_node('grid_mapper_py')\n\n gm = GridMapper(cell_size=0.15, grid_size=[400,400])\n \n rospy.spin()\n\nif __name__ == '__main__':\n try:\n node()\n except rospy.ROSInterruptException:\n pass\n", "sub_path": "blatt8/scripts/grid_mapper.py", "file_name": "grid_mapper.py", "file_ext": "py", "file_size_in_byte": 8704, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 25, "usage_type": "call"}, {"api_name": "tf.TransformListener", "line_number": 29, "usage_type": "call"}, {"api_name": "laser_geometry.laser_geometry.LaserProjection", "line_number": 30, "usage_type": "call"}, {"api_name": "laser_geometry.laser_geometry", "line_number": 30, "usage_type": "name"}, {"api_name": "rospy.Publisher", "line_number": 31, "usage_type": "call"}, {"api_name": "nav_msgs.msg.OccupancyGrid", "line_number": 31, "usage_type": "argument"}, {"api_name": "rospy.Subscriber", "line_number": 32, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.LaserScan", "line_number": 32, "usage_type": "argument"}, {"api_name": "rospy.Publisher", "line_number": 33, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointCloud2", "line_number": 33, "usage_type": "argument"}, {"api_name": "rospy.Time.now", "line_number": 34, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 34, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 38, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 43, "usage_type": "call"}, {"api_name": "ros_numpy.occupancy_grid.numpy_to_occupancy_grid", "line_number": 73, "usage_type": "call"}, {"api_name": "ros_numpy.occupancy_grid", "line_number": 73, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 86, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 93, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 93, "usage_type": "attribute"}, {"api_name": "rospy.Duration", "line_number": 93, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 96, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 96, "usage_type": "attribute"}, {"api_name": "ros_numpy.numpify", "line_number": 131, "usage_type": "call"}, {"api_name": "ros_numpy.point_cloud2.get_xyz_points", "line_number": 132, "usage_type": "call"}, {"api_name": "ros_numpy.point_cloud2", "line_number": 132, "usage_type": "attribute"}, {"api_name": "rospy.Time.now", "line_number": 139, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 163, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointCloud2", "line_number": 204, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointField", "line_number": 216, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointField.FLOAT32", "line_number": 216, "usage_type": "attribute"}, {"api_name": "sensor_msgs.msg.PointField", "line_number": 217, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointField.FLOAT32", "line_number": 217, "usage_type": "attribute"}, {"api_name": "sensor_msgs.msg.PointField", "line_number": 218, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.PointField.FLOAT32", "line_number": 218, "usage_type": "attribute"}, {"api_name": "numpy.isfinite", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 223, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 242, "usage_type": "call"}, {"api_name": "tf.transformations.euler_from_quaternion", "line_number": 245, "usage_type": "call"}, {"api_name": "tf.transformations", "line_number": 245, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 253, "usage_type": "call"}, {"api_name": "rospy.init_node", "line_number": 269, "usage_type": "call"}, {"api_name": "rospy.spin", "line_number": 273, "usage_type": "call"}, {"api_name": "rospy.ROSInterruptException", "line_number": 278, "usage_type": "attribute"}]} +{"seq_id": "149897360", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 10 07:49:21 2017\n\n@author: pavel\n\"\"\"\nimport time\nimport subprocess\nimport logging\n\n\nfrom pynput.keyboard import Controller, Listener\nfrom xkbgroup import XKeyboard\n\nimport layout_corrector.config as config\nimport layout_corrector.correction as correction\nimport layout_corrector.state as state\n\nlog = logging.getLogger(__name__)\n\ngroup_sounds = {0: config.layout_0_sound,\n 1: config.layout_1_sound,}\n\n\ndef key_combo(keyboard, modifier, key):\n \"\"\"\n with keyboard.pressed(modifier):\n keyboard.press(key)\n keyboard.release(key)\n \"\"\"\n keyboard.press(modifier)\n keyboard.press(key)\n keyboard.release(key)\n keyboard.release(modifier)\n \ndef cut_to_buffer(keyboard):\n key_combo(keyboard, *config.cut_combo)\n \ndef paste_from_buffer(keyboard):\n key_combo(keyboard, *config.paste_combo)\n \ndef get_buffer():\n #pyperclip\n p = subprocess.Popen(['xsel', '-b', '-o'],\n stdout=subprocess.PIPE, close_fds=True)\n stdout, stderr = p.communicate()\n return stdout.decode('utf-8')\n \ndef set_buffer(text):\n p = subprocess.Popen(['xsel', '-b', '-i'],\n stdin=subprocess.PIPE, close_fds=True)\n p.communicate(input=text.encode('utf-8'))\n\ndef play(sound):\n if config.sounds:\n try:\n p = subprocess.Popen([\"aplay\", sound], \n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, close_fds=True)\n #stdout, stderr = p.communicate()\n #print(stdout.decode('utf-8')) \n except Exception as e:\n log.exception(e)\n\nclass Switcher:\n def __init__(self):\n self.xkb = XKeyboard()\n self.controller = Controller()\n self.state = state.StateMachine()\n \n self.busy = False\n \n def run(self): \n with Listener(on_press = self.on_key_press,\n on_release = self.on_key_release) as listener:\n listener.join()\n \n\n def announce_key(self):\n group = self.xkb.group_num \n play(group_sounds.get(group))\n \n\n def on_key_press(self, key):\n log.debug(\"%s pressed\", key) \n self.state.press(key)\n \n try:\n char = key.char\n self.announce_key()\n except Exception as e: #not a char\n if key in config.sound_keys:\n self.announce_key()\n\n \n def on_key_release(self, key):\n log.debug(\"%s released\", key)\n if self.state.bingo():\n self.replace_selection()\n self.state.release(key) \n \n def get_text(self): \n cut_to_buffer(self.controller)\n \n text = get_buffer()\n log.debug(\"get text: %s\", text) \n return text\n \n def set_text(self, text):\n log.debug(\"set_text: %s\", text)\n set_buffer(text) \n paste_from_buffer(self.controller)\n\n def replace_selection(self):\n if not self.busy:\n self.busy = True \n log.info(\"Making correction\")\n \n for key in self.state.pressed_keys():\n self.controller.release(key)\n \n text = self.get_text() \n \n if len(text) > 0:\n new_text = correction.correct(text)\n log.info(\"correction: %s -> %s\", text, new_text)\n \n time.sleep(config.replace_delay)\n self.set_text(new_text) \n play(config.replace_sound)\n else:\n log.info(\"nothing to correct\")\n\t\t\t\t\n \n self.busy = False\n \nif __name__ == '__main__':\n Switcher().run()\n", "sub_path": "debian/layout-corrector/usr/share/layout-corrector/layout_corrector.py", "file_name": "layout_corrector.py", "file_ext": "py", "file_size_in_byte": 3804, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "layout_corrector.config.layout_0_sound", "line_number": 22, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 22, "usage_type": "name"}, {"api_name": "layout_corrector.config.layout_1_sound", "line_number": 23, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 23, "usage_type": "name"}, {"api_name": "layout_corrector.config.cut_combo", "line_number": 38, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 38, "usage_type": "name"}, {"api_name": "layout_corrector.config.paste_combo", "line_number": 41, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 41, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 45, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 51, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 52, "usage_type": "attribute"}, {"api_name": "layout_corrector.config.sounds", "line_number": 56, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 56, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 58, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 59, "usage_type": "attribute"}, {"api_name": "subprocess.STDOUT", "line_number": 60, "usage_type": "attribute"}, {"api_name": "xkbgroup.XKeyboard", "line_number": 68, "usage_type": "call"}, {"api_name": "pynput.keyboard.Controller", "line_number": 69, "usage_type": "call"}, {"api_name": "layout_corrector.state.StateMachine", "line_number": 70, "usage_type": "call"}, {"api_name": "layout_corrector.state", "line_number": 70, "usage_type": "name"}, {"api_name": "pynput.keyboard.Listener", "line_number": 75, "usage_type": "call"}, {"api_name": "layout_corrector.config.sound_keys", "line_number": 93, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 93, "usage_type": "name"}, {"api_name": "layout_corrector.correction.correct", "line_number": 126, "usage_type": "call"}, {"api_name": "layout_corrector.correction", "line_number": 126, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 129, "usage_type": "call"}, {"api_name": "layout_corrector.config.replace_delay", "line_number": 129, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 129, "usage_type": "name"}, {"api_name": "layout_corrector.config.replace_sound", "line_number": 131, "usage_type": "attribute"}, {"api_name": "layout_corrector.config", "line_number": 131, "usage_type": "name"}]} +{"seq_id": "538668887", "text": "from django.http import HttpResponse\nfrom .BaseCtl import BaseCtl\nfrom django.shortcuts import render, redirect\nfrom ORS.utility.DataValidator import DataValidator\nfrom service.models import Subject\nfrom service.forms import SubjectForm\nfrom service.service.SubjectService import SubjectService\nfrom service.service.CollegeService import CollegeService\nfrom service.service.CourseService import CourseService\n\n\nclass SubjectCtl(BaseCtl):\n\n def preload(self, request):\n self.form['Course_List'] = CourseService().preload(self.form)\n\n def request_to_form(self, requestForm):\n self.form[\"id\"] = requestForm[\"id\"]\n self.form[\"subjectName\"] = requestForm[\"subjectName\"]\n self.form[\"subjectDescription\"] = requestForm[\"subjectDescription\"]\n self.form[\"course_ID\"] = requestForm[\"course_ID\"]\n\n # Populate Form from Model\n def model_to_form(self, obj):\n if (obj == None):\n return\n self.form[\"id\"] = obj.id\n self.form[\"subjectName\"] = obj.subjectName\n self.form[\"subjectDescription\"] = obj.subjectDescription\n\n self.form[\"course_ID\"] = obj.course_ID\n\n # Convert form into module\n def form_to_model(self, obj):\n c = CourseService().get(self.form[\"course_ID\"])\n pk = int(self.form[\"id\"])\n if (pk > 0):\n obj.id = pk\n obj.subjectName = self.form[\"subjectName\"]\n obj.subjectDescription = self.form[\"subjectDescription\"]\n obj.course_ID = self.form[\"course_ID\"]\n obj.courseName = c.courseName\n return obj\n\n # Validate form\n def input_validation(self):\n super().input_validation()\n inputError = self.form[\"inputError\"]\n if (DataValidator.isNull(self.form[\"subjectName\"])):\n inputError[\"subjectName\"] = \" subjectName can not be null\"\n self.form[\"error\"] = True\n else:\n if DataValidator.isaplhacheck(self.form[\"subjectName\"]):\n inputError[\"subjectName\"] = \"Name contains only alphabets\"\n self.form[\"error\"] = True\n\n if (DataValidator.isNull(self.form[\"subjectDescription\"])):\n inputError[\"subjectDescription\"] = \"subjectDescription can not be null\"\n self.form[\"error\"] = True\n\n if (DataValidator.isNull(self.form[\"course_ID\"])):\n inputError[\"course_ID\"] = \"course ID can not be null\"\n self.form[\"error\"] = True\n\n return self.form[\"error\"]\n\n # Display Marksheet page\n\n def display(self, request, params={}):\n if (params[\"id\"] > 0):\n r = self.get_service().get(params[\"id\"])\n self.model_to_form(r)\n res = render(request, self.get_template(), {\"form\": self.form})\n return res\n\n # Submit Marksheet page\n def submit(self, request, params={}):\n if params['id'] > 0:\n pk = params['id']\n dup = self.get_service().get_model().objects.exclude(id=pk).filter(subjectName=self.form[\"subjectName\"])\n if dup.count() > 0:\n self.form[\"error\"] = True\n self.form['message'] = \"Subject Name already exists\"\n res = render(request, self.get_template(), {\"form\": self.form})\n else:\n r = self.form_to_model(Subject())\n self.get_service().save(r)\n self.form[\"id\"] = r.id\n self.form[\"error\"] = False\n self.form[\"message\"] = \"Data is Updated successfully\"\n res = render(request, self.get_template(), {\"form\": self.form})\n return res\n else:\n duplicate = self.get_service().get_model().objects.filter(subjectName=self.form[\"subjectName\"])\n if duplicate.count() > 0:\n self.form[\"error\"] = True\n self.form[\"message\"] = \"Subject is already exists\"\n res = render(request, self.get_template(),\n {\"form\": self.form})\n else:\n r = self.form_to_model(Subject())\n self.get_service().save(r)\n self.form[\"id\"] = r.id\n self.form[\"error\"] = False\n self.form[\"message\"] = \"Data is successfully saved\"\n res = render(request, self.get_template(), {\"form\": self.form})\n return res\n\n # Template html of Student page \n def get_template(self):\n return \"ORS/Subject.html\"\n\n # Service of Student\n\n def get_service(self):\n return SubjectService()\n", "sub_path": "ORS/ctl/SubjectCtl.py", "file_name": "SubjectCtl.py", "file_ext": "py", "file_size_in_byte": 4506, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "BaseCtl.BaseCtl", "line_number": 12, "usage_type": "name"}, {"api_name": "service.service.CourseService.CourseService", "line_number": 15, "usage_type": "call"}, {"api_name": "service.service.CourseService.CourseService", "line_number": 35, "usage_type": "call"}, {"api_name": "ORS.utility.DataValidator.DataValidator.isNull", "line_number": 49, "usage_type": "call"}, {"api_name": "ORS.utility.DataValidator.DataValidator", "line_number": 49, "usage_type": "name"}, {"api_name": "ORS.utility.DataValidator.DataValidator.isaplhacheck", "line_number": 53, "usage_type": "call"}, {"api_name": "ORS.utility.DataValidator.DataValidator", "line_number": 53, "usage_type": "name"}, {"api_name": "ORS.utility.DataValidator.DataValidator.isNull", "line_number": 57, "usage_type": "call"}, {"api_name": "ORS.utility.DataValidator.DataValidator", "line_number": 57, "usage_type": "name"}, {"api_name": "ORS.utility.DataValidator.DataValidator.isNull", "line_number": 61, "usage_type": "call"}, {"api_name": "ORS.utility.DataValidator.DataValidator", "line_number": 61, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 73, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 84, "usage_type": "call"}, {"api_name": "service.models.Subject", "line_number": 86, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 91, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 98, "usage_type": "call"}, {"api_name": "service.models.Subject", "line_number": 101, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 106, "usage_type": "call"}, {"api_name": "service.service.SubjectService.SubjectService", "line_number": 116, "usage_type": "call"}]} +{"seq_id": "628019416", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"category/\", views.Inlet_Category_list.as_view()),\n path(\"category/chart/\", views.get_inlet_category_chart),\n path(\"inlet/\", views.Inlet_List.as_view()),\n path(\"inlet/add/\", views.Inlet_Create.as_view()),\n path(\"inlet/chart/\", views.get_expenses_by_month),\n]", "sub_path": "backend/expense_tracker/Budget/api/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 346, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "463510932", "text": "from flask import Flask, render_template ,request, redirect\nfrom mysqlconnection import connectToMySQL\n\napp=Flask(__name__)\n\nmysql = connectToMySQL('LeadsAndClients')\n\n@app.route('/')\ndef index():\n languages = mysql.query_db(\"SELECT * FROM languages;\")\n return render_template('index.html', languages = languages)\n\n# @app.route('/change', methods=['POST'])\n# def create():\n# query = \"INSERT INTO languages (first_name, last_name, occupation, created_at, updated_at) VALUES (%(first_name)s, %(last_name)s, %(occupation)s, NOW(), NOW());\"\n# data = {\n# 'first_name': request.form['first'],\n# 'last_name': request.form['last'],\n# 'occupation': request.form['occupation']\n# }\n \n# new_friend_id = mysql.query_db(query, data)\n\n# return redirect('/')\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 869, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "mysqlconnection.connectToMySQL", "line_number": 6, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "71779944", "text": "from pymongo import MongoClient\nimport datetime\nfrom datetime import date\n\nclient = MongoClient()\n\ndb = client.site_entity_store\n\n\nin_site = {\n 'id': 3,\n 'name': 'site_three',\n 'location': (55.741895, -55.989308),\n 'created_date': datetime.datetime.now()\n}\n\n\ninit_site = {\n\n \"entity\": {\n \"name\": \"entity_one\",\n \"location\": {\n \"lat\": 37.7815312,\n \"long\": -122.3909155\n },\n \"contents\": \"contents of entity one\",\n \"capacity\": 10000,\n \"created_on\": datetime.datetime.now()},\n\n \"ownership\": {\n \"ownership_id\": \"Owner_0001\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n\n \"transactions\": [\n {\"delivery\": {\n \"owner\": \"Owner_0001\",\n \"contents\": \"contents of entity one\",\n \"quantity\": 100,\n \"transaction_creation\": datetime.datetime.now(),\n \"transaction_completion\": \"some completed date time field here\"\n }}\n\n ],\n\n \"agentData\": [\n {\"data\": \"Similar to the above, with agent mapping to agent collection\"}],\n\n \"capacityData\": [\n {\"data\": \"store last n capacity transactions\"},\n {\"data\": \"depends on transaction action, status\"}\n ]\n}\n\nsecond_site = {\n\n \"entity\": {\n \"name\": \"Site 2\",\n \"location\": {\n \"lat\": 37.7815312,\n \"long\": -122.3909155\n },\n \"contents\": \"S2-00-0002\",\n \"capacity\": 10000,\n \"created_on\": datetime.datetime.now()},\n\n \"ownership\": {\n \"ownership_id\": \"Producer 1024\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n\n \"transactions\": [\n {\"delivery\": {\n \"owner\": \"Producer 1024\",\n \"contents\": \"S2-00-0002\",\n \"quantity\": 100,\n \"transaction_creation\": datetime.datetime.now(),\n \"transaction_completion\": \"\"\n }}\n\n ],\n\n \"agentData\": [\n {\"agent\": \"ericd34n\"}],\n\n \"capacityData\": [\n {\"event\": \"delivery\", \"quantity\": 100},\n {\"event\": \"sensor\", \"quantity\": 112}\n ]\n}\n\n\nthird_site = {\n\n \"entity\": {\n \"name\": \"Site_Three\",\n \"location\": {\n \"lat\": 47.7815312,\n \"long\": -82.3909155\n },\n \"contents\": \"S2-00-0002\",\n \"capacity\": 10000,\n \"created_on\": str(datetime.datetime.today())},\n\n \"ownership\": {\n \"ownership_id\": \"Producer 1024\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n}\n\nfourth_site = {\n\n \"entity\": {\n \"name\": \"Site_Four\",\n \"location\": {\n \"lat\": 47.7815312,\n \"long\": -82.3909155\n },\n \"contents\": \"S4-04-0004\",\n \"capacity\": 10000,\n \"created_on\": str(datetime.datetime.today())},\n\n \"ownership\": {\n \"ownership_id\": \"Producer 1024\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n}\n\n\nfifth_site = {\n\n \"entity\": {\n \"name\": \"Site_Five\",\n \"location\": {\n \"lat\": 47.7815312,\n \"long\": -82.3909155\n },\n \"contents\": \"S5-05-0005\",\n \"capacity\": 10000,\n \"created_on\": str(datetime.datetime.today())},\n\n \"ownership\": {\n \"ownership_id\": \"Producer 1024\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n}\n\n\nsixth_site = {\n\n \"entity\": {\n \"name\": \"Site_Sixth\",\n \"location\": {\n \"lat\": 47.7815312,\n \"long\": -82.3909155\n },\n \"contents\": \"S6-06-0006\",\n \"capacity\": 10000,\n \"created_on\": str(datetime.datetime.today())},\n\n \"ownership\": {\n \"ownership_id\": \"Producer 1024\",\n \"address\": \"5555 Parsec Avenue Nowhere, California\"},\n}\n\nsites = db.sites\n\n# sites.insert_one(init_site)\n#sites.insert_one(fourth_site)\n#sites.insert_one(fifth_site)\n#sites.insert_one(sixth_site)\n\n\n", "sub_path": "initialize_model.py", "file_name": "initialize_model.py", "file_ext": "py", "file_size_in_byte": 3847, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymongo.MongoClient", "line_number": 5, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 101, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 101, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 118, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 136, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 136, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 154, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 154, "usage_type": "attribute"}]} +{"seq_id": "324803095", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nImplementation of Sideways Information Passing graph (builds it from a given\nruleset)\n\"\"\"\n\nimport itertools\nfrom functools import reduce\nfrom hashlib import md5\n\nfrom rdflib import RDF, BNode, Namespace, URIRef, Variable\nfrom rdflib.collection import Collection\nfrom rdflib.graph import Graph\nfrom rdflib.util import first\n\nfrom FuXi import debug\nfrom FuXi.DLP import SKOLEMIZED_CLASS_NS\nfrom FuXi.DLP.Negation import ProperSipOrderWithNegation\nfrom FuXi.Horn.PositiveConditions import And, Exists, SetOperator, Uniterm\n\nfrom .RuleStore import N3Builtin\n\n__all__ = [\n \"BuildNaturalSIP\",\n \"CollectSIPArcVars\",\n \"findFullSip\",\n \"GetArgs\",\n \"getOccurrenceId\",\n \"GetOp\",\n \"GetVariables\",\n \"IncomingSIPArcs\",\n \"InvalidSIPException\",\n \"iterCondition\",\n \"make_md5_digest\",\n \"normalizeTerm\",\n \"RenderSIPCollection\",\n \"SetOp\",\n \"SIPGraphArc\",\n \"SIPRepresentation\",\n \"validSip\",\n]\n\n\ndef make_md5_digest(value):\n return md5(isinstance(value, str) and value.encode(\"utf-8\") or value).hexdigest()\n\n\nMAGIC = Namespace(\"http://doi.acm.org/10.1145/28659.28689#\")\n\n\ndef iterCondition(condition):\n if debug: # pragma: no cover\n print(f\"iterCondition condition={condition}\")\n if isinstance(condition, Exists):\n return iterCondition(condition.formula)\n else:\n return isinstance(condition, SetOperator) and condition or iter([condition])\n\n\ndef normalizeTerm(uri, sipGraph):\n try:\n return sipGraph.qname(uri).split(\":\")[-1]\n except Exception:\n return uri.n3()\n\n\ndef RenderSIPCollection(sipGraph, dot=None):\n try:\n from pydot import Dot, Edge, Node # type: ignore\n except Exception:\n import warnings\n\n warnings.warn(\"Missing pydot library\", ImportWarning)\n if not dot:\n dot = Dot(graph_type=\"digraph\")\n dot.leftNodesLookup = {}\n nodes = {}\n for N, prop, q in sipGraph.query(\n \"SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }\",\n initNs={\"magic\": MAGIC},\n ):\n\n if MAGIC.BoundHeadPredicate in sipGraph.objects(subject=N, predicate=RDF.type):\n NCol = [N]\n else:\n NCol = Collection(sipGraph, N)\n\n if q not in nodes:\n newNode = Node(\n make_md5_digest(q), label=normalizeTerm(q, sipGraph), shape=\"plaintext\"\n )\n nodes[q] = newNode\n dot.add_node(newNode)\n\n bNode = BNode()\n nodeLabel = \", \".join([normalizeTerm(term, sipGraph) for term in NCol])\n edgeLabel = \", \".join(\n [\n var.n3()\n for var in Collection(\n sipGraph, first(sipGraph.objects(prop, MAGIC.bindings))\n )\n ]\n )\n markedEdgeLabel = \"\"\n if nodeLabel in dot.leftNodesLookup:\n bNode, leftNode, markedEdgeLabel = dot.leftNodesLookup[nodeLabel]\n # print(\"\\t\", nodeLabel, edgeLabel,\n # markedEdgeLabel, not edgeLabel == markedEdgeLabel)\n else:\n leftNode = Node(make_md5_digest(bNode), label=nodeLabel, shape=\"plaintext\")\n dot.leftNodesLookup[nodeLabel] = (bNode, leftNode, edgeLabel)\n nodes[bNode] = leftNode\n dot.add_node(leftNode)\n\n if not edgeLabel == markedEdgeLabel:\n edge = Edge(leftNode, nodes[q], label=edgeLabel)\n dot.add_edge(edge)\n return dot\n\n\nclass SIPGraphArc(object):\n \"\"\"\n A `sip` for `r` is a labeled graph that satisfies the following conditions:\n 1. Each node is either a subset or a member of `P(r)` or `{ph}`.\n 2. Each arc is of the form `N -> q`, with label `X`, where `N` is a subset\n of `P(r)` or `{ph}`, `q` is a member of `P(r)` and `X` is a set of\n variables such that\n (i) Each variable of `X` appears in `N`.\n (ii) Each member of `N` is connected to a variable in `X`.\n (iii) For some argument of `q`, all its variables appear in `X`. Further,\n each variable of `X` appears in an argument of `q` that satisfies this\n condition.\n \"\"\"\n\n def __init__(self, left, right, variables, graph=None, headPassing=False):\n self.variables = variables\n self.left = left\n self.right = right\n self.graph = graph is None and Graph() or graph\n self.arc = SKOLEMIZED_CLASS_NS[BNode()]\n self.graph.add((self.arc, RDF.type, MAGIC.SipArc))\n varsCol = Collection(self.graph, BNode())\n [varsCol.append(i) for i in self.variables]\n self.graph.add((self.arc, MAGIC.bindings, varsCol.uri))\n if headPassing:\n self.boundHeadPredicate = True\n self.graph.add((self.left, self.arc, self.right))\n else:\n self.boundHeadPredicate = False\n self.graph.add((self.left, self.arc, self.right))\n\n def __repr__(self):\n \"\"\"Visual of graph arc\"\"\"\n return \"%s - (%s) > %s\" % (self.left, self.variables, self.right)\n\n\ndef CollectSIPArcVars(left, right, phBoundVars):\n \"\"\"docstring for CollectSIPArcVars\"\"\"\n if isinstance(left, list):\n return set(\n reduce(\n lambda x, y: x + y,\n [\n hasattr(t, \"isHead\") and phBoundVars or GetArgs(t, secondOrder=True)\n for t in left\n ],\n )\n ).intersection(GetArgs(right, secondOrder=True))\n else:\n incomingVarsToInclude = (\n phBoundVars and phBoundVars or GetArgs(left, secondOrder=True)\n )\n return set(incomingVarsToInclude).intersection(GetArgs(right, secondOrder=True))\n\n\ndef SetOp(term, value):\n \"\"\"docstring for SetOp\"\"\"\n if isinstance(term, N3Builtin):\n term.uri = value\n elif isinstance(term, Uniterm):\n if term.op == RDF.type:\n term.arg[-1] = value\n else:\n term.op = value\n else:\n raise Exception(f\"SetOp encountered an unprocessable term: {term}\")\n\n\ndef GetOp(term):\n\n # print(f\"GetOp term={term}\")\n \"\"\"docstring for GetOp\"\"\"\n if isinstance(term, N3Builtin):\n return term.uri\n elif isinstance(term, Uniterm):\n return term.op == RDF.type and term.arg[-1] or term.op\n elif isinstance(term, Exists):\n return GetOp(term.formula)\n else:\n # @@DEVOTE FIXME: remove when fixed\n import inspect\n import warnings\n\n warnings.warn(\n f\"GetOp failure called by \"\n f\"{inspect.stack()[1].function} in {inspect.stack()[2].function} \"\n f\"in {inspect.stack()[3].function}\",\n UserWarning,\n )\n\n raise Exception(f\"GetOp encountered unprocessable term {term}.\")\n\n\ndef GetVariables(term, secondOrder=False):\n \"\"\"docstring for GetVariables\"\"\"\n for v in GetArgs(term, secondOrder):\n if isinstance(v, Variable):\n yield v\n\n\ndef GetArgs(term, secondOrder=False):\n \"\"\"docstring for GetArgs\"\"\"\n if isinstance(term, N3Builtin):\n return [term.argument, term.result]\n elif isinstance(term, Uniterm):\n args = []\n if term.op == RDF.type:\n if secondOrder and isinstance(term.arg[-1], (Variable, BNode)):\n args.extend(term.arg)\n else:\n args.append(term.arg[0])\n elif isinstance(term.op, (Variable, BNode)):\n args.append(term.op)\n args.extend(term.arg)\n else:\n args.extend(term.arg)\n return args\n elif isinstance(term, Exists):\n return GetArgs(term.formula, secondOrder)\n else:\n raise Exception(\"Unprocessable term: %s\" % term)\n\n\ndef IncomingSIPArcs(sip, predOcc):\n \"\"\"docstring for IncomingSIPArcs\"\"\"\n for s, p, o in sip.triples((None, None, predOcc)):\n if (p, RDF.type, MAGIC.SipArc) in sip:\n if (s, RDF.type, MAGIC.BoundHeadPredicate) in sip:\n yield [s], Collection(sip, first(sip.objects(p, MAGIC.bindings)))\n else:\n yield Collection(sip, s), Collection(\n sip, first(sip.objects(p, MAGIC.bindings))\n )\n\n\ndef validSip(sipGraph):\n \"\"\"docstring for validSip\"\"\"\n if not len(sipGraph):\n return False\n for arc in sipGraph.query(\n \"SELECT ?arc { ?arc m:bindings ?bindings OPTIONAL\"\n + \"{ ?bindings rdf:first ?val } FILTER(!BOUND(?val)) }\",\n initNs={\"m\": MAGIC},\n ):\n return False\n return True\n\n\ndef getOccurrenceId(uniterm, lookup={}):\n \"\"\"docstring for SetOp\"\"\"\n pO = URIRef(GetOp(uniterm) + \"_\" + \"_\".join(GetArgs(uniterm)))\n lookup[pO] = GetOp(uniterm)\n return pO\n\n\ndef findFullSip(tpl, right):\n \"\"\"docstring for findFullSip\"\"\"\n (rt, vars) = tpl\n\n right = right.formulae if isinstance(right, And) else right\n\n if not vars:\n if len(rt) == 1:\n vars = GetArgs(rt[0], secondOrder=True)\n else:\n vars = reduce(\n lambda l, r: [\n i\n for i in GetArgs(l, secondOrder=True) + GetArgs(r, secondOrder=True)\n if isinstance(i, (Variable, BNode))\n ],\n rt,\n )\n if len(right) == 1:\n if set(GetArgs(right[0], secondOrder=True)).intersection(vars):\n # Valid End of recursion, return full SIP order\n yield rt + right\n else:\n # for every combination of left and right, trigger recursive call\n for item in right:\n _vars = set(\n [\n v\n for v in GetArgs(item, secondOrder=True)\n if isinstance(v, (Variable, BNode))\n ]\n )\n _inVars = set([v for v in vars])\n if _vars.intersection(vars):\n # There is an incoming arc, continue processing inductively on\n # the rest of right\n _inVars.update(_vars.difference(vars))\n for sipOrder in findFullSip(\n (rt + [item], _inVars), [i for i in right if i != item]\n ):\n yield sipOrder\n\n\nclass InvalidSIPException(Exception):\n def __init__(self, msg=None):\n super(InvalidSIPException, self).__init__(msg)\n\n\ndef BuildNaturalSIP(\n clause,\n derivedPreds,\n adornedHead,\n hybridPreds2Replace=None,\n ignoreUnboundDPreds=False,\n):\n \"\"\"\n Natural SIP:\n\n Informally, for a rule of a program, a sip represents a decision about the\n order in which the predicates of the rule will be evaluated, and how\n values for variables are passed from predicates to other predicates during\n the evaluation\n\n >>> from functools import reduce\n >>> from io import StringIO\n >>> from FuXi.Rete.RuleStore import SetupRuleStore\n >>> from FuXi.Rete import PROGRAM2\n >>> ruleStore, ruleGraph = SetupRuleStore(StringIO(PROGRAM2))\n >>> ruleStore._finalize()\n >>> fg = Graph().parse(data=PROGRAM2, format='n3')\n >>> from FuXi.Horn.HornRules import Ruleset\n >>> rs = Ruleset(n3Rules=ruleGraph.store.rules, nsMapping=ruleGraph.store.nsMgr)\n >>> for rule in rs: print(rule) # doctest: +SKIP\n Forall ?X ?Y ( ex:sg(?X ?Y) :- ex:flat(?X ?Y) )\n Forall ?Z3 ?Z1 ?Z4 ?Y ?X ?Z2 ( ex:sg(?X ?Y) :- And( ex:up(?X ?Z1) ex:sg(?Z1 ?Z2) ex:flat(?Z2 ?Z3) ex:sg(?Z3 ?Z4) ex:down(?Z4 ?Y) ) )\n >>> sip = BuildNaturalSIP(list(rs)[-1], [], None) # doctest: +SKIP\n >>> for N, x in IncomingSIPArcs(sip, MAGIC.sg): print(N.n3(), x.n3()) # doctest: +SKIP\n ( ) ( ?Z3 )\n ( ) ( ?Z1 )\n\n >>> sip = BuildNaturalSIP(list(rs)[-1], [MAGIC.sg], None) # doctest: +SKIP\n >>> list(sip.query('SELECT ?q { ?prop a magic:SipArc . [] ?prop ?q . }', initNs={'magic':MAGIC})) # doctest: +SKIP\n [rdflib.term.URIRef('http://doi.acm.org/10.1145/28659.28689#sg'), rdflib.term.URIRef('http://doi.acm.org/10.1145/28659.28689#sg')]\n \"\"\"\n # @@DEVNOTE ground under repair\n # assert adornedHead is not None\n\n # @@DEVOTE FIXME: remove when fixed\n if adornedHead is None:\n import inspect\n import warnings\n\n warnings.warn(\n f\"adornedHead {clause} (a {clause.__class__.__name__}) is None\\n\"\n f\"{inspect.stack()[1].function} in {inspect.stack()[2].function} \"\n f\"in {inspect.stack()[3].function} in {inspect.stack()[4].function}\",\n UserWarning,\n )\n\n from FuXi.Rete.Magic import AdornedUniTerm\n\n occurLookup = {}\n boundHead = isinstance(adornedHead, AdornedUniTerm) and \"b\" in adornedHead.adornment\n phBoundVars = (\n list(adornedHead.getDistinguishedVariables(varsOnly=True))\n if adornedHead is not None\n else []\n )\n assert isinstance(clause.head, Uniterm), \"Only one literal in the head.\"\n\n def collectSip(left, right):\n if isinstance(left, list):\n vars = CollectSIPArcVars(left, right, phBoundVars)\n if not vars and ignoreUnboundDPreds:\n raise InvalidSIPException(\"No bound variables for %s\" % right)\n leftList = Collection(sipGraph, None)\n left = list(set(left))\n [leftList.append(i) for i in [GetOp(ii) for ii in left]]\n left.append(right)\n # arc = SIPGraphArc(\n # leftList.uri, getOccurrenceId(\n # right, occurLookup), vars, sipGraph\n # )\n return left\n else:\n left.isHead = True\n vars = CollectSIPArcVars(left, right, phBoundVars)\n if not vars and ignoreUnboundDPreds:\n raise InvalidSIPException(\"No bound variables for %s\" % right)\n ph = GetOp(left)\n # q = getOccurrenceId(right, occurLookup)\n if boundHead:\n # arc = SIPGraphArc(\n # ph, q, vars, sipGraph, headPassing=boundHead\n # )\n sipGraph.add((ph, RDF.type, MAGIC.BoundHeadPredicate))\n rt = [left, right]\n else:\n rt = [right]\n return rt\n\n sipGraph = Graph()\n if isinstance(clause.body, And):\n if ignoreUnboundDPreds:\n foundSip = False\n sips = findFullSip(([clause.head], None), clause.body)\n while not foundSip:\n try:\n sip = next(sips)\n except StopIteration:\n # Throw SIP exception if sip isn't found (probably means\n # query + rules combination is 'malformed')\n raise InvalidSIPException(\n \"Unable to find a sip for %s (%s)\" % (clause, adornedHead)\n )\n try:\n reduce(collectSip, iterCondition(And(sip)))\n foundSip = True\n bodyOrder = sip\n except InvalidSIPException:\n foundSip = False\n else:\n if first(\n [i for i in clause.body if isinstance(i, Uniterm) and i.naf or False]\n ):\n # There are negative literals in body, ensure\n # the given sip order puts negated literals at the end\n bodyOrder = first(\n list(\n filter(\n ProperSipOrderWithNegation,\n findFullSip(([clause.head], None), clause.body),\n )\n )\n )\n else:\n bodyOrder = first(findFullSip(([clause.head], None), clause.body))\n assert bodyOrder, \"Couldn't find a valid SIP for %s\" % clause\n reduce(collectSip, iterCondition(And(bodyOrder)))\n sipGraph.sipOrder = And(bodyOrder[1:])\n # assert validSip(sipGraph), sipGraph.serialize(format='n3')\n else:\n if boundHead:\n reduce(\n collectSip,\n itertools.chain(iterCondition(clause.head), iterCondition(clause.body)),\n )\n sipGraph.sipOrder = clause.body\n if derivedPreds:\n # We therefore generalize our notation to allow\n # more succinct representation of sips, in which only arcs entering\n # derived predicates are represented.\n arcsToRemove = []\n collectionsToClear = []\n for N, prop, q in sipGraph.query(\n \"SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }\",\n initNs={\"magic\": MAGIC},\n ):\n if occurLookup[q] not in derivedPreds and (\n occurLookup[q] not in hybridPreds2Replace\n if hybridPreds2Replace\n else False\n ):\n arcsToRemove.extend([(N, prop, q), (prop, None, None)])\n collectionsToClear.append(Collection(sipGraph, N))\n # clear bindings collection as well\n bindingsColBNode = first(sipGraph.objects(prop, MAGIC.bindings))\n collectionsToClear.append(Collection(sipGraph, bindingsColBNode))\n for removeSts in arcsToRemove:\n sipGraph.remove(removeSts)\n for col in collectionsToClear:\n col.clear()\n return sipGraph\n\n\ndef SIPRepresentation(sipGraph):\n rt = []\n for N, prop, q in sipGraph.query(\n \"SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }\",\n initNs={\"magic\": MAGIC},\n ):\n if MAGIC.BoundHeadPredicate in sipGraph.objects(subject=N, predicate=RDF.type):\n NCol = [N]\n else:\n NCol = Collection(sipGraph, N)\n rt.append(\n \"{ %s } -> %s %s\"\n % (\n \", \".join([normalizeTerm(term, sipGraph) for term in NCol]),\n \", \".join(\n [\n var.n3()\n for var in Collection(\n sipGraph, first(sipGraph.objects(prop, MAGIC.bindings))\n )\n ]\n ),\n normalizeTerm(q, sipGraph),\n )\n )\n return rt\n", "sub_path": "FuXi/Rete/SidewaysInformationPassing.py", "file_name": "SidewaysInformationPassing.py", "file_ext": "py", "file_size_in_byte": 18195, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "hashlib.md5", "line_number": 45, "usage_type": "call"}, {"api_name": "rdflib.Namespace", "line_number": 48, "usage_type": "call"}, {"api_name": "FuXi.debug", "line_number": 52, "usage_type": "name"}, {"api_name": "FuXi.Horn.PositiveConditions.Exists", "line_number": 54, "usage_type": "argument"}, {"api_name": "FuXi.Horn.PositiveConditions.SetOperator", "line_number": 57, "usage_type": "argument"}, {"api_name": "warnings.warn", "line_number": 73, "usage_type": "call"}, {"api_name": "pydot.Dot", "line_number": 75, "usage_type": "call"}, {"api_name": "rdflib.RDF.type", "line_number": 83, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 83, "usage_type": "name"}, {"api_name": "rdflib.collection.Collection", "line_number": 86, "usage_type": "call"}, {"api_name": "pydot.Node", "line_number": 89, "usage_type": "call"}, {"api_name": "rdflib.BNode", "line_number": 95, "usage_type": "call"}, {"api_name": "rdflib.collection.Collection", "line_number": 100, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 101, "usage_type": "call"}, {"api_name": "pydot.Node", "line_number": 111, "usage_type": "call"}, {"api_name": "pydot.Edge", "line_number": 117, "usage_type": "call"}, {"api_name": "rdflib.graph.Graph", "line_number": 140, "usage_type": "call"}, {"api_name": "FuXi.DLP.SKOLEMIZED_CLASS_NS", "line_number": 141, "usage_type": "name"}, {"api_name": "rdflib.BNode", "line_number": 141, "usage_type": "call"}, {"api_name": "rdflib.RDF.type", "line_number": 142, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 142, "usage_type": "name"}, {"api_name": "rdflib.collection.Collection", "line_number": 143, "usage_type": "call"}, {"api_name": "rdflib.BNode", "line_number": 143, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 162, "usage_type": "call"}, {"api_name": "RuleStore.N3Builtin", "line_number": 179, "usage_type": "argument"}, {"api_name": "FuXi.Horn.PositiveConditions.Uniterm", "line_number": 181, "usage_type": "argument"}, {"api_name": "rdflib.RDF.type", "line_number": 182, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 182, "usage_type": "name"}, {"api_name": "RuleStore.N3Builtin", "line_number": 194, "usage_type": "argument"}, {"api_name": "FuXi.Horn.PositiveConditions.Uniterm", "line_number": 196, "usage_type": "argument"}, {"api_name": "rdflib.RDF.type", "line_number": 197, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 197, "usage_type": "name"}, {"api_name": "FuXi.Horn.PositiveConditions.Exists", "line_number": 198, "usage_type": "argument"}, {"api_name": "warnings.warn", "line_number": 205, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 207, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 208, "usage_type": "call"}, {"api_name": "rdflib.Variable", "line_number": 218, "usage_type": "argument"}, {"api_name": "RuleStore.N3Builtin", "line_number": 224, "usage_type": "argument"}, {"api_name": "FuXi.Horn.PositiveConditions.Uniterm", "line_number": 226, "usage_type": "argument"}, {"api_name": "rdflib.RDF.type", "line_number": 228, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 228, "usage_type": "name"}, {"api_name": "rdflib.Variable", "line_number": 229, "usage_type": "name"}, {"api_name": "rdflib.BNode", "line_number": 229, "usage_type": "name"}, {"api_name": "rdflib.Variable", "line_number": 233, "usage_type": "name"}, {"api_name": "rdflib.BNode", "line_number": 233, "usage_type": "name"}, {"api_name": "FuXi.Horn.PositiveConditions.Exists", "line_number": 239, "usage_type": "argument"}, {"api_name": "rdflib.RDF.type", "line_number": 248, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 248, "usage_type": "name"}, {"api_name": "rdflib.RDF.type", "line_number": 249, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 249, "usage_type": "name"}, {"api_name": "rdflib.collection.Collection", "line_number": 250, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 250, "usage_type": "call"}, {"api_name": "rdflib.collection.Collection", "line_number": 252, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 253, "usage_type": "call"}, {"api_name": "rdflib.URIRef", "line_number": 272, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.And", "line_number": 281, "usage_type": "argument"}, {"api_name": "functools.reduce", "line_number": 287, "usage_type": "call"}, {"api_name": "rdflib.Variable", "line_number": 291, "usage_type": "name"}, {"api_name": "rdflib.BNode", "line_number": 291, "usage_type": "name"}, {"api_name": "rdflib.Variable", "line_number": 306, "usage_type": "name"}, {"api_name": "rdflib.BNode", "line_number": 306, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 369, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 371, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 372, "usage_type": "call"}, {"api_name": "FuXi.Rete.Magic.AdornedUniTerm", "line_number": 379, "usage_type": "argument"}, {"api_name": "FuXi.Horn.PositiveConditions.Uniterm", "line_number": 385, "usage_type": "argument"}, {"api_name": "rdflib.collection.Collection", "line_number": 392, "usage_type": "call"}, {"api_name": "rdflib.RDF.type", "line_number": 412, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 412, "usage_type": "name"}, {"api_name": "rdflib.graph.Graph", "line_number": 418, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.And", "line_number": 419, "usage_type": "argument"}, {"api_name": "functools.reduce", "line_number": 433, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.And", "line_number": 433, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 439, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.Uniterm", "line_number": 440, "usage_type": "argument"}, {"api_name": "rdflib.util.first", "line_number": 444, "usage_type": "call"}, {"api_name": "FuXi.DLP.Negation.ProperSipOrderWithNegation", "line_number": 447, "usage_type": "argument"}, {"api_name": "rdflib.util.first", "line_number": 453, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 455, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.And", "line_number": 455, "usage_type": "call"}, {"api_name": "FuXi.Horn.PositiveConditions.And", "line_number": 456, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 460, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 462, "usage_type": "call"}, {"api_name": "rdflib.collection.Collection", "line_number": 481, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 483, "usage_type": "call"}, {"api_name": "rdflib.collection.Collection", "line_number": 484, "usage_type": "call"}, {"api_name": "rdflib.RDF.type", "line_number": 498, "usage_type": "attribute"}, {"api_name": "rdflib.RDF", "line_number": 498, "usage_type": "name"}, {"api_name": "rdflib.collection.Collection", "line_number": 501, "usage_type": "call"}, {"api_name": "rdflib.collection.Collection", "line_number": 509, "usage_type": "call"}, {"api_name": "rdflib.util.first", "line_number": 510, "usage_type": "call"}]} +{"seq_id": "284182642", "text": "#Import Libraries and create a makeshift loading screen\nimport os\nprint(\"please wait For a few moments\")\nfrom textblob import TextBlob\n\n#clear terminal of loading screen\nos.system('clear')\n\n#User Input for rating\nRating=raw_input(\"what is your review:\")\n#convert to TextBlob String\nrating= TextBlob(Rating)\n#covert out of 100 to out of 5\nUser_rating= rating.sentiment.polarity*5\n#print out rating\nprint (\"expected User rating:\"+str(User_rating)+\"/5\")\n", "sub_path": "Linux.py", "file_name": "Linux.py", "file_ext": "py", "file_size_in_byte": 451, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.system", "line_number": 7, "usage_type": "call"}, {"api_name": "textblob.TextBlob", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "455208889", "text": "from tkinter import N\nimport requests\nimport json\n\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n\n@csrf_exempt\ndef testAPI(request):\n if (request.method == 'GET'):\n url = 'https://api.fpt.ai/hmi/tts/v5'\n\n payload = '342424324323424'\n headers = {\n 'api-key': 'cnnvqSxKkxOHXwJvkff681tgU7O8Gi0B',\n 'speed': '',\n 'voice': 'banmai'\n }\n\n response = requests.request('POST', url, data=payload.encode('utf-8'), headers=headers)\n\n rs = response.text\n\n return JsonResponse(rs, safe=False)\n", "sub_path": "tdai/api/views/view_testcallapi.py", "file_name": "view_testcallapi.py", "file_ext": "py", "file_size_in_byte": 610, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.request", "line_number": 22, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 26, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.csrf_exempt", "line_number": 10, "usage_type": "name"}]} +{"seq_id": "446957147", "text": "\"\"\"\nClasses and utilities that represents Xena XenaManager-2G port.\n\n:author: yoram@ignissoft.com\n\"\"\"\n\nimport os\nfrom collections import OrderedDict\nfrom enum import Enum\n\nfrom trafficgenerator.tgn_utils import TgnError\n\nfrom xenamanager.api.XenaSocket import XenaCommandException\nfrom xenamanager.xena_object import XenaObject, XenaObject21\nfrom xenamanager.xena_stream import XenaStream, XenaStreamState\n\n\nclass XenaCaptureBufferType(Enum):\n raw = 0\n text = 1\n pcap = 2\n\n\nclass XenaPort(XenaObject):\n \"\"\" Represents Xena port. \"\"\"\n\n info_config_commands = ['p_info', 'p_config', 'p_receivesync', 'ps_indices', 'pr_tplds']\n\n stats_captions = {'pr_pfcstats': ['total', 'CoS 0', 'CoS 1', 'CoS 2', 'CoS 3', 'CoS 4', 'CoS 5', 'CoS 6', 'CoS 7'],\n 'pr_total': ['bps', 'pps', 'bytes', 'packets'],\n 'pr_notpld': ['bps', 'pps', 'bytes', 'packets'],\n 'pr_extra': ['fcserrors', 'pauseframes', 'arprequests', 'arpreplies', 'pingrequests',\n 'pingreplies', 'gapcount', 'gapduration'],\n 'pt_total': ['bps', 'pps', 'bytes', 'packets'],\n 'pt_extra': ['arprequests', 'arpreplies', 'pingrequests', 'pingreplies', 'injectedfcs',\n 'injectedseq', 'injectedmis', 'injectedint', 'injectedtid', 'training'],\n 'pt_notpld': ['bps', 'pps', 'bytes', 'packets']}\n\n def __init__(self, parent, index):\n \"\"\"\n :param parent: parent module or chassis.\n :param index: port index in format module/port (both 0 based)\n \"\"\"\n\n objRef = '{}/{}'.format('/'.join(parent.ref.split('/')[:2]), index)\n super(self.__class__, self).__init__(objType='port', index=index, parent=parent, objRef=objRef)\n self._data['name'] = '{}/{}'.format(parent.name, index)\n self.p_info = None\n\n def inventory(self):\n self.p_info = self.get_attributes()\n\n def reserve(self, force=False):\n \"\"\" Reserve port.\n\n XenaManager-2G -> Reserve/Relinquish Port.\n\n :param force: True - take forcefully, False - fail if port is reserved by other user\n \"\"\"\n\n p_reservation = self.get_attribute('p_reservation')\n if p_reservation == 'RESERVED_BY_YOU':\n return\n elif p_reservation == 'RESERVED_BY_OTHER' and not force:\n raise TgnError('Port {} reserved by {}'.format(self, self.get_attribute('p_reservedby')))\n self.relinquish()\n self.send_command('p_reservation', 'reserve')\n\n def relinquish(self):\n if self.get_attribute('p_reservation') != 'RELEASED':\n self.send_command('p_reservation relinquish')\n\n def release(self):\n if self.get_attribute('p_reservation') == 'RESERVED_BY_YOU':\n self.send_command('p_reservation release')\n\n def reset(self):\n \"\"\" Reset port-level parameters to standard values, and delete all streams, filters, capture,\n and dataset definitions.\n \"\"\"\n self.objects = OrderedDict()\n return self.send_command('p_reset')\n\n def wait_for_up(self, timeout=40):\n self.wait_for_states('p_receivesync', timeout, 'IN_SYNC')\n\n #\n # Configurations.\n #\n\n def load_config(self, config_file_name):\n \"\"\" Load configuration file from xpc file.\n\n :param config_file_name: full path to the configuration file.\n \"\"\"\n\n with open(config_file_name) as f:\n commands = f.read().splitlines()\n\n for command in commands:\n if not command.startswith(';'):\n try:\n self.send_command(command)\n except XenaCommandException as e:\n self.logger.warning(str(e))\n\n def save_config(self, config_file_name):\n \"\"\" Save configuration file to xpc file.\n\n :param config_file_name: full path to the configuration file.\n \"\"\"\n\n with open(config_file_name, 'w+') as f:\n f.write('P_RESET\\n')\n for line in self.send_command_return_multilines('p_fullconfig', '?'):\n f.write(line.split(' ', 1)[1].lstrip())\n\n def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled):\n \"\"\" Add stream.\n\n :param name: stream description.\n :param tpld_id: TPLD ID. If None the a unique value will be set.\n :param state: new stream state.\n :type state: xenamanager.xena_stream.XenaStreamState\n :return: newly created stream.\n :rtype: xenamanager.xena_stream.XenaStream\n \"\"\"\n\n stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name)\n stream._create()\n tpld_id = tpld_id if tpld_id else XenaStream.next_tpld_id\n stream.set_attributes(ps_comment='\"{}\"'.format(stream.name), ps_tpldid=tpld_id)\n XenaStream.next_tpld_id = max(XenaStream.next_tpld_id + 1, tpld_id + 1)\n stream.set_state(state)\n return stream\n\n def remove_stream(self, index):\n \"\"\" Remove stream.\n\n :param index: index of stream to remove.\n \"\"\"\n\n self.streams[index].del_object_from_parent()\n\n #\n # Operations.\n #\n\n def start_traffic(self, blocking=False):\n \"\"\" Start port traffic.\n\n Port -> Start Traffic\n\n :param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.\n \"\"\"\n self.session.start_traffic(blocking, self)\n\n def stop_traffic(self):\n \"\"\" Stop port traffic.\n\n Port -> Stop Traffic\n \"\"\"\n self.session.stop_traffic(self)\n\n def start_capture(self):\n \"\"\" Start capture on port.\n\n Capture -> Start Capture\n \"\"\"\n self.del_objects_by_type('capture')\n self.send_command('p_capture', 'on')\n\n def stop_capture(self):\n \"\"\" Stop capture on port.\n\n Capture -> Stop Capture\n \"\"\"\n self.send_command('p_capture', 'off')\n\n #\n # Statistics.\n #\n\n def clear_stats(self):\n \"\"\" Clear att TX and RX statistics counter.\n\n Port Statistics -> Clear TX Counters, Clear RX Counters\n \"\"\"\n self.send_command('pt_clear')\n self.send_command('pr_clear')\n\n def read_port_stats(self):\n \"\"\"\n :return: dictionary {group name {stat name: value}}.\n Sea XenaPort.stats_captions.\n \"\"\"\n\n stats_with_captions = OrderedDict()\n for stat_name in self.stats_captions.keys():\n stats_with_captions[stat_name] = self.read_stat(self.stats_captions[stat_name], stat_name)\n return stats_with_captions\n\n def read_stream_stats(self):\n \"\"\"\n :return: dictionary {stream index {stat name: value}}.\n Sea XenaStream.stats_captions.\n \"\"\"\n stream_stats = OrderedDict()\n for stream in self.streams.values():\n stream_stats[stream] = stream.read_stats()\n return stream_stats\n\n def read_tpld_stats(self):\n \"\"\"\n :return: dictionary {tpld index {group name {stat name: value}}}.\n Sea XenaTpld.stats_captions.\n \"\"\"\n payloads_stats = OrderedDict()\n for tpld in self.tplds.values():\n payloads_stats[tpld] = tpld.read_stats()\n return payloads_stats\n\n #\n # Properties.\n #\n\n @property\n def streams(self):\n \"\"\"\n :return: dictionary {id: object} of all streams.\n :rtype: dict of (int, xenamanager.xena_stream.XenaStream)\n \"\"\"\n\n if not self.get_objects_by_type('stream'):\n tpld_ids = []\n for index in self.get_attribute('ps_indices').split():\n stream = XenaStream(parent=self, index='{}/{}'.format(self.index, index))\n tpld_ids.append(stream.get_attribute('ps_tpldid'))\n if tpld_ids:\n XenaStream.next_tpld_id = max([XenaStream.next_tpld_id] + [int(t) for t in tpld_ids]) + 1\n return {s.id: s for s in self.get_objects_by_type('stream')}\n\n @property\n def tplds(self):\n \"\"\"\n :return: dictionary {id: object} of all current tplds.\n :rtype: dict of (int, xenamanager.xena_port.XenaTpld)\n \"\"\"\n\n # As TPLDs are dynamic we must re-read them each time from the port.\n self.parent.del_objects_by_type('tpld')\n for tpld in self.get_attribute('pr_tplds').split():\n XenaTpld(parent=self, index='{}/{}'.format(self.index, tpld))\n return {t.id: t for t in self.get_objects_by_type('tpld')}\n\n @property\n def capture(self):\n \"\"\"\n :return: capture object.\n :rtype: XenaCapture\n \"\"\"\n\n if not self.get_object_by_type('capture'):\n XenaCapture(parent=self)\n return self.get_object_by_type('capture')\n\n\nclass XenaTpld(XenaObject21):\n\n stats_captions = {'pr_tpldtraffic': ['bps', 'pps', 'byt', 'pac'],\n 'pr_tplderrors': ['dummy', 'seq', 'mis', 'pld'],\n 'pr_tpldlatency': ['min', 'avg', 'max', 'avg1sec', 'min1sec', 'max1sec'],\n 'pr_tpldjitter': ['min', 'avg', 'max', 'avg1sec', 'min1sec', 'max1sec']}\n\n def __init__(self, parent, index):\n \"\"\"\n :param parent: parent port object.\n :param index: TPLD index in format module/port/tpld.\n \"\"\"\n super(self.__class__, self).__init__(objType='tpld', index=index, parent=parent)\n\n def read_stats(self):\n \"\"\"\n :return: dictionary {group name {stat name: value}}.\n Sea XenaTpld.stats_captions.\n \"\"\"\n\n stats_with_captions = OrderedDict()\n for stat_name in self.stats_captions.keys():\n stats_with_captions[stat_name] = self.read_stat(self.stats_captions[stat_name], stat_name)\n return stats_with_captions\n\n\nclass XenaCapture(XenaObject):\n \"\"\" Represents capture parameters, correspond to the Capture panel of the XenaManager, and deal with configuration\n of the capture criteria and inspection of the captured data from a port.\n \"\"\"\n\n info_config_commands = ['pc_fullconfig']\n stats_captions = ['status', 'packets', 'starttime']\n\n def __init__(self, parent):\n objRef = '{}/capture'.format(parent.ref)\n super(self.__class__, self).__init__(objType='capture', index=parent.index, parent=parent, objRef=objRef)\n\n def read_stats(self):\n \"\"\"\n :return: dictionary {stat name: value}.\n Sea XenaCapture.stats_captions.\n \"\"\"\n return self.read_stat(XenaCapture.stats_captions, 'pc_stats')\n\n def get_packets(self, from_index=0, to_index=None, cap_type=XenaCaptureBufferType.text,\n file_name=None, tshark=None):\n \"\"\" Get captured packets from chassis.\n\n :param from_index: index of first packet to read.\n :param to_index: index of last packet to read. If None - read all packets.\n :param cap_type: returned capture format. If pcap then file name and tshark must be provided.\n :param file_name: if specified, capture will be saved in file.\n :param tshark: tshark object for pcap type only.\n :type: xenamanager.xena_tshark.Tshark\n :return: list of requested packets, None for pcap type.\n \"\"\"\n\n to_index = to_index if to_index else len(self.packets)\n\n raw_packets = []\n for index in range(from_index, to_index):\n raw_packets.append(self.packets[index].get_attribute('pc_packet').split('0x')[1])\n\n if cap_type == XenaCaptureBufferType.raw:\n self._save_captue(file_name, raw_packets)\n return raw_packets\n\n text_packets = []\n for raw_packet in raw_packets:\n text_packet = ''\n for c, b in zip(range(len(raw_packet)), raw_packet):\n if c % 32 == 0:\n text_packet += '\\n{:06x} '.format(int(c / 2))\n elif c % 2 == 0:\n text_packet += ' '\n text_packet += b\n text_packets.append(text_packet)\n\n if cap_type == XenaCaptureBufferType.text:\n self._save_captue(file_name, text_packets)\n return text_packets\n\n temp_file_name = file_name + '_'\n self._save_captue(temp_file_name, text_packets)\n tshark.text_to_pcap(temp_file_name, file_name)\n os.remove(temp_file_name)\n\n #\n # Properties.\n #\n\n @property\n def packets(self):\n \"\"\"\n :return: dictionary {id: object} of all packets.\n :rtype: dict of (int, xenamanager.xena_port.XenaCapturePacket)\n \"\"\"\n\n if not self.get_object_by_type('cappacket'):\n for index in range(0, self.read_stats()['packets']):\n XenaCapturePacket(parent=self, index='{}/{}'.format(self.index, index))\n return {p.id: p for p in self.get_objects_by_type('cappacket')}\n\n #\n # Private methods.\n #\n\n def _save_captue(self, file_name, packets):\n if file_name:\n with open(file_name, 'w+') as f:\n for packet in packets:\n f.write(packet)\n\n\nclass XenaCapturePacket(XenaObject21):\n\n info_config_commands = ['pc_info']\n\n def __init__(self, parent, index):\n objRef = '{}/{}'.format(parent.ref, index.split('/')[-1])\n super(self.__class__, self).__init__(objType='cappacket', parent=parent, index=index, objRef=objRef)\n", "sub_path": "xenamanager/xena_port.py", "file_name": "xena_port.py", "file_ext": "py", "file_size_in_byte": 13386, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "enum.Enum", "line_number": 18, "usage_type": "name"}, {"api_name": "xenamanager.xena_object.XenaObject", "line_number": 24, "usage_type": "name"}, {"api_name": "trafficgenerator.tgn_utils.TgnError", "line_number": 65, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 81, "usage_type": "call"}, {"api_name": "xenamanager.api.XenaSocket.XenaCommandException", "line_number": 104, "usage_type": "name"}, {"api_name": "xenamanager.xena_stream.XenaStreamState.enabled", "line_number": 118, "usage_type": "attribute"}, {"api_name": "xenamanager.xena_stream.XenaStreamState", "line_number": 118, "usage_type": "name"}, {"api_name": "xenamanager.xena_stream.XenaStream", "line_number": 129, "usage_type": "call"}, {"api_name": "xenamanager.xena_stream.XenaStream.next_tpld_id", "line_number": 131, "usage_type": "attribute"}, {"api_name": "xenamanager.xena_stream.XenaStream", "line_number": 131, "usage_type": "name"}, {"api_name": "xenamanager.xena_stream.XenaStream.next_tpld_id", "line_number": 133, "usage_type": "attribute"}, {"api_name": "xenamanager.xena_stream.XenaStream", "line_number": 133, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 198, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 208, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 218, "usage_type": "call"}, {"api_name": "xenamanager.xena_stream.XenaStream", "line_number": 237, "usage_type": "call"}, {"api_name": "xenamanager.xena_stream.XenaStream.next_tpld_id", "line_number": 240, "usage_type": "attribute"}, {"api_name": "xenamanager.xena_stream.XenaStream", "line_number": 240, "usage_type": "name"}, {"api_name": "xenamanager.xena_object.XenaObject21", "line_number": 268, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 288, "usage_type": "call"}, {"api_name": "xenamanager.xena_object.XenaObject", "line_number": 294, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 354, "usage_type": "call"}, {"api_name": "xenamanager.xena_object.XenaObject21", "line_number": 383, "usage_type": "name"}]} +{"seq_id": "390586903", "text": "\"\"\"\n ASL project - fall 2017\n\n author: Jovan Nikolic\n\n Processes json log file produced by memtiers\n\"\"\"\n\nimport json\nimport numpy as np\nimport csv\n\nplots_base_name = \"plots/baseline_nomidd_1server/\"\nfile_base_name = \"data/baseline_nomidd_1server/\"\njson_file_base_name = file_base_name + \"json_output_file_\"\nthroughput_literal = \"Ops/sec\"\nhits_literal = \"Hits/sec\"\nlatency_literal = \"Latency\"\n\n# a = [\"SET\"]\n# b = [\"Sets\"]\n# c = [\"_writeonly\"]\n# d = [\"WRITE-ONLY\"]\n#\na = [\"GET\", \"SET\"]\nb = [\"Gets\", \"Sets\"]\nc = [\"_readonly\", \"_writeonly\"]\nd = [\"READ-ONLY\", \"WRITE-ONLY\"]\n\n# experimental setup\nmemtier_vms = 3\nmemtier_instances_per_vm = 1\nnum_threads_per_instance = 2\nclients_per_thread = [1, 5, 8, 14, 19, 23, 28, 32, 42, 52, 64]\nrepetitions = 3\n\ndata = {} # > > >\n\n\ndef make_filename(cpt, rep, readonly, vm):\n if readonly:\n c = \"_S0-G1_\"\n else:\n c = \"_S1-G0_\"\n return json_file_base_name + \"cpt\" + str(cpt) + \"_rep\" + str(rep) + c + \"vm\" + str(vm) + \".json\"\n\n\ndef read_jsons(readonly):\n bigger_dict = {}\n for cpt in clients_per_thread:\n big_dict = {}\n for rep in range(1, repetitions + 1):\n small_dict = {}\n for vm in range(1, memtier_vms + 1):\n with open(make_filename(cpt, rep, readonly, vm)) as json_file:\n json_data = json.load(json_file)\n json_file.close()\n small_dict[vm] = json_data\n big_dict[rep] = small_dict\n bigger_dict[cpt] = big_dict\n if readonly:\n data['GET'] = bigger_dict\n else:\n data['SET'] = bigger_dict\n\n\ndef print_csv(full_header, full_data, path):\n with open(path, 'w') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=full_header)\n writer.writeheader()\n\n for row in range(len(full_data[0])):\n one_row = {}\n for column in range(len(full_header)):\n one_row[full_header[column]] = full_data[column][row]\n writer.writerow(one_row)\n\n csv_file.close()\n\n\ndef assemble_and_print():\n full_data = []\n total_num_clients = memtier_vms * memtier_instances_per_vm * num_threads_per_instance * np.asarray(\n clients_per_thread)\n full_data.append(total_num_clients)\n\n for j in range(len(a)):\n throughput_means = []\n throughput_stdev = []\n\n restime_means = []\n restime_stdev = []\n\n for i, cpt in enumerate(clients_per_thread):\n sums_in_reps = []\n response_times_in_reps = []\n for rep in range(1, repetitions + 1):\n sum_throughput = 0\n response_times = []\n for vm in range(1, memtier_vms + 1):\n sum_throughput += data[a[j]][cpt][rep][vm][\"ALL STATS\"][b[j]][throughput_literal]\n response_times.append(data[a[j]][cpt][rep][vm][\"ALL STATS\"][b[j]][latency_literal])\n sums_in_reps.append(sum_throughput)\n response_times_in_reps.append(np.mean(np.asarray(response_times)))\n\n average_throughput_over_repetitions = np.mean(np.asarray(sums_in_reps))\n stdev_throughput_over_repetitions = np.std(np.asarray(sums_in_reps))\n throughput_means.append(average_throughput_over_repetitions)\n throughput_stdev.append(stdev_throughput_over_repetitions)\n\n average_restime_over_repetitions = np.mean(np.asarray(response_times_in_reps))\n stdev_restime_over_repetitions = np.std(np.asarray(response_times_in_reps))\n restime_means.append(average_restime_over_repetitions)\n restime_stdev.append(stdev_restime_over_repetitions)\n\n full_data.append(throughput_means)\n full_data.append(throughput_stdev)\n full_data.append(restime_means)\n full_data.append(restime_stdev)\n\n # print_csv([\"Number of Clients\",\n # \"Average Throughput WRITE-ONLY\", \"Std Dev Throughput WRITE-ONLY\",\n # \"Average Response Time WRITE-ONLY\", \"Std Dev Response Time WRITE-ONLY\"], full_data,\n # plots_base_name + \"source_baseline_nomidd_1server.csv\")\n\n print_csv([\"Number of Clients\", \"Average Throughput READ-ONLY\", \"Std Dev Throughput READ-ONLY\",\n \"Average Response Time READ-ONLY\", \"Std Dev Response Time READ-ONLY\",\n \"Average Throughput WRITE-ONLY\", \"Std Dev Throughput WRITE-ONLY\",\n \"Average Response Time WRITE-ONLY\", \"Std Dev Response Time WRITE-ONLY\"], full_data,\n plots_base_name + \"source_baseline_nomidd_1server.csv\")\n\n\ndef main():\n read_jsons(False)\n read_jsons(True)\n assemble_and_print()\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "process_memtier_data_baseline_nomidd_1server.py", "file_name": "process_memtier_data_baseline_nomidd_1server.py", "file_ext": "py", "file_size_in_byte": 4724, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 56, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 112, "usage_type": "call"}]} +{"seq_id": "137028543", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile name: fasta_extractor.py\nAuthor: Ivan Munoz-Gutierrez\nDate created: 02/10/2021\nDate last modified: 03/27/2021\nPython version: 3.9\nDescription: Extract fasta sequences contained in fasta files. For more\n information refer to the epilog_msg in the user_input\n function.\n\nTODO: make an option to extract fasta sequences in a single folder. Make the\n program more general.\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nimport textwrap\n\n\ndef user_input():\n \"\"\"\n Parse command line arguments provided by the user and check correct usage.\n\n Uses the module argparse to parse the command line arguments\n\n Parameters\n ----------\n --input, --output and --style\n Command line arguments provided by the user.\n\n Returns\n -------\n argparse object (.input, .output and .style)\n .input : list\n If one argument is provided, the list contains one element which\n is a path to a single fasta file requested for processing. If two\n arguments are provided, the list contains two elements. The first\n element is the path to an input directory that contains primary\n subfolders for analysis. The second element is the name of the\n fasta file that is contained in the primary subfolders and will be\n processed.\n .output : string\n Holds the path to the output directory.\n .style : string\n Header style of the fasta(s) file(s) to be analyzed.\n \"\"\"\n epilog_msg = (\"\"\"\n The program can process one or more fasta files. When only one fasta file\n needs to be processed, the user should provide the path to the file. In the\n case of multiple fasta files, the user should provide a path to a folder\n containing subfolders with the fasta file that needs to be processed. For\n example, the user can have a tree folder structure named results as shown\n below. In this case, the path to the results folder is the input. As it can\n be observed, the results folder contains two primary subfolders and every\n primary subfolder contains the SW0001 and SW0002 assembly.fasta that would\n be processed.\n\n ~/results/\n SW0001_n2759_L1000-/\n assembly.fasta\n SW0002_n2770_L1000-/\n assembly.fasta\n\n If the path to the results folder from the above example is provided as\n input, the program searches for assembly.fasta in the SW0001 subfolder and\n parse the fasta file. When a header is found, i.e. when a '>' symbol is\n found, the fasta sequence will be extracted as an independent file. The\n script will repeat the process every time it finds a header. When the EOF\n is reached, the script continues with the next SW0002 subfolder. If the\n user doesn't provide an output path, the new fasta files are saved in the\n same folder that contains the fasta file used for the extraction.\n\n This program parses two styles of fasta files, Unicycler and GeneBank. The\n Unicycler style is characterized by providing the length and topology of\n the molecule in the header, whereas GeneBank provides the accession number.\n By default, this programs assumes that the provided fasta files are\n Unicycler style. The user can specify the style by providing the\n corresponding flag.\n\n If the fasta file style is Unicycler, the new extracted fasta sequences are\n named according to the name of the directory that contains the fasta file.\n Additionally, header's information as length and topology are included in\n the fasta file name. In the case of GeneBank style, the new extracted fasta\n files are named according to the accession number present in the header.\n\n Examples of usage\n ----------------\n Example 1\n Let's pretend the results folder shown above is the input. If we want to\n get the extracted fasta files in the same folder as the provided\n assembly.fasta, the user should type:\n\n python3 fasta_extractor.py -i ~/results assembly.fasta\n\n The input flag gets two arguments, the path to the results folder and the\n name of the fasta files to be processed. An hypothetical result could be\n the following:\n\n ~/results/\n SW0001_n2759_L1000-/\n assembly.fasta\n SW0001_n2759_L1000_4000000_circular.fasta\n SW0001_n2759_L1000_100000_circular.fasta\n SW0001_n2759_L1000_5000_circular.fasta\n SW0002_n2770_L1000-/\n assembly.fasta\n SW0002_n2770_L1000_3800000_linear.fasta\n SW0002_n2770_L1000_125000_circular.fasta\n\n It is important to note that the dash at the end of the folder's name is\n replaced with underscore when naming the extracted fasta files (our lab\n adds a dash at the end of the folder's name). If the folder's name doesn't\n have a dash, the program will add an underscore anyway.\n\n Example 2\n Let's use again the same results folder shown above as input. Now, if we\n want the extracted fasta files in an specific folder named assemblies that\n is in home the user should type:\n\n python3 fasta_extractor.py -i ~/results assembly.fasta -o ~/assemblies\n\n An hypothetical result could be the following:\n\n ~/results/\n SW0001_n2759_L1000-/\n assembly.fasta\n SW0002_n2770_L1000-/\n assembly.fasta\n ~/assemblies/\n SW0001_n2759_L1000_4000000_circular.fasta\n SW0001_n2759_L1000_100000_circular.fasta\n SW0001_n2759_L1000_5000_circular.fasta\n SW0002_n2770_L1000_3800000_linear.fasta\n SW0002_n2770_L1000_125000_circular.fasta\n\n Example 3\n In case the user has only one fasta file for processing, the user should\n provide the path to that file as follows:\n\n python3 fasta_extractor.py -i ~/results/SW0001_n2759_L1000-/assembly.fasta\n\n An hypothetical result could be the following:\n\n ~/results/\n SW0001_n2759_L1000-/\n assembly.fasta\n SW0001_n2759_L1000_4000000_circular.fasta\n SW0001_n2759_L1000_100000_circular.fasta\n SW0001_n2759_L1000_5000_circular.fasta\n\n Example 4\n If the user wants to extract multiple fasta sequences from a fasta file\n named sequences.fasta created in GenBank, and the fasta file is in Desktop,\n the user should type the following:\n\n python3 fasta_extractor.py -i ~/Desktop/sequences.fasta -s genbank\n\n To get the correcto output, the user must specify the style of the fasta\n file. Therefore, the user must provide the -s flag with the genbank\n argument. An hypothetical result could be the following:\n\n ~/Desktop/\n sequences.fasta\n CP049609.1.fasta\n CP049610.1.fasta\n CP049611.1.fasta\n \"\"\")\n # Creating a parser object for parsing arguments and providing help.\n parser = argparse.ArgumentParser(\n prog='python3 fasta_extractor.py',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=(\n \"Extracts fasta sequences contained in a fasta file\"),\n epilog=textwrap.dedent(epilog_msg))\n # Creating required argument group.\n mandatory_argument = parser.add_argument_group(\"required arguments\")\n # Making required argument.\n mandatory_argument.add_argument(\n '-i', '--input', required=True, nargs='+',\n help=(\n \"\"\"\n One or two arguments are required. If the user provides one\n argument, the program will process one fasta file. Therefore, the\n argument must be a path to the fasta file that needs to be\n processed. If the user provides two arguments, the program will\n process fasta files within primary subfolders. The fasta files to\n be processed must have the same name. Therefore, in this option,\n the first argument must give the path to the folder that contains\n the primary subfolders to be analyzed, and the second argument is\n the name of the fasta file contained in the primary subfolders that\n the program will process.\"\"\")\n )\n # Making optional arguments.\n parser.add_argument('-o', '--output', help=\"Path to output directory.\")\n parser.add_argument(\n '-s', '--style',\n help=(\n \"\"\"\n Header style of the submitted fasta file (Unicycler or GenBank). If\n style is Unicycler, type unicycler or u. If the style is GenBank\n type genbank or g.\"\"\")\n )\n # Saving parsed arguments.\n args = parser.parse_args()\n # Checking if user provided mandatory arguments.\n if len(args.input) == 1 and (not os.path.exists(args.input[0])):\n parser.exit(1, message=textwrap.dedent(\"\"\"\\\n Error: path to fasta file doesn't exist\\n\"\"\"))\n if len(args.input) == 1 and (os.path.isdir(args.input[0])):\n parser.exit(1, message=textwrap.dedent(\"\"\"\\\n Error: the path provided is a directory not a fasta file\\n\"\"\"))\n if len(args.input) == 2 and (not os.path.exists(args.input[0])):\n parser.exit(1, message=textwrap.dedent(\"\"\"\\\n Error: path to input folder file doesn't exist\\n\"\"\"))\n if len(args.input) > 2:\n parser.exit(1, message=textwrap.dedent(\"\"\"\\\n Error: too many arguments\\n\"\"\"))\n # If output folder is provided, check if it exists.\n if (args.output is not None) and (not os.path.exists(args.output)):\n parser.exit(1, message=\"Error: output directory does not exits\\n\")\n # If header style is provided check correct input.\n if args.style is not None:\n fasta_style = args.style.lower()\n if not (fasta_style == \"unicycler\" or fasta_style == \"u\" \n or fasta_style == \"genbank\" or fasta_style == \"g\"):\n parser.exit(1, message=\"Error: wrong submitted style\\n\")\n # Standardizing name of header style\n else:\n if fasta_style == \"unicycler\" or fasta_style == \"u\":\n args.style = \"unicycler\"\n if fasta_style == \"genbank\" or fasta_style == \"g\":\n args.style = \"genbank\"\n\n return args\n\n\ndef get_file_paths(file_name, input_folder):\n \"\"\"\n Get the paths of files with the same name that are contained in primary\n subdirectories.\n\n Iterate over subdirectories of a given directory (input_folder) looking\n for files with the same name (file_name). Return the paths to these files.\n\n This function was designed to get the path of the assembly.fasta files\n generated by Unicycler.\n\n Parameters\n ----------\n file_name : str\n Name of the file which path is needed, usually assembly.fasta.\n input_folder : str\n Path to the directory to analyze.\n\n Returns\n -------\n file_addresses : list\n List of paths to file_name.\n\n For example, if you have the hypothetical tree:\n\n ~/assemblies/\n SW0001/\n assembly.fasta\n SW0002/\n assembly.fasta\n\n You will get the following:\n [\"~/assemblies/SW0001/assembly.fasta\",\n \"~/assemblies/SW0002/assembly.fasta\"]\n \"\"\"\n # List to save the paths to file_name.\n file_addresses = []\n # Getting all files' and folders' names in the indicated directory.\n files_and_folders = os.listdir(input_folder)\n # Iterating over all the files and folders contained in input_folder.\n for folder in files_and_folders:\n # Checking if the current object is a folder or not.\n if os.path.isdir(os.path.join(input_folder, folder)):\n # If folder contains file_name, get path and append it to\n # file_addresses. Otherwise, print an error message and continue.\n if not os.path.exists(\n os.path.join(input_folder, folder, file_name)):\n print(\"folder \" + folder + \" does not have \" + file_name)\n continue\n file_addresses.append(\n os.path.join(input_folder, folder, file_name))\n\n return file_addresses\n\ndef header_extractor(header, style):\n \"\"\"\n Parse a header of a fasta sequence to extract information.\n\n If the style is unicycler, length and topology are extrated. If the style\n is genbank, accession number is extracted.\n\n Parameters\n ----------\n header : string\n Header of fasta sequence.\n style : string\n style of fasta file, it could be Unycler or GenBank style.\n\n Returns\n -------\n header_info : string\n If header style is unicycler, returns length and topology separated by\n underscore. For example, 5000000_circular.\n If header style is genbank, returns the accession number present in the\n header. For example, CP029244.1.\n \"\"\"\n # Spliting header into list.\n header = header.split(\" \")\n if style == \"unicycler\" or style == None:\n # Information needed.\n length = \"\"\n topology = \"\"\n # Looping over header to get info.\n for info in header:\n if \"length\" in info:\n info = info.split(\"=\")\n length = info[1]\n length = length.replace('\\n', '')\n elif \"circular\" in info:\n info = info.split(\"=\")\n topology = info[0]\n topology = topology.replace('\\n', '')\n else:\n continue\n if topology == \"\":\n topology = \"linear\"\n header_info = length + '_' + topology\n elif style == \"genbank\":\n # Getting the accession number\n header_info = header[0][1:]\n else:\n sys.exit(\"Error: wrong fasta header style.\")\n\n return header_info\n\n\ndef fasta_extractor(input_file, header_style, output_folder):\n \"\"\"\n Parse a fasta file to extract its fasta sequences.\n\n The extracted fasta sequences are saved into independent files and are\n named depending of the header style provided. If header style is unicycler,\n new files are named according to the name of the directory that contains\n the input_file. Additionally, the length and topology of the extracted\n fasta sequences are included in their name. If the header style is genbank,\n new files are named according to the accession number provided in the\n header of each fasta sequence.\n\n If the user doesn't specify the output_folder, the new fasta files are\n outputed in the same directory where the input_file is located.\n\n For example, if we have a hypothetical fasta file that contains three fasta\n sequences in the following path: ~/My_assembly/assembly.fasta. If header\n style is unicycler and if we don't specify the output_folder, a\n hypothetical output could be:\n\n ~/My_assembly/\n assembly.fasta\n My_assembly_4000000_circular.fasta\n My_assembly_100000_circular.fasta\n My_assembly_80000_circular.fasta\n\n Parameters\n ----------\n input_file : string\n Path to file to be opened for parsing.\n header_style : string\n Style of header that can be unicycler or genbank.\n output_folder : string\n Path to save the the new fasta files.\n \"\"\"\n # Getting absolute path to input file.\n path_infile = os.path.abspath(input_file)\n # Getting path to folder containing input file.\n path_infolder = os.path.dirname(path_infile)\n # Getting name of folder containing input file.\n folder_name = os.path.basename(path_infolder)\n # If folder_name has a dash at its end, replace it with underscore (in our\n # lab we add a dash at the end of folder name).\n if folder_name[len(folder_name) - 1:] == '-':\n folder_name = folder_name[: -1]\n folder_name = folder_name + '_'\n # If folder_name has underscore at its end, ignore.\n elif folder_name[len(folder_name) - 1:] == '_':\n pass\n # Otherwise add underscore at its end.\n else:\n folder_name = folder_name + '_'\n\n # Getting path to output folder.\n if output_folder is None:\n path_output = path_infolder\n else:\n path_output = output_folder\n\n # Opening input file.\n with open(input_file, \"r\") as infile:\n # Counter of fasta sequence.\n counter = 0\n # Iterating over infile.\n for line in infile:\n # If line is the first header open a new fasta file for writing.\n if line[0] == '>' and counter == 0:\n # Gettting information from header.\n header = header_extractor(line, header_style)\n # Making file name and new fasta file header.\n if header_style == \"unicycler\" or header_style is None:\n outfile_name = (folder_name + header)\n outfile_header = '>' + outfile_name + '\\n'\n if header_style == \"genbank\":\n outfile_name = header\n outfile_header = line\n # Opening out file.\n outfile = open(\n path_output + '/' + outfile_name + \".fasta\", 'w')\n # Copying header into outfile.\n outfile.write(outfile_header)\n # Increasing counter.\n counter += 1\n # If line isn't the first header, close the previous fasta file and\n # open a new one for writing.\n if line[0] == '>' and counter > 0:\n # Closing previous outfile.\n outfile.close()\n # Getting information of new header.\n header = header_extractor(line, header_style)\n # Making file name and new fasta file header.\n if header_style == \"unicycler\" or header_style is None:\n outfile_name = (folder_name + header)\n outfile_header = '>' + outfile_name + '\\n'\n if header_style == \"genbank\":\n outfile_name = header\n outfile_header = line\n # Opening out file.\n outfile = open(\n path_output + '/' + outfile_name + \".fasta\", 'w')\n # Copying header into outfile.\n outfile.write(outfile_header)\n # Increase counter.\n counter += 1\n # If line is not header concatene line into the opened fasta file.\n # To make sure that line is comming from a fasta sequence, counter\n # must be greaater than 0.\n if line[0] != '>' and counter > 0:\n outfile.write(line)\n # Closing the last fasta file only if a file was created, i.e. if the \n # counter is greater than 0.\n if counter > 0:\n outfile.close()\n\n\ndef main():\n \"\"\"Extract fasta sequences from fasta files.\"\"\"\n # Getting user input.\n args = user_input()\n # Getting input information list.\n input_info = args.input\n # Getting path to output directory.\n output_folder = args.output\n # Getting the header style of fasta file\n header_style = args.style\n\n # If user provided one argument in input, process the provided fasta file.\n if len(input_info) == 1:\n fasta_extractor(input_info[0], header_style, output_folder)\n # Otherwise, process the fasta files in the primary subdirectories.\n else:\n # Getting a list of paths to the primary subdirectories that contains \n # the requested fasta file.\n input_path_list = get_file_paths(input_info[1], input_info[0])\n # Looping over the list of paths to extract fasta sequences.\n for _, path in enumerate(input_path_list):\n fasta_extractor(path, header_style, output_folder)\n\n print(\"fasta_extractor is done!\")\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "fasta_extractor.py", "file_name": "fasta_extractor.py", "file_ext": "py", "file_size_in_byte": 19746, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 173, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 175, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 211, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path", "line_number": 213, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path", "line_number": 216, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 217, "usage_type": "call"}, {"api_name": "textwrap.dedent", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 223, "usage_type": "call"}, {"api_name": "os.path", "line_number": 223, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path", "line_number": 283, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 286, "usage_type": "call"}, {"api_name": "os.path", "line_number": 286, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 287, "usage_type": "call"}, {"api_name": "os.path", "line_number": 287, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 291, "usage_type": "call"}, {"api_name": "os.path", "line_number": 291, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 342, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 383, "usage_type": "call"}, {"api_name": "os.path", "line_number": 383, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 385, "usage_type": "call"}, {"api_name": "os.path", "line_number": 385, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 387, "usage_type": "call"}, {"api_name": "os.path", "line_number": 387, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 486, "usage_type": "call"}]} +{"seq_id": "362657632", "text": "from django.shortcuts import render, get_object_or_404, redirect\r\nfrom django.views.decorators.http import require_POST\r\n\r\nfrom cart.forms import AddProductForm\r\nfrom .cart import *\r\n# Create your views here.\r\n\r\n# 표기 = decorators / import 필요\r\n@require_POST\r\ndef add(request, product_id):\r\n print('장바구니에 넣는 제품 id : ', product_id)\r\n\r\n # cart.py를 import하고 Cart를 빼옴 / Cart(request) >> 객체생성\r\n cart = Cart(request)\r\n\r\n product = get_object_or_404(Product, id=product_id)\r\n # 유효한 값이 들어가 있는지 체크\r\n # input에 들어간 values를 가지고 옴\r\n form = AddProductForm(request.POST)\r\n if form.is_valid():\r\n cd = form.cleaned_data\r\n\r\n # 장바구니 추가\r\n cart.add(product=product, quantity= cd['quantity'], is_update= cd['is_update'])\r\n\r\n # redirect >> 서버에 요청 해달라는 명령\r\n return redirect('cart:detail')\r\n\r\ndef detail(request):\r\n cart = Cart(request)\r\n for product in cart:\r\n product['quantity_form'] = AddProductForm(initial={'quantity': product['quantity'], 'is_update': True})\r\n return render(request, 'cart/detail.html', {'cart': cart})", "sub_path": "cart/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1183, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "cart.forms", "line_number": 14, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 16, "usage_type": "call"}, {"api_name": "cart.forms.AddProductForm", "line_number": 19, "usage_type": "call"}, {"api_name": "cart.forms.add", "line_number": 24, "usage_type": "call"}, {"api_name": "cart.forms", "line_number": 24, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 27, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_POST", "line_number": 9, "usage_type": "name"}, {"api_name": "cart.forms", "line_number": 30, "usage_type": "name"}, {"api_name": "cart.forms", "line_number": 31, "usage_type": "name"}, {"api_name": "cart.forms.AddProductForm", "line_number": 32, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 33, "usage_type": "call"}, {"api_name": "cart.forms", "line_number": 33, "usage_type": "name"}]} +{"seq_id": "529276159", "text": "import random\nimport struct\nimport sys\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom SimulaQron.general.hostConfig import *\nfrom SimulaQron.cqc.backend.cqcHeader import *\nfrom SimulaQron.cqc.pythonLib.cqc import *\n\nfrom flow import circuit_file_to_flow, count_qubits_in_sequence\nfrom angle import measure_angle\n\n# Randomly select circuit from circuits directory\ncircuits_path = Path(\".\") / \"circuits\"\ncircuit_file_paths = list(circuits_path.glob(\"*.json\"))\ncircuit = random.choice(circuit_file_paths)\n\n# Load circuit as MBQC flow\nprint(\"Client Loading {}\".format(circuit))\nseq_out = circuit_file_to_flow(\"./circuits/circuit1.json\")\n\n# Determine number of cubits our circuit needs\nnQubits = count_qubits_in_sequence(seq_out)\n\n# Initialize measurements count and entanglement lists\nnMeasurement = 0\nE1 = []\nE2 = []\n\n# We use the flow sequence to build entanglemtn lists and count measurements\nfor s in seq_out:\n s.printinfo()\n if s.type == \"E\":\n E1.append(s.qubits[0])\n E2.append(s.qubits[1])\n if s.type == \"M\":\n nMeasurement += 1\n\n# Outcome of each qubit will be stored in this outcome list\noutcome = nQubits * [-1]\n\nserver_name = \"Charlie\"\n\nwith CQCConnection(\"Bob\") as client:\n print(\"Client Sending (classical): Create {} qubits\".format(nQubits))\n client.sendClassical(server_name, nQubits)\n\n angles = []\n for i in range(0, nQubits):\n rand_angle = int(256 * random.random())\n angles.append(rand_angle)\n q = qubit(client)\n q.rot_Y(64) # |+> state\n q.rot_Z(rand_angle)\n print(\"Client Sending (quantum): qubit {}\".format(i + 1))\n client.sendQubit(q, server_name)\n\n time.sleep(1)\n print(\"Client Sending (classical): Ask to perform {} measurements\".format(nQubits))\n client.sendClassical(server_name, nMeasurement)\n time.sleep(1)\n print(\"Client Sending (classical): List of 1st Qubits to Entangle\".format(nQubits))\n client.sendClassical(server_name, E1)\n time.sleep(1)\n print(\"Client Sending (classical): List of 2nd Qubits to Entangle\".format(nQubits))\n client.sendClassical(server_name, E2)\n\n for s in seq_out:\n if s.type == \"M\":\n # Which qubit are we measuring?\n qubit_n = s.qubit\n\n # What is the angle we wish to measure\n computation_angle = s.angle\n input_angle = angles[qubit_n]\n\n # Calclate the angle to send with randomisation applied\n r = np.round(random.random())\n angle_to_send = measure_angle(\n qubit_n, seq_out, outcome, input_angle, computation_angle\n ) + r * (np.pi)\n\n print(\"Client Sending (classical): ask to measure qubit {}\".format(qubit_n))\n time.sleep(1)\n client.sendClassical(server_name, qubit_n)\n\n print(\n \"Client Sending (classical): measurement angle {}\".format(angle_to_send)\n )\n time.sleep(1)\n client.sendClassical(server_name, angle_to_send)\n\n m = int.from_bytes(client.recvClassical(), \"little\")\n print(\"Client Received: result {}\".format(m))\n\n # We adjust for the randomness only we know we added\n if r == 1:\n outcome[qubit_n - 1] = 1 - m\n else:\n outcome[qubit_n - 1] = m\n\n print(\"Client Output: {}\".format(outcome))\n sys.exit(0)\n", "sub_path": "examples/ubqc/client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 3400, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pathlib.Path", "line_number": 16, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 18, "usage_type": "call"}, {"api_name": "flow.circuit_file_to_flow", "line_number": 22, "usage_type": "call"}, {"api_name": "flow.count_qubits_in_sequence", "line_number": 25, "usage_type": "call"}, {"api_name": "random.random", "line_number": 52, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 60, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 80, "usage_type": "call"}, {"api_name": "random.random", "line_number": 80, "usage_type": "call"}, {"api_name": "angle.measure_angle", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 83, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 86, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 92, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 105, "usage_type": "call"}]} +{"seq_id": "97894125", "text": "# -*- coding: utf-8 -*-\n\nu\"\"\"\nEnvelope contact form.\n\"\"\"\n\nimport logging\nfrom smtplib import SMTPException\n\nfrom django import forms\nfrom django.core import mail\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom envelope import settings\n\n\nlogger = logging.getLogger('envelope.forms')\n\n\nclass BaseContactForm(forms.Form):\n u\"\"\"\n Base contact form class.\n \"\"\"\n sender = forms.CharField(label=_(\"From\"), max_length=70)\n email = forms.EmailField(label=_(\"Email\"))\n subject = forms.CharField(label=_(\"Subject\"), max_length=127)\n message = forms.CharField(label=_(\"Message\"), max_length=1000,\n widget=forms.Textarea())\n\n def __init__(self, *args, **kwargs):\n self.email_template = kwargs.pop('email_template')\n super(BaseContactForm, self).__init__(*args, **kwargs)\n\n def save(self):\n u\"\"\"\n Sends the message.\n \"\"\"\n subject = settings.ENVELOPE_SUBJECT_INTRO + self.cleaned_data['subject']\n context = self.get_context()\n message = render_to_string(self.email_template, context)\n try:\n mail.EmailMessage(subject, message, settings.ENVELOPE_FROM_EMAIL,\n settings.ENVELOPE_EMAIL_RECIPIENTS,\n headers = {'Reply-To': self.cleaned_data['email']}).send()\n logger.info(_(\"Contact form submitted and sent (from: %s)\") %\n self.cleaned_data['email'])\n except SMTPException:\n logger.exception(_(\"An error occured while sending the email\"))\n return False\n else:\n return True\n\n def get_context(self):\n u\"\"\"\n Returns a dictionary of values to be passed to the email body template.\n\n Override this method to set additional template variables.\n \"\"\"\n return self.cleaned_data.copy()\n\n\nclass ContactForm(BaseContactForm):\n u\"\"\"\n The default contact form class.\n\n This class extends the base form with a possibility to select message\n category. For example, user can ask a general question regarding the\n website or a more specific one, like \"ask tech support\" or \"I want to speak\n to the manager\".\n\n The categories are controlled by configuring ``ENVELOPE_CONTACT_CHOICES`` in\n your settings.py. The value for this setting should be a tuple of 2-element\n tuples, as usual with Django choice fields. Keep first elements of those\n tuples as integer values (or use None for the category \"Other\").\n \"\"\"\n category = forms.ChoiceField(label=_(\"Category\"),\n choices=settings.ENVELOPE_CONTACT_CHOICES)\n\n def __init__(self, *args, **kwargs):\n u\"\"\"\n This does the trick with placing category choice above the subject.\n \"\"\"\n super(ContactForm, self).__init__(*args, **kwargs)\n self.fields.keyOrder = [\n 'sender',\n 'email',\n 'category',\n 'subject',\n 'message',\n ]\n\n def get_context(self):\n u\"\"\"\n Adds full category description to template variables in order to display\n the category in email body.\n \"\"\"\n context = super(ContactForm, self).get_context()\n context['category'] = self.get_category_display()\n return context\n\n def get_category_display(self):\n u\"\"\"\n Returns the displayed name of the selected category.\n \"\"\"\n try:\n category = int(self.cleaned_data['category'])\n except (AttributeError, ValueError):\n category = None\n return dict(settings.ENVELOPE_CONTACT_CHOICES).get(category)\n", "sub_path": "envelope/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 3681, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "django.forms.Form", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 21, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 25, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 25, "usage_type": "call"}, {"api_name": "django.forms.EmailField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 26, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 26, "usage_type": "call"}, {"api_name": "django.forms.CharField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 27, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 27, "usage_type": "call"}, {"api_name": "django.forms.CharField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 28, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 28, "usage_type": "call"}, {"api_name": "django.forms.Textarea", "line_number": 29, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 29, "usage_type": "name"}, {"api_name": "envelope.settings.ENVELOPE_SUBJECT_INTRO", "line_number": 39, "usage_type": "attribute"}, {"api_name": "envelope.settings", "line_number": 39, "usage_type": "name"}, {"api_name": "django.template.loader.render_to_string", "line_number": 41, "usage_type": "call"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 43, "usage_type": "call"}, {"api_name": "django.core.mail", "line_number": 43, "usage_type": "name"}, {"api_name": "envelope.settings.ENVELOPE_FROM_EMAIL", "line_number": 43, "usage_type": "attribute"}, {"api_name": "envelope.settings", "line_number": 43, "usage_type": "name"}, {"api_name": "envelope.settings.ENVELOPE_EMAIL_RECIPIENTS", "line_number": 44, "usage_type": "attribute"}, {"api_name": "envelope.settings", "line_number": 44, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 46, "usage_type": "call"}, {"api_name": "smtplib.SMTPException", "line_number": 48, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 49, "usage_type": "call"}, {"api_name": "django.forms.ChoiceField", "line_number": 77, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 77, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 77, "usage_type": "call"}, {"api_name": "envelope.settings.ENVELOPE_CONTACT_CHOICES", "line_number": 78, "usage_type": "attribute"}, {"api_name": "envelope.settings", "line_number": 78, "usage_type": "name"}, {"api_name": "envelope.settings.ENVELOPE_CONTACT_CHOICES", "line_number": 110, "usage_type": "attribute"}, {"api_name": "envelope.settings", "line_number": 110, "usage_type": "name"}]} +{"seq_id": "475822375", "text": "# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao (Bin.Xiao@microsoft.com)\n# Modified by Dequan Wang and Xingyi Zhou\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport math\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom .DCNv2.dcn_v2 import DCN\nimport torch.utils.model_zoo as model_zoo\nimport copy\nfrom .se_module import SELayer\nimport numpy as np\n\nBN_MOMENTUM = 0.1\nlogger = logging.getLogger(__name__)\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\nclass SELayerCat(nn.Module):\n def __init__(self):\n super(SELayerCat, self).__init__()\n # predefined\n self.overlap_link = [(1), (1, 2), (2), (1, 3), (1, 4, 2, 3), (2, 4), (3), (3, 4), (4)]\n self.center = [(0.6, 0.6), (0.4, 0.6), (0.6, 0.4), (0.4, 0.4)]\n self.patch = self.GetPatchIndex(self.center)\n self.overlap_area = [(32, 48), (48, 32), (32, 32), (48, 32), (32, 48)]\n self.size = 80\n self.fc1_2 = SELayer(2, 1, self.overlap_area[0])\n self.fc1_3 = SELayer(2, 1, self.overlap_area[1])\n self.fc2_4 = SELayer(2, 1, self.overlap_area[3])\n self.fc3_4 = SELayer(2, 1, self.overlap_area[4])\n self.fc_1234 = SELayer(4, 1, self.overlap_area[2])\n # index se module fc layer\n self.se_2 = {1: self.fc1_2, 3: self.fc1_3, 5: self.fc2_4, 7: self.fc3_4}\n self.se_4 = {4: self.fc_1234}\n\n def GetPatchIndex(self, center):\n \"\"\"get patch module coordinate\"\"\"\n patch_module = {}\n for idx, cs in enumerate(center):\n patch_module[idx] = [[0, 0, cs[0], cs[1]], [cs[0], 0, 1, cs[1]],\n [0, cs[1], cs[0], 1], [cs[0], cs[1], 1, 1]]\n return patch_module\n\n def FeReshapeCat(self,x,link):\n \"\"\"\n reshape feature(add depth dim) and concatenate \"\"\"\n cat_seq = []\n for i in range(0, len(link), 2):\n cat_seq.append(x[link[i]-1][link[i+1]-1].unsqueeze(2))\n cat_seq.append(x[link[i+1]-1][link[i]-1].unsqueeze(2))\n output = torch.cat(cat_seq, 2)\n # out = self.forward(input, input.shape[-2], input.shape[-1], len(cat_seq))\n return output\n\n def FtCrop(self,x):\n \"\"\"\n crop feature and return 4*4 list\"\"\"\n x_patch_total = []\n for i in range(x.shape[2]):\n x_single = x[:,:,i]\n x_patch = []\n patch_module = (np.array(self.patch[i])*self.size).tolist()\n for patch_idx in patch_module:\n x_patch.append(x_single[:, :, int(patch_idx[0]):int(patch_idx[2]),\n int(patch_idx[1]):int(patch_idx[3])])\n x_patch_total.append(x_patch)\n return x_patch_total\n\n def forward(self, x):\n print('selayer cat')\n x_out = []\n x_patch_total = self.FtCrop(x)\n link = self.overlap_link\n # process 9 patches\n # for i, link in enumerate(self.overlap_link):\n # if isinstance(link, int):\n # x_out.append(x_patch_total[link-1][link-1])\n # continue\n # # se_module process 2 channels\n # if len(link) == 2:\n # x_out.append(self.se_2[i](self.FeReshapeCat(x_patch_total, link)))\n # # se_module process 4 channels\n # if len(link) == 4:\n # x_out.append(self.se_4[i](self.FeReshapeCat(x_patch_total, link)))\n x_out.append(x_patch_total[link[0] - 1][link[0] - 1])\n x_out.append(self.fc1_2(self.FeReshapeCat(x_patch_total, link[1])))\n x_out.append(x_patch_total[link[2] - 1][link[2] - 1])\n x_out.append(self.fc1_3(self.FeReshapeCat(x_patch_total, link[3])))\n x_out.append(self.fc_1234(self.FeReshapeCat(x_patch_total, link[4])))\n x_out.append(self.fc2_4(self.FeReshapeCat(x_patch_total, link[5])))\n x_out.append(x_patch_total[link[6] - 1][link[6] - 1])\n x_out.append(self.fc3_4(self.FeReshapeCat(x_patch_total, link[7])))\n x_out.append(x_patch_total[link[8] - 1][link[8] - 1])\n out_final = torch.cat([torch.cat([x_out[i], x_out[i+1], x_out[i+2]], 2) for i in range(0,9,3)], 3)\n return out_final\n\n def __call__(self, x):\n return self.forward(x)\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv3d(in_planes, out_planes, kernel_size=(1, 3, 3), stride=(1, stride, stride),\n padding=(0, 1, 1), bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm3d(planes, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm3d(planes, momentum=BN_MOMENTUM)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm3d(planes, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv3d(planes, planes, kernel_size=(1, 3, 3), stride=(1, stride, stride),\n padding=(0, 1, 1), bias=False)\n self.bn2 = nn.BatchNorm3d(planes, momentum=BN_MOMENTUM)\n self.conv3 = nn.Conv3d(planes, planes * self.expansion, kernel_size=1,\n bias=False)\n self.bn3 = nn.BatchNorm3d(planes * self.expansion,\n momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\ndef fill_up_weights(up):\n w = up.weight.data\n f = math.ceil(w.size(2) / 2)\n c = (2 * f - 1 - f % 2) / (2. * f)\n for i in range(w.size(2)):\n for j in range(w.size(3)):\n w[0, 0, i, j] = \\\n (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c))\n for c in range(1, w.size(0)):\n w[c, 0, :, :] = w[0, 0, :, :]\n\ndef fill_fc_weights(layers):\n for m in layers.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.001)\n # torch.nn.init.kaiming_normal_(m.weight.data, nonlinearity='relu')\n # torch.nn.init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\nclass DCNBlock(nn.Module):\n def __init__(self):\n super(DCNBlock, self).__init__()\n self.inplanes = 2048 # need to modify according backbone\n self.deconv_with_bias = False\n self.deconv_layers = self._make_deconv_layer(\n 3,\n [256, 128, 64],\n [4, 4, 4],\n )\n\n def _get_deconv_cfg(self, deconv_kernel):\n padding, output_padding = 0, 0\n if deconv_kernel == 4:\n padding = 1\n output_padding = 0\n elif deconv_kernel == 3:\n padding = 1\n output_padding = 1\n elif deconv_kernel == 2:\n padding = 0\n output_padding = 0\n\n return deconv_kernel, padding, output_padding\n\n def _make_deconv_layer(self, num_layers, num_filters, num_kernels):\n assert num_layers == len(num_filters), \\\n 'ERROR: num_deconv_layers is different len(num_deconv_filters)'\n assert num_layers == len(num_kernels), \\\n 'ERROR: num_deconv_layers is different len(num_deconv_filters)'\n\n layers = []\n for i in range(num_layers):\n kernel, padding, output_padding = \\\n self._get_deconv_cfg(num_kernels[i])\n\n planes = num_filters[i]\n fc = DCN(self.inplanes, planes,\n kernel_size=(3,3), stride=1,\n padding=1, dilation=1, deformable_groups=1)\n\n up = nn.ConvTranspose2d(\n in_channels=planes,\n out_channels=planes,\n kernel_size=kernel,\n stride=2,\n padding=padding,\n output_padding=output_padding,\n bias=self.deconv_with_bias)\n fill_up_weights(up)\n\n layers.append(fc)\n layers.append(nn.BatchNorm2d(planes, momentum=BN_MOMENTUM))\n layers.append(nn.ReLU(inplace=True))\n layers.append(up)\n layers.append(nn.BatchNorm2d(planes, momentum=BN_MOMENTUM))\n layers.append(nn.ReLU(inplace=True))\n self.inplanes = planes\n return nn.Sequential(*layers)\n\n def forward(self, x):\n return self.deconv_layers(x)\n\n def __call__(self, x):\n return self.forward(x)\n\nclass DCNNet(nn.Module):\n def __init__(self):\n super(DCNNet, self).__init__()\n self.block0 = DCNBlock()\n self.block1 = DCNBlock()\n self.block2 = DCNBlock()\n self.block3 = DCNBlock()\n\n def forward(self, x):\n x0 = self.block0(x[:, :, 0].contiguous()).unsqueeze(2)\n x1 = self.block1(x[:, :, 1].contiguous()).unsqueeze(2)\n x2 = self.block2(x[:, :, 2].contiguous()).unsqueeze(2)\n x3 = self.block3(x[:, :, 3].contiguous()).unsqueeze(2)\n outputs = [x0, x1, x2, x3]\n x = torch.cat(outputs, 2)\n return x\n\n def __call__(self, x):\n return self.forward(x)\n\n\nclass PoseResNet(nn.Module):\n\n def __init__(self, block, layers, heads, head_conv):\n self.inplanes = 64\n self.heads = heads\n self.deconv_with_bias = False\n\n super(PoseResNet, self).__init__()\n self.conv1 = nn.Conv3d(3, 64, kernel_size=(1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3),\n bias=False)\n self.bn1 = nn.BatchNorm3d(64, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.dcn = DCNNet()\n self.se = SELayerCat()\n\n for head in self.heads:\n classes = self.heads[head]\n if head_conv > 0:\n fc = nn.Sequential(\n nn.Conv2d(64, head_conv,\n kernel_size=3, padding=1, bias=True),\n nn.ReLU(inplace=True),\n nn.Conv2d(head_conv, classes,\n kernel_size=1, stride=1,\n padding=0, bias=True))\n if 'hm' in head:\n fc[-1].bias.data.fill_(-2.19)\n else:\n fill_fc_weights(fc)\n else:\n fc = nn.Conv2d(64, classes,\n kernel_size=1, stride=1,\n padding=0, bias=True)\n if 'hm' in head:\n fc.bias.data.fill_(-2.19)\n else:\n fill_fc_weights(fc)\n self.__setattr__(head, fc)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv3d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=(1, stride, stride), bias=False),\n nn.BatchNorm3d(planes * block.expansion, momentum=BN_MOMENTUM),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.dcn(x)\n x = self.se(x)\n\n ret = {}\n for head in self.heads:\n ret[head] = self.__getattr__(head)(x)\n return [ret]\n\n def init_weights(self, num_layers):\n if 1:\n # url = model_urls['resnet{}'.format(num_layers)]\n # pretrained_state_dict = model_zoo.load_url(url)\n print('=> loading pretrained model')\n self.load_state_dict(torch.load('/home/lyc/.torch/resnet_50_3d.pth'), strict=False)\n print('=> init deconv weights from normal distribution')\n for name, m in self.dcn.named_modules():\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def __call__(self, x):\n return self.forward(x)\n\nresnet_spec = {18: (BasicBlock, [2, 2, 2, 2]),\n 34: (BasicBlock, [3, 4, 6, 3]),\n 50: (Bottleneck, [3, 4, 6, 3]),\n 101: (Bottleneck, [3, 4, 23, 3]),\n 152: (Bottleneck, [3, 8, 36, 3])}\n\ndef convert_pth():\n \"\"\"\n modify pth from 2d to 3d\"\"\"\n model_path = '/home/lyc/.torch/models/resnet101-5d3b4d8f.pth'\n model = torch.load(model_path)\n model_new = copy.deepcopy(model)\n keys = model.keys()\n count = 0\n for idx, key_each in enumerate(list(keys)):\n if key_each.find('conv') != -1 or key_each.find('downsample') != -1:\n if len(model[key_each].shape) != 4:\n continue\n b, c, w, h = model[key_each].shape\n # print(b,c,w,h)\n model_new[key_each] = model[key_each].reshape(b, c, 1, w, h)\n count += 1\n continue\n model_new[key_each] = model[key_each]\n torch.save(model_new, '/home/lyc/.torch/resnet_101_3d.pth')\n print(count)\n\ndef resnet_dcn_se_net(num_layers, heads, head_conv=256):\n block_class, layers = resnet_spec[num_layers]\n\n model = PoseResNet(block_class, layers, heads, head_conv=head_conv)\n model.init_weights(num_layers)\n return model\n\ndef test():\n import os\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n heads = {'hm': 15, 'wh': 2, 'hps': 8, 'reg': 2, 'hm_hp': 4, 'hp_offset': 2}\n x = torch.randn(1, 3, 4, 320, 320).to(1)\n model = resnet_dcn_se_net(101, heads).to(1)\n y = model(x)\n keys = list(model.state_dict().keys())\n\n for key in keys:\n print(key)\n print(1)\n\nif __name__ == '__main__':\n test()\n", "sub_path": "src/lib/models/networks/resnet_dcn_se.py", "file_name": "resnet_dcn_se.py", "file_ext": "py", "file_size_in_byte": 15987, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 35, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "se_module.SELayer", "line_number": 44, "usage_type": "call"}, {"api_name": "se_module.SELayer", "line_number": 45, "usage_type": "call"}, {"api_name": "se_module.SELayer", "line_number": 46, "usage_type": "call"}, {"api_name": "se_module.SELayer", "line_number": 47, "usage_type": "call"}, {"api_name": "se_module.SELayer", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.nn.Conv3d", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 120, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 124, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 124, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 131, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 133, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 156, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 156, "usage_type": "name"}, {"api_name": "torch.nn.Conv3d", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 161, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.Conv3d", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 165, "usage_type": "name"}, {"api_name": "torch.nn.Conv3d", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 166, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 168, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 170, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 198, "usage_type": "call"}, {"api_name": "math.fabs", "line_number": 203, "usage_type": "call"}, {"api_name": "torch.nn.Conv2d", "line_number": 209, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 209, "usage_type": "name"}, {"api_name": "torch.nn.init.normal_", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 210, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 210, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 214, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 214, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 216, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 216, "usage_type": "name"}, {"api_name": "DCNv2.dcn_v2.DCN", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 257, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 268, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 269, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 271, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 272, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 272, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 274, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 274, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 282, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 282, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 296, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 303, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 303, "usage_type": "name"}, {"api_name": "torch.nn.Conv3d", "line_number": 311, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 311, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 313, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 313, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 314, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 314, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool3d", "line_number": 315, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 315, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 326, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 326, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 327, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 327, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 329, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 329, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 330, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 330, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 338, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 338, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 350, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 350, "usage_type": "name"}, {"api_name": "torch.nn.Conv3d", "line_number": 351, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 351, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm3d", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 353, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 362, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 362, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 388, "usage_type": "call"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 391, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 391, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 392, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 392, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 392, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 393, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 393, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 393, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 408, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 422, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 434, "usage_type": "attribute"}, {"api_name": "torch.randn", "line_number": 436, "usage_type": "call"}]} +{"seq_id": "485152717", "text": "from typing import Callable, Optional\nfrom testutils.trees import TreeNode, build_tree\n\n\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> list[list[int]]:\n if root is None:\n return []\n\n ans: list[list[int]] = []\n level = [root]\n\n reverse = False\n while len(level) > 0:\n values = [node.val for node in level]\n ans.append(values[::-1] if reverse else values)\n\n new_level = []\n for node in level:\n if node.left:\n new_level.append(node.left)\n if node.right:\n new_level.append(node.right)\n\n level = new_level\n reverse = not reverse\n\n return ans\n\n\ntests = [\n (\n ([3, 9, 20, None, None, 15, 7],),\n [[3], [20, 9], [15, 7]],\n ),\n (\n ([1],),\n [[1]],\n ),\n (\n ([],),\n [],\n ),\n]\n\n\ndef validator(\n zigzagLevelOrder: Callable[[Optional[TreeNode]], list[list[int]]],\n inputs: tuple[list[Optional[int]]],\n expected: list[list[int]],\n) -> None:\n values, = inputs\n tree = build_tree(values)\n output = zigzagLevelOrder(tree)\n assert output == expected, (output, expected)\n", "sub_path": "binary_tree_zigzag_level_order_traversal.py", "file_name": "binary_tree_zigzag_level_order_traversal.py", "file_ext": "py", "file_size_in_byte": 1259, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.Optional", "line_number": 6, "usage_type": "name"}, {"api_name": "testutils.trees.TreeNode", "line_number": 6, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "testutils.trees.TreeNode", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "testutils.trees.build_tree", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "648015981", "text": "# load and prepare deepfashion dataset and save to file\n\n# TO USE:\n# provide attrs_map.json file as the first argument and \n# 'imgs_attrs_map.json' as the second argument with the optional\n# -s flag at the end of the command followed by the desired max set size\n\nimport json, sys\nfrom os import listdir\nfrom numpy import zeros\nfrom numpy import asarray\nfrom numpy import savez_compressed\nfrom numpy import savez\nfrom numpy import load\nfrom pandas import read_csv\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom datetime import date\n\ntoday = date.today()\n\nattr_count = {}\n\n# one hot enc for list of tags \ndef one_hot_enc(tags, mapping):\n # create empty vector\n enc = zeros(len(mapping), dtype = 'uint8')\n # mark 1 for each tag in the vector\n for tag in tags:\n enc[mapping[tag]] = 1\n return enc\n\n# makes sure that attributes are not over represented in data\n# returning a 0 indicates that there this image contains an over\n# representative class and should be passed over\ndef balancer(tags):\n for tag in tags:\n if attr_count[tag]>2000:\n return 0\n for tag in tags:\n attr_count[tag] += 1\n return 1\n\n# load images into memory\ndef load_dataset(file_mapping, tag_mapping, ds_size):\n photos, targets = list(), list()\n\n i = 0\n\n for fname, tags in file_mapping.items():\n print(f\" {((i/ds_size)*100):.0f} % complete\", sep=' ', end='\\r', flush=True)\n # print(str(i/total_len) + '% complete', end='', flush=True)\n\n # load the image\n photo = load_img(fname, target_size=(256,256))\n photo = img_to_array(photo, dtype = 'uint8')\n # load its\n tags = file_mapping[fname]\n\n if balancer(tags) == 0:\n continue\n\n target = one_hot_enc(tags, tag_mapping)\n photos.append(photo)\n targets.append(target)\n \n i+=1\n \n if i == ds_size:\n break\n\n X = asarray(photos, dtype='uint8')\n Y = asarray(targets, dtype='uint8')\n return X,Y\n\ndef main():\n # check for command line flag\n if(len(sys.argv)==5 and sys.argv[3]=='-s'):\n size = int(sys.argv[4])\n else:\n size = 20000\n\n print(f\"Producing data set with {size} images\")\n\n # load mappings\n f = open(sys.argv[1], 'r')\n attrs_map = json.load(f)\n f.close()\n\n for key in attrs_map.keys():\n attr_count[key] = 0\n \n print(attr_count)\n \n f = open(sys.argv[2], 'r')\n imgs_map = json.load(f)\n f.close()\n\n # load images and labels \n X, y = load_dataset(imgs_map,attrs_map,size)\n print(X.shape, y.shape)\n\n with open('metadata_'+ today.strftime(\"%m-%d-%y\") +'.txt', 'w') as md:\n json.dump(attr_count, md)\n\n # save arrays of images and their corresponding labels\n savez('deepfashion_data_'+today.strftime(\"%m-%d-%y\")+'.npz', X, y)\n\n\n\nmain()", "sub_path": "Attribute_Prep_&_Training/deepfashion_based/make_dataset.py", "file_name": "make_dataset.py", "file_ext": "py", "file_size_in_byte": 2885, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.date.today", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 20, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 27, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.load_img", "line_number": 55, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.img_to_array", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 73, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 78, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 79, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 86, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 87, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 95, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 96, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 107, "usage_type": "call"}]} +{"seq_id": "616721077", "text": "import matplotlib\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom keras.preprocessing.image import ImageDataGenerator\nimport operator\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport base64\nimport ast\nimport sys\n\ndef recommand(predictions, class_dict):\n # Recommend top 3\n predictions = predictions[0].tolist()\n predict = []\n for i in range(len(predictions)):\n predict.insert(i, [i, predictions[i]])\n\n predict2 = sorted(predict, key=lambda x: x[1], reverse=True)\n\n re_str = \"\"\n for i in range(10):\n recommend = [name for name, target in class_dict.items() if target == predict2[i][0]]\n re_str = re_str + str(recommend)[2:len(recommend)-3]\n if i == 9:\n break\n re_str += \",\"\n # recommand_percent = predict2[i][1]\n # print(recommand, \" \", round(recommand_percent, 3) * 100, \"%\")\\\n return re_str\n\n\n# base64.txt -> image -> save folder\nremove_str = 'data:image/png;base64,'\n\nimage_path = '/home/student/2019_Capstone-design/node/image_predict/predict_image/12/out.png'\ng = open(image_path, 'wb')\ng.write(base64.b64decode(sys.argv[1][len(remove_str):]))\ng.close()\n\n\nmodel1 = load_model('/home/student/2019_Capstone-design/node/image_predict/v2.01.h5')\nmodel1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# Print test prediction\n\nf2 = open('/home/student/2019_Capstone-design/node/image_predict/label_dict.txt')\nlabel_dict = eval(f2.read())\nf2.close()\n\nbatchsize = 64\nimage_size = (255, 255)\n\npred_gen = ImageDataGenerator().flow_from_directory(\n '/home/student/2019_Capstone-design/node/image_predict/predict_image/',\n class_mode='categorical',\n batch_size=batchsize,\n target_size=image_size\n)\npredictions = model1.predict_generator(pred_gen)\nnp.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)})\nimport operator\nindex, value = max(enumerate(predictions[0]), key=operator.itemgetter(1))\npred_result = [name for name, target in label_dict.items() if target == index]\n\n#recommand_top3\nre_list = recommand(predictions, label_dict)\nprint(re_list)\n", "sub_path": "node/image_predict/image_predict2.py", "file_name": "image_predict2.py", "file_ext": "py", "file_size_in_byte": 2128, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "base64.b64decode", "line_number": 39, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}, {"api_name": "keras.models.load_model", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.ImageDataGenerator", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.set_printoptions", "line_number": 61, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "639342895", "text": "import pandas as pd\nimport numpy as np\nimport unicodedata\nimport time\nimport nltk\nfrom nltk.tokenize.toktok import ToktokTokenizer\nfrom nltk.corpus import stopwords\nimport re\n\ndef basic_clean(string):\n \"\"\"\n Lowercase the string\n Normalize unicode characters\n Replace anything that is not a letter, number, whitespace or a single quote.\n \"\"\"\n string = string.lower()\n string = string.replace('c++','cplusplus')\n string = unicodedata.normalize('NFKD', string).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n \n # remove anything not a space character, an apostrophy, letter, or number\n string = re.sub(r\"[^a-z0-9'\\s]\", '', string)\n\n # convert newlines and tabs to a single space\n string = re.sub(r'[\\r|\\n|\\r\\n]+', ' ', string)\n \n string = string.strip()\n return string\n\ndef tokenize(s):\n tokenizer = nltk.tokenize.ToktokTokenizer()\n return tokenizer.tokenize(s, return_str=True)\n\n\n\ndef remove_stopwords(s,extra_words =[], exclude_words = []):\n #Tokenize the string\n s = tokenize(s)\n \n words = s.split()\n stopword_list = stopwords.words('english')\n \n #remove the excluded words fro the stopword list\n stopword_list = set(stopword_list) - set(exclude_words)\n \n #add in the user specified extra words\n stopword_list = stopword_list.union(set(extra_words))\n \n filtered_words = [w for w in words if w not in stopword_list]\n final_string = ' '.join(filtered_words)\n return final_string\n\ndef lemmatize(s):\n wnl = nltk.stem.WordNetLemmatizer()\n lemmas = [wnl.lemmatize(word) for word in s.split()]\n string_of_lemmas = ' '.join(lemmas)\n return string_of_lemmas\n\n\ndef stem(s):\n ps = nltk.porter.PorterStemmer()\n stems = [ps.stem(word) for word in s.split()]\n string_of_stems = ' '.join(stems)\n return string_of_stems\n\n\ndef prep_urls(df):\n df['original'] = df.readme_contents\n df['clean'] = df.readme_contents.apply(basic_clean).apply(remove_stopwords)\n df['stemmed'] = df.clean.apply(stem)\n df['lemmatized'] = df.clean.apply(lemmatize)\n \n #df.drop(columns = ['body'], inplace = True)\n return df\n\ndef text_join(text):\n return \"\".join(text)", "sub_path": "prep.py", "file_name": "prep.py", "file_ext": "py", "file_size_in_byte": 2177, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "unicodedata.normalize", "line_number": 18, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 21, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 24, "usage_type": "call"}, {"api_name": "nltk.tokenize.ToktokTokenizer", "line_number": 30, "usage_type": "call"}, {"api_name": "nltk.tokenize", "line_number": 30, "usage_type": "attribute"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 40, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 40, "usage_type": "name"}, {"api_name": "nltk.stem.WordNetLemmatizer", "line_number": 53, "usage_type": "call"}, {"api_name": "nltk.stem", "line_number": 53, "usage_type": "attribute"}, {"api_name": "nltk.porter.PorterStemmer", "line_number": 60, "usage_type": "call"}, {"api_name": "nltk.porter", "line_number": 60, "usage_type": "attribute"}]} +{"seq_id": "398921613", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nfrom PyQt5 import QtWidgets, QtGui\nfrom communication_networks.gui.optimal_topology_window import OptimalTopologyWindow\nfrom communication_networks.gui.topology_parameters_window import TopologyParametersWindow\n\n__author__ = \"dima\"\n\n\nclass Application(QtWidgets.QMainWindow):\n \"\"\"\n Головне вікно програми\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.app_path = os.path.abspath('.')\n self.stack = QtWidgets.QStackedWidget()\n self.setCentralWidget(self.stack)\n main_window = OptimalTopologyWindow(self)\n parameters_window = TopologyParametersWindow(self)\n self.stack.addWidget(main_window)\n self.stack.addWidget(parameters_window)\n self.stack.setCurrentWidget(main_window)\n self.init_menu()\n self.setFont(QtGui.QFont(\"SansSerif\", 10))\n self.setWindowTitle(\"Комунікаційні мережі\")\n self.resize(1024, 360)\n self.setWindowIcon(QtGui.QIcon('icon.png'))\n self.center()\n self.show()\n\n def init_menu(self):\n main_menu = self.menuBar().addMenu(\"Меню\")\n windows = main_menu.addMenu(\"Інструменти\")\n\n main_window_link = windows.addAction(\"Знайти оптимальну топологію\")\n main_window_link.triggered.connect(lambda: self.stack.setCurrentIndex(0))\n\n parameters_window_link = windows.addAction(\"Обчислити метрики топології\")\n parameters_window_link.triggered.connect(lambda: self.stack.setCurrentIndex(1))\n\n main_menu.addSeparator()\n\n about = main_menu.addAction(\"Довідка\")\n about.triggered.connect(self.show_about)\n\n main_menu.addSeparator()\n\n close = main_menu.addAction(\"Вихід\")\n close.triggered.connect(self.close)\n\n def show_about(self):\n \"\"\"\n Повідомлення з довідкою\n \"\"\"\n message = \"Програма для обчислення метрик топологічних структур.\"\n return QtWidgets.QMessageBox.information(QtWidgets.QMessageBox(), \"Довідка\", message, QtWidgets.QMessageBox.Ok)\n\n def center(self):\n \"\"\"\n Center the window\n \"\"\"\n window_size = self.frameGeometry()\n screen_center_point = QtWidgets.QDesktopWidget().availableGeometry().center()\n window_size.moveCenter(screen_center_point)\n self.move(window_size.topLeft())\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n GUI = Application()\n sys.exit(app.exec_())\n", "sub_path": "communication_networks/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2669, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 12, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 12, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QStackedWidget", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 20, "usage_type": "name"}, {"api_name": "communication_networks.gui.optimal_topology_window.OptimalTopologyWindow", "line_number": 22, "usage_type": "call"}, {"api_name": "communication_networks.gui.topology_parameters_window.TopologyParametersWindow", "line_number": 23, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 28, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 28, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 31, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 31, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.information", "line_number": 60, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 60, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 60, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDesktopWidget", "line_number": 67, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 67, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 73, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 73, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 73, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "154596848", "text": "import re\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional\n\nfrom jsoncomment import JsonComment\n\nfrom lean.components.cli_config_manager import CLIConfigManager\n\n\nclass LeanConfigManager:\n \"\"\"The LeanConfigManager class contains utilities to work with files containing LEAN engine configuration.\"\"\"\n\n def __init__(self, cli_config_manager: CLIConfigManager, default_file_name: str) -> None:\n \"\"\"Creates a new LeanConfigManager instance.\n\n :param cli_config_manager: the CLIConfigManager instance to use when retrieving credentials\n :param default_file_name: the default name of the file containing the Lean config\n \"\"\"\n self._cli_config_manager = cli_config_manager\n self._default_file_name = default_file_name\n self._default_path = None\n\n def get_lean_config_path(self) -> Path:\n \"\"\"Returns the path to the closest Lean config file.\n\n This recurses upwards in the directory tree looking for a Lean config file.\n This search can be overridden using set_default_lean_config_path().\n\n Raises an error if no Lean config file can be found.\n\n :return: the path to the closest Lean config file\n \"\"\"\n if self._default_path is not None:\n return self._default_path\n\n # Recurse upwards in the directory tree until we find a Lean config file\n current_dir = Path.cwd()\n while True:\n target_file = current_dir / self._default_file_name\n if target_file.exists():\n return target_file\n\n # If the parent directory is the same as the current directory we can't go up any more\n if current_dir.parent == current_dir:\n raise RuntimeError(\n \"This command should be executed in a Lean CLI project, run `lean init` in an empty directory to create one or specify the configuration file to use with --config\")\n\n current_dir = current_dir.parent\n\n def set_default_lean_config_path(self, path: Path) -> None:\n \"\"\"Overrides the default search for the path to the Lean config file.\n\n :param path: the path to the Lean config file to return in future calls to get_lean_config_path()\n \"\"\"\n self._default_path = path\n\n def get_data_directory(self) -> Path:\n \"\"\"Returns the path to the data directory.\n\n :return: the path to the data directory as it is configured in the Lean config\n \"\"\"\n config = self._read_lean_config()\n config_path = self.get_lean_config_path()\n return config_path.parent / config[\"data-folder\"]\n\n def clean_lean_config(self, config: str) -> str:\n \"\"\"Removes the properties from a Lean config file which can be set in get_complete_lean_config().\n\n This removes all the properties which the CLI can configure automatically based on the command that is ran.\n\n For example, given the following config:\n {\n // Environment docs\n \"environment\": \"backtesting\",\n\n // Key2 docs\n \"key2\": \"value2\"\n }\n\n Calling clean_lean_config(config) would return the following:\n {\n // Key2 docs\n \"key2\": \"value2\"\n }\n\n Because \"environment\" can be set automatically based on the command that is ran.\n\n :param config: the configuration to remove the auto-configurable keys from\n :return: the same config as passed in with the config argument, but without the auto-configurable keys\n \"\"\"\n # The keys that we can set automatically based on the command that is ran\n keys_to_remove = [\"environment\",\n \"composer-dll-directory\",\n \"debugging\", \"debugging-method\",\n \"job-user-id\", \"api-access-token\",\n \"algorithm-type-name\", \"algorithm-language\", \"algorithm-location\"]\n\n # This function is implemented by doing string manipulation because the config contains comments\n # If we were to parse it as JSON, we would have to remove the comments which we don't want to do\n sections = re.split(r\"\\n\\s*\\n\", config)\n for key in keys_to_remove:\n sections = [section for section in sections if f\"\\\"{key}\\\": \" not in section]\n\n return \"\\n\\n\".join(sections)\n\n def get_complete_lean_config(self,\n environment: str,\n algorithm_file: Path,\n debugging_method: Optional[str]) -> Dict[str, Any]:\n \"\"\"Returns a complete Lean config object containing all properties needed for the engine to run.\n\n This retrieves the path of the config, parses the file and adds all properties removed in clean_lean_config().\n\n It is assumed that the default LEAN Docker image is used and that the Lean CLI project is mounted at /LeanCLI.\n\n :param environment: the environment to set\n :param algorithm_file: the path to the algorithm that will be ran\n :param debugging_method: the debugging method to use, or None to disable debugging\n \"\"\"\n config = self._read_lean_config()\n\n config[\"environment\"] = environment\n config[\"close-automatically\"] = True\n\n config[\"composer-dll-directory\"] = \".\"\n\n config[\"debugging\"] = debugging_method is not None\n config[\"debugging-method\"] = debugging_method or \"LocalCmdline\"\n\n config[\"job-user-id\"] = self._cli_config_manager.user_id.get_value(default=\"0\")\n config[\"api-access-token\"] = self._cli_config_manager.api_token.get_value(default=\"\")\n\n if algorithm_file.name.endswith(\".py\"):\n lean_cli_project_root = self.get_lean_config_path().parent\n\n config[\"algorithm-type-name\"] = algorithm_file.name.split(\".\")[0]\n config[\"algorithm-language\"] = \"Python\"\n config[\"algorithm-location\"] = f\"/LeanCLI/{algorithm_file.relative_to(lean_cli_project_root).as_posix()}\"\n else:\n algorithm_text = algorithm_file.read_text()\n config[\"algorithm-type-name\"] = re.findall(f\"class ([a-zA-Z0-9]+)\", algorithm_text)[0]\n config[\"algorithm-language\"] = \"CSharp\"\n config[\"algorithm-location\"] = \"QuantConnect.Algorithm.CSharp.dll\"\n\n return config\n\n def _read_lean_config(self) -> Dict[str, Any]:\n \"\"\"Reads the Lean config into a dict.\n\n :return: a dict containing the contents of the Lean config file\n \"\"\"\n config_text = self.get_lean_config_path().read_text()\n\n # JsonComment can parse JSON with non-inline comments, so we remove the inline ones first\n config_without_inline_comments = re.sub(r\",\\s*//.*\", \",\", config_text, flags=re.MULTILINE)\n\n return JsonComment().loads(config_without_inline_comments)\n", "sub_path": "lean/components/lean_config_manager.py", "file_name": "lean_config_manager.py", "file_ext": "py", "file_size_in_byte": 6848, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "lean.components.cli_config_manager.CLIConfigManager", "line_number": 13, "usage_type": "name"}, {"api_name": "pathlib.Path.cwd", "line_number": 37, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 37, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 23, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 50, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 57, "usage_type": "name"}, {"api_name": "re.split", "line_number": 100, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 108, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 109, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 141, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 109, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 109, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 155, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 155, "usage_type": "attribute"}, {"api_name": "jsoncomment.JsonComment", "line_number": 157, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 147, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 147, "usage_type": "name"}]} +{"seq_id": "485159375", "text": "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport compas_rhino\n\nfrom compas_rhino.artists._artist import BaseArtist\n\nfrom compas.utilities import color_to_colordict\nfrom compas.utilities import pairwise\nfrom compas.geometry import add_vectors\nfrom compas.geometry import scale_vector\nfrom compas.geometry import centroid_polygon\n\n\n__all__ = ['MeshArtist']\n\n\nclass MeshArtist(BaseArtist):\n \"\"\"A mesh artist defines functionality for visualising COMPAS meshes in Rhino.\n\n Parameters\n ----------\n mesh : :class:`compas.datastructures.Mesh`\n A COMPAS mesh.\n layer : str, optional\n The name of the layer that will contain the mesh.\n settings : dict, optional\n A dict with custom visualisation settings.\n\n Attributes\n ----------\n mesh : :class:`compas.datastructures.Mesh`\n The COMPAS mesh associated with the artist.\n layer : str\n The layer in which the mesh should be contained.\n settings : dict\n Default settings for color, scale, tolerance, ...\n\n Examples\n --------\n .. code-block:: python\n\n import compas\n from compas.datastructures import Mesh\n from compas_rhino.artists import MeshArtist\n\n mesh = Mesh.from_obj(compas.get('faces.obj'))\n\n artist = MeshArtist(mesh, layer='COMPAS::MeshArtist')\n artist.clear_layer()\n artist.draw_faces(join_faces=True)\n artist.draw_vertices(color={key: '#ff0000' for key in mesh.vertices_on_boundary()})\n artist.draw_edges()\n artist.redraw()\n\n \"\"\"\n\n def __init__(self, mesh, layer=None, settings=None):\n super(MeshArtist, self).__init__()\n self._guid_vertex = {}\n self._guid_edge = {}\n self._guid_face = {}\n self._guid_vertexnormal = {}\n self._guid_facenormal = {}\n self._guid_vertexlabel = {}\n self._guid_edgelabel = {}\n self._guid_facelabel = {}\n self.mesh = mesh\n self.layer = layer\n self.settings = {\n 'color.vertices': (255, 255, 255),\n 'color.edges': (0, 0, 0),\n 'color.faces': (210, 210, 210),\n 'color.vertexnormals': (0, 255, 0),\n 'color.facenormals': (0, 255, 0),\n 'scale.vertexnormals': 0.1,\n 'scale.facenormals': 0.1,\n 'show.vertices': True,\n 'show.edges': True,\n 'show.faces': True,\n 'show.vertexnormals': False,\n 'show.facenormals': False,\n 'show.vertexlabels': False,\n 'show.facelabels': False,\n 'show.edgelabels': False,\n 'join_faces': True}\n if settings:\n self.settings.update(settings)\n\n @property\n def guid_vertex(self):\n \"\"\"Map between Rhino object GUIDs and mesh vertex identifiers.\"\"\"\n return self._guid_vertex\n\n @guid_vertex.setter\n def guid_vertex(self, values):\n self._guid_vertex = dict(values)\n\n @property\n def guid_edge(self):\n \"\"\"Map between Rhino object GUIDs and mesh edge identifiers.\"\"\"\n return self._guid_edge\n\n @guid_edge.setter\n def guid_edge(self, values):\n self._guid_edge = dict(values)\n\n @property\n def guid_face(self):\n \"\"\"Map between Rhino object GUIDs and mesh face identifiers.\"\"\"\n return self._guid_face\n\n @guid_face.setter\n def guid_face(self, values):\n self._guid_face = dict(values)\n\n @property\n def guid_vertexnormal(self):\n \"\"\"Map between Rhino object GUIDs and force diagram vertex normal identifiers.\"\"\"\n return self._guid_vertexnormal\n\n @guid_vertexnormal.setter\n def guid_vertexnormal(self, values):\n self._guid_vertexnormal = dict(values)\n\n @property\n def guid_facenormal(self):\n \"\"\"Map between Rhino object GUIDs and force diagram face normal identifiers.\"\"\"\n return self._guid_facenormal\n\n @guid_facenormal.setter\n def guid_facenormal(self, values):\n self._guid_facenormal = dict(values)\n\n @property\n def guid_vertexlabel(self):\n \"\"\"Map between Rhino object GUIDs and force diagram vertex label identifiers.\"\"\"\n return self._guid_vertexlabel\n\n @guid_vertexlabel.setter\n def guid_vertexlabel(self, values):\n self._guid_vertexlabel = dict(values)\n\n @property\n def guid_facelabel(self):\n \"\"\"Map between Rhino object GUIDs and mesh face label identifiers.\"\"\"\n return self._guid_facelabel\n\n @guid_facelabel.setter\n def guid_facelabel(self, values):\n self._guid_facelabel = dict(values)\n\n @property\n def guid_edgelabel(self):\n \"\"\"Map between Rhino object GUIDs and mesh edge label identifiers.\"\"\"\n return self._guid_edgelabel\n\n @guid_edgelabel.setter\n def guid_edgelabel(self, values):\n self._guid_edgelabel = dict(values)\n\n # ==========================================================================\n # clear\n # ==========================================================================\n\n def clear(self):\n \"\"\"Clear all objects previously drawn by this artist.\n \"\"\"\n guids = []\n guids_vertices = list(self.guid_vertex.keys())\n guids_edges = list(self.guid_edge.keys())\n guids_faces = list(self.guid_face.keys())\n guids_vertexnormals = list(self.guid_vertexnormal.keys())\n guids_facenormals = list(self.guid_facenormal.keys())\n guids_vertexlabels = list(self.guid_vertexlabel.keys())\n guids_edgelabels = list(self.guid_edgelabel.keys())\n guids_facelabels = list(self.guid_facelabel.keys())\n guids += guids_vertices + guids_edges + guids_faces\n guids += guids_vertexnormals + guids_facenormals\n guids += guids_vertexlabels + guids_edgelabels + guids_facelabels\n compas_rhino.delete_objects(self.guids + guids, purge=True)\n self._guid_vertex = {}\n self._guid_edge = {}\n self._guid_face = {}\n self._guid_vertexnormal = {}\n self._guid_facenormal = {}\n self._guid_vertexlabel = {}\n self._guid_edgelabel = {}\n self._guid_facelabel = {}\n\n def clear_layer(self):\n \"\"\"Clear the main layer of the artist.\"\"\"\n if self.layer:\n compas_rhino.clear_layer(self.layer)\n # else:\n # compas_rhino.clear_current_layer()\n\n # ==========================================================================\n # components\n # ==========================================================================\n\n def draw(self, settings=None):\n \"\"\"Draw the mesh using the chosen visualisation settings.\n\n Parameters\n ----------\n settings : dict, optional\n Dictionary of visualisation settings that will be merged with the settings of the artist.\n\n Notes\n -----\n This method will attempt to clear all previously drawn elements by this artist.\n However, clearing the artist layer has to be done explicitly with a call to ``MeshArtist.clear_layer``.\n\n \"\"\"\n self.clear()\n if not settings:\n settings = {}\n self.settings.update(settings)\n if self.settings['show.vertices']:\n self.draw_vertices()\n if self.settings['show.vertexlabels']:\n self.draw_vertexlabels()\n if self.settings['show.vertexnormals']:\n self.draw_vertexnormals()\n if self.settings['show.faces']:\n self.draw_faces(join_faces=self.settings['join_faces'])\n if self.settings['show.facelabels']:\n self.draw_facelabels()\n if self.settings['show.facenormals']:\n self.draw_facenormals()\n if self.settings['show.edges']:\n self.draw_edges()\n if self.settings['show.edgelabels']:\n self.draw_edgelabels()\n\n def draw_mesh(self, color=None, disjoint=False):\n \"\"\"Draw the mesh as a consolidated RhinoMesh.\n\n Parameters\n ----------\n color : 3-tuple, optional\n RGB color components in integer format (0-255).\n disjoint : bool, optional\n Draw the faces of the mesh with disjoint vertices.\n Default is ``False``.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n Notes\n -----\n The mesh should be a valid Rhino Mesh object, which means it should have\n only triangular or quadrilateral faces.\n Faces with more than 4 vertices will be triangulated on-the-fly.\n \"\"\"\n key_index = self.mesh.key_index()\n vertices = self.mesh.vertices_attributes('xyz')\n faces = [[key_index[key] for key in self.mesh.face_vertices(fkey)] for fkey in self.mesh.faces()]\n new_faces = []\n for face in faces:\n f = len(face)\n if f == 3:\n new_faces.append(face + face[-1:])\n elif f == 4:\n new_faces.append(face)\n elif f > 4:\n centroid = len(vertices)\n vertices.append(centroid_polygon([vertices[index] for index in face]))\n for a, b in pairwise(face + face[0:1]):\n new_faces.append([centroid, a, b, b])\n else:\n continue\n layer = self.layer\n name = \"{}.mesh\".format(self.mesh.name)\n guid = compas_rhino.draw_mesh(vertices, new_faces, layer=layer, name=name, color=color, disjoint=disjoint)\n self.guids += [guid]\n return [guid]\n\n def draw_vertices(self, keys=None, color=None):\n \"\"\"Draw a selection of vertices.\n\n Parameters\n ----------\n keys : list\n A list of vertex keys identifying which vertices to draw.\n Default is ``None``, in which case all vertices are drawn.\n color : str, tuple, dict\n The color specififcation for the vertices.\n Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.\n To apply the same color to all vertices, provide a single color specification.\n Individual colors can be assigned using a dictionary of key-color pairs.\n Missing keys will be assigned the default vertex color (``self.settings['color.vertices']``).\n The default is ``None``, in which case all vertices are assigned the default vertex color.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n vertices = keys or list(self.mesh.vertices())\n vertex_color = color_to_colordict(color,\n vertices,\n default=self.settings['color.vertices'],\n colorformat='rgb',\n normalize=False)\n points = []\n for vertex in vertices:\n points.append({\n 'pos': self.mesh.vertex_coordinates(vertex),\n 'name': \"{}.vertex.{}\".format(self.mesh.name, vertex),\n 'color': vertex_color[vertex]})\n\n guids = compas_rhino.draw_points(points, layer=self.layer, clear=False, redraw=False)\n self.guid_vertex = zip(guids, vertices)\n return guids\n\n def draw_faces(self, keys=None, color=None, join_faces=False):\n \"\"\"Draw a selection of faces.\n\n Parameters\n ----------\n fkeys : list\n A list of face keys identifying which faces to draw.\n The default is ``None``, in which case all faces are drawn.\n color : str, tuple, dict\n The color specififcation for the faces.\n Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.\n To apply the same color to all faces, provide a single color specification.\n Individual colors can be assigned using a dictionary of key-color pairs.\n Missing keys will be assigned the default face color (``self.settings['color.faces']``).\n The default is ``None``, in which case all faces are assigned the default face color.\n join_faces : bool, optional\n Join the faces into 1 mesh.\n Default is ``False``, in which case the faces are drawn as individual meshes.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n faces = keys or list(self.mesh.faces())\n face_color = color_to_colordict(color,\n faces,\n default=self.settings['color.faces'],\n colorformat='rgb',\n normalize=False)\n facets = []\n for face in faces:\n facets.append({\n 'points': self.mesh.face_coordinates(face),\n 'name': \"{}.face.{}\".format(self.mesh.name, face),\n 'color': face_color[face]})\n\n guids = compas_rhino.draw_faces(facets, layer=self.layer, clear=False, redraw=False)\n if not join_faces:\n self.guid_face = zip(guids, faces)\n return guids\n\n guid = compas_rhino.rs.JoinMeshes(guids, delete_input=True)\n compas_rhino.rs.ObjectLayer(guid, self.layer)\n compas_rhino.rs.ObjectName(guid, '{}.mesh'.format(self.mesh.name))\n if color:\n compas_rhino.rs.ObjectColor(guid, color)\n\n self.guids += [guid]\n return [guid]\n\n def draw_edges(self, keys=None, color=None):\n \"\"\"Draw a selection of edges.\n\n Parameters\n ----------\n keys : list\n A list of edge keys (as uv pairs) identifying which edges to draw.\n The default is ``None``, in which case all edges are drawn.\n color : str, tuple, dict\n The color specififcation for the edges.\n Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.\n To apply the same color to all edges, provide a single color specification.\n Individual colors can be assigned using a dictionary of key-color pairs.\n Missing keys will be assigned the default edge color (``self.settings['color.edges']``).\n The default is ``None``, in which case all edges are assigned the default edge color.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n edges = keys or list(self.mesh.edges())\n edge_color = color_to_colordict(color,\n edges,\n default=self.settings['color.edges'],\n colorformat='rgb',\n normalize=False)\n lines = []\n for edge in edges:\n lines.append({\n 'start': self.mesh.vertex_coordinates(edge[0]),\n 'end': self.mesh.vertex_coordinates(edge[1]),\n 'color': edge_color[edge],\n 'name': \"{}.edge.{}-{}\".format(self.mesh.name, *edge)})\n\n guids = compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False)\n self.guid_edge = zip(guids, edges)\n return guids\n\n # ==========================================================================\n # normals\n # ==========================================================================\n\n def draw_vertexnormals(self, keys=None, color=None, scale=None):\n \"\"\"Draw the normals at the vertices of the mesh.\n\n Parameters\n ----------\n keys : list, optional\n A (sub)set of vertices for which the normals should be drawn.\n Default is to draw all vertex normals.\n color : str (HEX) or tuple (RGB), optional\n The color specification of the normal vectors.\n String values are interpreted as hex colors.\n Tuples are interpreted as RGB components.\n The default vector color is in the settings: ``self.settings['color.vertexnormals']``.\n scale : float, optional\n Scale factor for the vertex normals.\n Default is ``1.0``.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n vertices = keys or list(self.mesh.vertices())\n scale = scale or self.settings['scale.vertexnormals']\n color = color or self.settings['color.vertexnormals']\n\n lines = []\n for vertex in vertices:\n a = self.mesh.vertex_coordinates(vertex)\n n = self.mesh.vertex_normal(vertex)\n b = add_vectors(a, scale_vector(n, scale))\n lines.append({\n 'start': a,\n 'end': b,\n 'color': color,\n 'name': \"{}.vertexnormal.{}\".format(self.mesh.name, vertex),\n 'arrow': 'end'})\n\n guids = compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False)\n self.guid_vertexnormal = zip(guids, vertices)\n return guids\n\n def draw_facenormals(self, keys=None, color=None, scale=None):\n \"\"\"Draw the normals of the faces.\n\n Parameters\n ----------\n keys : list, optional\n A (sub)set of faces for which the normals should be drawn.\n Default is to draw all face normals.\n color : str (HEX) or tuple (RGB), optional\n The color specification of the normal vectors.\n String values are interpreted as hex colors.\n Tuples are interpreted as RGB components.\n The default vector color is in the settings: ``self.settings['color.facenormals']``.\n scale : float, optional\n Scale factor for the face normals.\n Default is ``1.0``.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n faces = keys or list(self.mesh.faces())\n scale = scale or self.settings['scale.facenormals']\n color = color or self.settings['color.facenormals']\n\n lines = []\n for face in faces:\n a = self.mesh.face_centroid(face)\n n = self.mesh.face_normal(face)\n b = add_vectors(a, scale_vector(n, scale))\n lines.append({\n 'start': a,\n 'end': b,\n 'name': \"{}.facenormal.{}\".format(self.mesh.name, face),\n 'color': color,\n 'arrow': 'end'})\n\n guids = compas_rhino.draw_lines(lines, layer=self.layer, clear=False, redraw=False)\n self.guid_facenormal = zip(guids, faces)\n return guids\n\n # ==========================================================================\n # labels\n # ==========================================================================\n\n def draw_vertexlabels(self, text=None, color=None):\n \"\"\"Draw labels for a selection vertices.\n\n Parameters\n ----------\n text : dict\n A dictionary of vertex labels as key-text pairs.\n The default value is ``None``, in which case every vertex will be labelled with its key.\n color : str, tuple, dict\n The color sepcification of the labels.\n String values are interpreted as hex colors.\n Tuples are interpreted as RGB component specifications.\n If a dictionary of specififcations is provided,\n the keys should refer to vertex keys and the values should be color specifications in the form of strings or tuples.\n The default value is ``None``, in which case the labels are assigned the default vertex color (``self.settings['color.vertices']``).\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n if text is None:\n vertex_text = {key: str(key) for key in self.mesh.vertices()}\n elif isinstance(text, dict):\n vertex_text = text\n elif text == 'key':\n vertex_text = {key: str(key) for key in self.mesh.vertices()}\n elif text == 'index':\n vertex_text = {key: str(index) for index, key in enumerate(self.mesh.vertices())}\n else:\n raise NotImplementedError\n\n vertex_color = color_to_colordict(color,\n vertex_text.keys(),\n default=self.settings['color.vertices'],\n colorformat='rgb',\n normalize=False)\n labels = []\n for vertex in vertex_text:\n labels.append({\n 'pos': self.mesh.vertex_coordinates(vertex),\n 'name': \"{}.vertexlabel.{}\".format(self.mesh.name, vertex),\n 'color': vertex_color[vertex],\n 'text': vertex_text[vertex]})\n\n guids = compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False)\n self.guid_vertexlabel = zip(guids, vertex_text.keys())\n return guids\n\n def draw_facelabels(self, text=None, color=None):\n \"\"\"Draw labels for a selection of faces.\n\n Parameters\n ----------\n text : dict\n A dictionary of face labels as key-text pairs.\n The default value is ``None``, in which case every face will be labelled with its key.\n color : str, tuple, dict\n The color sepcification of the labels.\n String values are interpreted as hex colors.\n Tuples are interpreted as RGB component specifications.\n If a dictionary of specififcations is provided,\n the keys should refer to face keys and the values should be color specifications in the form of strings or tuples.\n The default value is ``None``, in which case the labels are assigned the default face color (``self.settings['color.faces']``).\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n if text is None:\n face_text = {key: str(key) for key in self.mesh.faces()}\n elif isinstance(text, dict):\n face_text = text\n elif text == 'key':\n face_text = {key: str(key) for key in self.mesh.faces()}\n elif text == 'index':\n face_text = {key: str(index) for index, key in enumerate(self.mesh.faces())}\n else:\n raise NotImplementedError\n\n face_color = color_to_colordict(color,\n face_text.keys(),\n default=self.settings['color.faces'],\n colorformat='rgb',\n normalize=False)\n\n labels = []\n for face in face_text:\n labels.append({\n 'pos': self.mesh.face_center(face),\n 'name': \"{}.facelabel.{}\".format(self.mesh.name, face),\n 'color': face_color[face],\n 'text': face_text[face]})\n\n guids = compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False)\n self.guid_facelabel = zip(guids, face_text.keys())\n return guids\n\n def draw_edgelabels(self, text=None, color=None):\n \"\"\"Draw labels for a selection of edges.\n\n Parameters\n ----------\n text : dict\n A dictionary of edge labels as key-text pairs.\n The default value is ``None``, in which case every edge will be labelled with its key.\n color : str, tuple, dict\n The color sepcification of the labels.\n String values are interpreted as hex colors.\n Tuples are interpreted as RGB component specifications.\n Individual colors can be assigned using a dictionary of edge-color pairs.\n Missing keys will be assigned the default edge color (``self.settings['color.edges']``).\n The default is ``None``, in which case all edges are assigned the default edge color.\n\n Returns\n -------\n list\n The GUIDs of the created Rhino objects.\n\n \"\"\"\n if text is None:\n edge_text = {(u, v): \"{}-{}\".format(u, v) for u, v in self.mesh.edges()}\n elif isinstance(text, dict):\n edge_text = text\n else:\n raise NotImplementedError\n\n edge_color = color_to_colordict(color,\n edge_text.keys(),\n default=self.settings['color.edges'],\n colorformat='rgb',\n normalize=False)\n labels = []\n for edge in edge_text:\n labels.append({\n 'pos': self.mesh.edge_midpoint(*edge),\n 'name': \"{}.edgelabel.{}-{}\".format(self.mesh.name, *edge),\n 'color': edge_color[edge],\n 'text': edge_text[edge]})\n\n guids = compas_rhino.draw_labels(labels, layer=self.layer, clear=False, redraw=False)\n self.guid_edgelabel = zip(guids, edge_text.keys())\n return guids\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == \"__main__\":\n\n from compas.datastructures import Mesh\n\n mesh = Mesh.from_polyhedron(20)\n\n artist = MeshArtist(mesh)\n artist.clear()\n artist.draw_faces()\n artist.draw_vertices()\n artist.draw_edges()\n", "sub_path": "src/compas_rhino/artists/meshartist.py", "file_name": "meshartist.py", "file_ext": "py", "file_size_in_byte": 25658, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "compas_rhino.artists._artist.BaseArtist", "line_number": 19, "usage_type": "name"}, {"api_name": "compas_rhino.delete_objects", "line_number": 182, "usage_type": "call"}, {"api_name": "compas_rhino.clear_layer", "line_number": 195, "usage_type": "call"}, {"api_name": "compas.geometry.centroid_polygon", "line_number": 272, "usage_type": "call"}, {"api_name": "compas.utilities.pairwise", "line_number": 273, "usage_type": "call"}, {"api_name": "compas_rhino.draw_mesh", "line_number": 279, "usage_type": "call"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 306, "usage_type": "call"}, {"api_name": "compas_rhino.draw_points", "line_number": 318, "usage_type": "call"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 348, "usage_type": "call"}, {"api_name": "compas_rhino.draw_faces", "line_number": 360, "usage_type": "call"}, {"api_name": "compas_rhino.rs.JoinMeshes", "line_number": 365, "usage_type": "call"}, {"api_name": "compas_rhino.rs", "line_number": 365, "usage_type": "attribute"}, {"api_name": "compas_rhino.rs.ObjectLayer", "line_number": 366, "usage_type": "call"}, {"api_name": "compas_rhino.rs", "line_number": 366, "usage_type": "attribute"}, {"api_name": "compas_rhino.rs.ObjectName", "line_number": 367, "usage_type": "call"}, {"api_name": "compas_rhino.rs", "line_number": 367, "usage_type": "attribute"}, {"api_name": "compas_rhino.rs.ObjectColor", "line_number": 369, "usage_type": "call"}, {"api_name": "compas_rhino.rs", "line_number": 369, "usage_type": "attribute"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 397, "usage_type": "call"}, {"api_name": "compas_rhino.draw_lines", "line_number": 410, "usage_type": "call"}, {"api_name": "compas.geometry.add_vectors", "line_number": 449, "usage_type": "call"}, {"api_name": "compas.geometry.scale_vector", "line_number": 449, "usage_type": "call"}, {"api_name": "compas_rhino.draw_lines", "line_number": 457, "usage_type": "call"}, {"api_name": "compas.geometry.add_vectors", "line_number": 492, "usage_type": "call"}, {"api_name": "compas.geometry.scale_vector", "line_number": 492, "usage_type": "call"}, {"api_name": "compas_rhino.draw_lines", "line_number": 500, "usage_type": "call"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 541, "usage_type": "call"}, {"api_name": "compas_rhino.draw_labels", "line_number": 554, "usage_type": "call"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 591, "usage_type": "call"}, {"api_name": "compas_rhino.draw_labels", "line_number": 605, "usage_type": "call"}, {"api_name": "compas.utilities.color_to_colordict", "line_number": 638, "usage_type": "call"}, {"api_name": "compas_rhino.draw_labels", "line_number": 651, "usage_type": "call"}, {"api_name": "compas.datastructures.Mesh.from_polyhedron", "line_number": 664, "usage_type": "call"}, {"api_name": "compas.datastructures.Mesh", "line_number": 664, "usage_type": "name"}]} +{"seq_id": "468512664", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# http://117.121.55.198:55660/goods_cfg?invitedway=ad&account=13621656&pv=iphone-app&uid=13621656&ip=117.136.69.150&bid=sky&brandid=sky&brand_id=sky&flag=1.4.390bd8fa2e8393a5ee162cc26a2d479d2&v=1.4.3&invitedby=7\n\n# KC\n# http://113.31.81.100:8080/kcorders/recharge/pay/payrecord.php?brandid=kc&uid=79668095&phone=15999619371\n# http://113.31.81.100:8080/kcorders/recharge/pay/payrecord.php?brandid=kc&uid=7966809\n\n# UU\n# http://113.31.81.101:8080/uuorders/recharge/pay/payrecord.php?brandid=uu&uid=100002&phone=15999619371\n# http://113.31.81.101:8080/uuorders/recharge/pay/payrecord.php?brandid=uu&uid=100002\n\n# SKY\n# http://117.121.55.199:8080/orders/recharge/pay/payrecord.php?brandid=sky&uid=570731&phone=15999619371\n# http://117.121.55.199:8080/orders/recharge/pay/payrecord.php?brandid=sky&uid=570731\n\n# http://117.121.55.198:55660/goods_cfg?invitedway=ad&account=13621656&pv=iphone-app&uid=13621656&ip=117.136.69.150&bid=sky&brandid=sky&brand_id=sky&flag=1.4.390bd8fa2e8393a5ee162cc26a2d479d2&v=1.4.3&invitedby=7\n\n# import sys\n# sys.path.insert(1, \"/data/server/libs\")\nimport os,sys\n\n# 设置上上一级目录下的libs目录为系统路径\n# if sys.platform != 'win32':\n# \tlibs_path = os.path.join(os.path.abspath('../../'), \"libs\")\n# \tprint(\"add libs path:\", libs_path)\n# \tsys.path.insert(1, libs_path)\n#\n# sys.path.insert(1, \"/data/server/ext_libs/common_libs\")\n# sys.path.insert(1, \"/data/server/operate_events/src\")\nimport datetime\nimport random\nimport time\nimport ams\nimport dao\nimport config\nimport urllib\nfrom libs_gl import xhttp\nfrom libs_gl import xlog\nfrom libs_gl import cz_db_tools\n\n# 活动开始与结束时间\nACT_START_TIME = datetime.datetime.strptime(\"2016-07-27 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\nACT_END_TIME = datetime.datetime.strptime(\"2016-08-01 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\n\nACT_ORDER_START_TIME = datetime.datetime.strptime(\"2016-07-27 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\nACT_ORDER_END_TIME = datetime.datetime.strptime(\"2016-08-01 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\n\n\nORDER_PAYRECORD_URL = {\n\t\"kc\": \"http://113.31.81.100:8080/kcorders/recharge/pay/payrecord.php\",\n\t\"uu\": \"http://113.31.81.101:8080/uuorders/recharge/pay/payrecord.php\",\n\t\"typt\": \"http://117.121.55.199:8080/orders/recharge/pay/payrecord.php\",\n}\n\nprize_prop = {\n\t\"0\": {\n\t\t\"name\": \"【50元话费】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(2001,2501),\n\t},\n\n\t\"1\": {\n\t\t\"name\": \"【2年来显】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(4101,5101),\n\t},\n\n\t\"2\": {\n\t\t\"name\": \"【大屏手机】\",\n\t\t\"virtual_goods\": False,\n\t\t\"range\": range(6161,6171),\n\t},\n\n\t\"3\": {\n\t\t\"name\": \"【20M流量】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(2501,3501),\n\t},\n\t\"4\": {\n\t\t\"name\": \"【88元途牛旅游现金卡】\",\n\t\t\"virtual_goods\": False,\n\t\t\"range\": range(6101,6141),\n\t},\n\t\"5\": {\n\t\t\"name\": \"【100元话费】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(3501,3701),\n\t},\n\t\"6\": {\n\t\t\"name\": \"【500元出境定制旅游现金抵扣券】\",\n\t\t\"virtual_goods\": False,\n\t\t\"range\": range(5101,6101),\n\t},\n\t\"7\": {\n\t\t\"name\": \"【100M流量包】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(3701,4101),\n\t},\n\t\"8\": {\n\t\t\"name\": \"【1年来显】\",\n\t\t\"virtual_goods\": True,\n\t\t\"range\": range(1,2001),\n\t},\n\t\"9\": {\n\t\t\"name\": \"【188元途牛旅游现金卡】\",\n\t\t\"virtual_goods\": False,\n\t\t\"range\": range(6141,6161),\n\t},\n}\n\n# PRIZE_NUMS = [\n# \trange(1, 3000),\n# \trange(6101, 6150),\n# \trange(4201, 5000),\n# \trange(6176, 6178),\n# \trange(5601, 5900),\n# \trange(5901, 6100),\n# \trange(3001, 4200),\n# \trange(6151, 6170),\n# \trange(6171, 6175),\n# \trange(5001, 5600),\n# ]\n#\n# LOTTERYREASON = [\n# \t\"【5元话费】\",\n# \t\"【电子称】\",\n# \t\"【20元话费】\",\n# \t\"【7寸四核平板一部】\",\n# \t\"【50元话费】\",\n# \t\"【100M流量包】\",\n# \t\"【10元话费】\",\n# \t\"【500M流量包】\",\n# \t\"【保温杯(500ML)】\",\n# \t\"【20M流量包】\",\n# \t\"您已经没有抽奖机会咯,充值可以获得更多抽奖机会哦~\",\n# \t\"开小差了。请稍后再试!\",\n# ]\n\nLOTTERY_PROMPT = \"恭喜您获得了\"\nLOTTERY_ERROR = \"服务器开小差��。请稍后再试!\"\nLOTTERY_NO_ONE = \"您没有抽奖机会咯,充值可以获得更多抽奖机会哦~\"\n\n# 测试的UID列表\nTEST_UID_LIST = {\n\t\"kc\": [\"79668095\", \"107163047\", \"117556486\", \"113898227\"],\n\t\"uu\": [\"100002\", \"26584314\", \"26762891\"],\n\t\"sky\": [\"104927\", \"16757035\", \"16793570\"],\n\t\"4g\": [\"570731\", \"5285647\", \"5066911\"],\n\t\"3g\": [\"107449\", \"19506736\", \"19387445\"],\n\t\"feiin\": [\"182143\", \"6924043\", \"7097335\"],\n}\n\n\n# \"0\": \"name\": \"【50元话费】\",\"1\": \"name\": \"【2年来显】\",\"2\": \"name\": \"【大屏手机】\",\"3\": \"name\": \"【20M流量】\",\n# \"4\": \"name\": \"【88元途牛旅游现金卡】\",\"5\": \"name\": \"【100元话费】\",\n# \"6\": \"name\": \"【500元出境定制旅游现金抵扣券】\",\"7\": \"name\": \"【100M流量包】\",\n# \"8\": \"name\": \"【1年来显】\",\n#\"9\": \"name\": \"【188元途牛旅游现金卡】\",\n\nBRAND_GOODS_INFO = {\n\t\"kc\": {\n\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"2572\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n\t\"uu\": {\n\t\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"311\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n\t\"3g\": {\n\t\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"854\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n\t\"4g\": {\n\t\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"7004\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n\t\"sky\": {\n\t\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"697\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n\t\"feiin\": {\n\t\t\t\"goods_list\": {\n\t\t\t\"0\": {\"id\": \"1000\", \"name\": u\"【旅游季抽奖】50元话费\", \"price\": \"50\"},\n\t\t\t\"1\": {\"id\": \"2016072604\", \"name\": u\"【旅游季抽奖】2年来显\", \"price\": \"0\"},\n\t\t\t#\"3\": {\"id\": \"2016072601\", \"name\": u\"【旅游季抽奖】20M流量\", \"price\": \"0\"},\n\t\t\t\"5\": {\"id\": \"99\", \"name\": u\"【旅游季抽奖】100元话费\", \"price\": \"100\"},\n\t\t\t#\"7\": {\"id\": \"2016072602\", \"name\": u\"【旅游季抽奖】100M全国流量包\", \"price\": \"0\"},\n\t\t\t\"8\": {\"id\": \"2016072603\", \"name\": u\"【旅游季抽奖】1年来显\", \"price\": \"0\"},\n\t\t}\n\t},\n}\n\nredis_conf = {\n\t# \"host\": \"117.121.21.90\",\n\t# \"passwd\": \"AGW_redis_p@ssw0rd\",\n\t\"host\": \"127.0.0.1\",\n\t\"passwd\": \"redis_pass\",\n\t\"port\": 6379,\n\t\"redis_db_index\": 0,\n}\n\nCACHE_REDIS = None\n''':type :redis.Redis'''\n\n\ndef init_redis():\n\tglobal CACHE_REDIS\n\tCACHE_REDIS = cz_db_tools.create_redis(redis_conf['host'], redis_conf['passwd'], redis_conf['port'],\n\t\t\t\t\t\t\t\t\t\t redis_conf['redis_db_index'])\n\tif not CACHE_REDIS:\n\t\treturn False\n\treturn True\n\n\ndef query_pay_log(bid, uid):\n\t\"\"\"\n\t查询充值列表\n\t:param bid:\n\t:param uid:\n\t:param start_time:\n\t:param end_time:\n\t:return: 返回充值记录\n\t[\n\t\t{\n\t\t\t\"money\": 3000,\n\t\t\t\"src\": 11,\n\t\t\t\"orderno\": \"1000201112141409410637570731\",\n\t\t\t\"uid\": \"570731\",\n\t\t\t\"phone\": \"15831188570\",\n\t\t\t\"paytype\": \"8\",\n\t\t\t\"brandid\": \"sky\",\n\t\t\t\"utstime\": \"1323843109\",\n\t\t\t\"goodsid\": 0,\n\t\t\t\"time\": \"Dec 14, 2011 2:11:49 PM\"\n\t\t},\n\t\t{\n\t\t\t\"money\": 3000,\n\t\t\t\"src\": 54,\n\t\t\t\"orderno\": \"1000201201022041080651570731\",\n\t\t\t\"uid\": \"570731\",\n\t\t\t\"phone\": \"15831188570\",\n\t\t\t\"paytype\": \"8\",\n\t\t\t\"brandid\": \"sky\",\n\t\t\t\"utstime\": \"1325508191\",\n\t\t\t\"goodsid\": 0,\n\t\t\t\"time\": \"Jan 2, 2012 8:43:11 PM\"\n\t\t}\n\t]\n\t\"\"\"\n\n\turl = ORDER_PAYRECORD_URL.get(bid)\n\tif not url:\n\t\turl = ORDER_PAYRECORD_URL.get(\"typt\")\n\n\tif not url:\n\t\txlog.error(u\"品牌[%s]没有配置订单系统地址\" % (bid,))\n\t\treturn None\n\n\tparam = {\n\t\t\"brandid\": bid,\n\t\t\"uid\": uid,\n\t}\n\n\tres = xhttp.get(url, param, isJson=True)\n\tif not res:\n\t\treturn None\n\n\treturn res\n\n\ndef check_activity_time_range():\n\t\"\"\"\n\t校验当前时间是否在活动时间内\n\t活动还没开始,返回-1\n\t活动已经开始,返回0\n\t活动已经结束,返回1\n\t:return:\n\t\"\"\"\n\tnow_time = datetime.datetime.now()\n\tdiff_time = now_time - ACT_START_TIME\n\tif diff_time.days < 0:\n\t\t# 活动还没有开始\n\t\treturn -1\n\n\tdiff_time = now_time - ACT_END_TIME\n\tif diff_time.days > 0:\n\t\t# 活动已经结束\n\t\treturn 1\n\n\treturn 0\n\n\ndef query_recharge_money(pay_log_list, bid, uid, start_time, end_time):\n\t\"\"\"\n\t查询某个用户在时间范围[start_time,end_time]内的充值金额(不支持充值卡充值)\n\t:param pay_log_list: 通过订单系统查询的充值记录列表\n\t:param bid:\n\t:param uid:\n\t:param start_time:\n\t:param end_time:\n\t:return: 充值金额\n\t\"\"\"\n\tif not pay_log_list:\n\t\treturn 0\n\tcount = 0\n\tfor record in pay_log_list:\n\t\tif str(record.get(\"paytype\", \"0\")) in (\"98\", \"5\", \"200\"):\n\t\t\tcontinue\n\n\t\tstr_time = record.get(\"time\", \"\")\n\t\tif not str_time:\n\t\t\tcontinue\n\t\torder_time = datetime.datetime.strptime(str_time, \"%b %d, %Y %I:%M:%S %p\")\n\t\tdiff_time = order_time - ACT_ORDER_START_TIME\n\n\t\tif diff_time.days < 0:\n\t\t\t# 订单时间是在活动时间之前\n\t\t\tcontinue\n\n\t\tdiff_time = order_time - ACT_ORDER_END_TIME\n\t\tif diff_time.days > 0:\n\t\t\t# 订单时间是在活动时间之后\n\t\t\tcontinue\n\n\t\tcount = count + record.get(\"money\", 0)\n\n\treturn count\n\n\ndef query_havelottery_num(bid, uid):\n\t\"\"\"\n\t通过金额判断此时用户所拥有的抽奖次数\n\t:return:\n\t\"\"\"\n\tif bid not in BRAND_GOODS_INFO.keys():\n\t\t# 品牌不在活动品牌列表中\n\t\treturn\n\tcountNum = 0\n\ttry:\n\t\tnow_time = datetime.datetime.now()\n\t\tdiff_time = now_time - ACT_START_TIME\n\t\tif diff_time.days < 0:\n\t\t\t# 活动还没有开始\n\t\t\treturn countNum\n\n\t\tdiff_time = now_time - ACT_END_TIME\n\t\tif diff_time.days > 0:\n\t\t\t# 活动已经结束\n\t\t\treturn countNum\n\n\t\tpay_log_list = query_pay_log(bid, uid)\n\t\trechargeMoney = query_recharge_money(pay_log_list, bid, uid, ACT_START_TIME, ACT_END_TIME)\n\t\t# countNum = rechargeMoney / 10000\n\t\txlog.info(u\"用户bid[%s],uid[%s],rechargeMoney[%s]\"%(bid, uid, rechargeMoney))\n\t\tif rechargeMoney in range(10000, 20000):\n\t\t\tcountNum = 1\n\t\telif rechargeMoney in range(20000, 30000):\n\t\t\tcountNum = 3\n\t\telif rechargeMoney in range(30000, 40000):\n\t\t\tcountNum = 5\n\t\telif rechargeMoney >= 40000 :\n\t\t\tcountNum = 7\n\texcept:\n\t\txlog.error(\"\", exc_info=True)\n\treturn countNum\n\n\ndef get_user_lottery_num(bid, uid):\n\t\"\"\"\n\t获取当前用户redis里保存的抽奖次数\n\t:return:\n\t\"\"\"\n\tuseNum = CACHE_REDIS.hget(bid + \":travel_season\", bid + \"_\" + \"travel_season\" + uid + \"_uselotterynum\")\n\tif not useNum:\n\t\treturn 0\n\treturn int(useNum)\n\n\ndef set_user_lottery_num(bid, uid, userNum):\n\t\"\"\"\n\t保存用户的抽奖次数到Redis中\n\t\"\"\"\n\tCACHE_REDIS.hset(bid + \":travel_season\", bid + \"_\" + \"travel_season\" + uid + \"_uselotterynum\", userNum)\n\n\ndef decrease_prize_num(bid, uid, prize_idx):\n\t\"\"\"\n\tredis保存的奖品减少1\n\t当redis商品都被抽完的时候。返回默认5元话费的商品编号\n\t:param bid:\t品牌Id\n\t:param prize_idx: 奖品索引\n\t:return: prize_idx 返回获奖的商品编号\n\t\"\"\"\n\tprize_num_key = \"travel_season_prize_info\"\n\tkey = \"goodsnum\" + str(prize_idx)\n\tcacheNum = CACHE_REDIS.hget(prize_num_key, key)\n\txlog.info(u\"奖品[%s]剩余数[%s]\"%(prize_idx, cacheNum))\n\tif not cacheNum:\n\t\treturn -1\n\tgoodsnum = int(cacheNum)\n\tif goodsnum <= 0:\n\t\t# 抽中的商品数量全部用完。改发默认5元话费商品\n\t\tprize_idx = 0\n\n\t# 奖品可能发生变化\n\tkey = \"goodsnum\" + str(prize_idx)\n\tCACHE_REDIS.hset(prize_num_key, key, goodsnum - 1)\n\n\t# 保存用户中奖记录。保存的key规则 bid:uid:travel_season value规则 商品编号+抽奖时间\n\tCACHE_REDIS.rpush(bid + \":\" + uid + \":travel_season\",\n\t\t\t\t\t str(prize_idx) + \",\" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time())))\n\treturn prize_idx\n\n\ndef is_good_lucker(bid, uid):\n\t\"\"\"\n\t判断用户的中奖纪录中是否有现金卡或手机\n\t:param bid:\n\t:param uid:\n\t:return:\n\t\"\"\"\n\tif not (bid and uid):\n\t\txlog.error(u\"参数错误:bid[%s],uid[%s]\"%(bid, uid))\n\t\treturn True\n\tlottery_list = queryLottery_id(bid, uid)\n\tif not lottery_list:\n\t\txlog.error(u\"用户没有获奖纪录bid[%s],uid[%s]\"%(bid, uid))\n\t\treturn False\n\tfor lottery in lottery_list:\n\t\t# 判断是否中了大奖\n\t\tif int(lottery) in (2, 4, 9):\n\t\t\treturn True\n\n\treturn False\n\n\n\n\ndef get_all_prize_num():\n\t\"\"\"\n\t获取redis保存的奖品的总数\n\t当redis商品都被抽完的时候。返回默认5元话费的商品编号\n\t:param bid:\t品牌Id\n\t:return: prize_idx 返回获奖的商品编号\n\t\"\"\"\n\tprize_num_key = \"travel_season_prize_info\"\n\tkey = \"goodsnum\"\n\tgoods_sum = 0\n\tfor i in range(0, 10):\n\t\tkey_index = key + str(i)\n\t\tcacheNum = CACHE_REDIS.hget(prize_num_key, key)\n\t\tgoodsnum = int(cacheNum)\n\t\tgoods_sum += goodsnum\n\n\treturn goods_sum\n\n\n\ndef startLottery(bid, uid):\n\t\"\"\"\n\t开始抽奖\n\t1,通过订单系统,查询用户的充值记录\n\t2,计算用户的总共可以抽奖次数\n\t3,取出Redis中保存的用户已经抽奖的次数\n\t4,如果还有抽奖次数,进行抽奖\n\n\t:param bid:\n\t:param uid:\n\t:return: 抽奖结果,{\"result\": 0, \"prize_idx\": prize_idx, \"reason\": LOTTERYREASON[prize_idx]}\n\t\tresult \t\t0 接口执行错误码\n\t\tprize_idx\t1 奖品索引,-1表示没有中奖\n\t\treason\t\t抽奖结果说明\n\t:rtype : dict\n\t\"\"\"\n\ttry:\n\t\t# 校验活动时间\n\t\tres = check_activity_time_range()\n\t\tif res == -1:\n\t\t\treturn {\"result\": -2, \"prize_idx\": -1, \"reason\": u\"抽奖活动还没有开始,抽奖开始时间:%s\"%(ACT_START_TIME.strftime(\"%Y-%m-%d %H:%M:%S\")),\"have_num\":0}\n\t\tif res == 1:\n\t\t\treturn {\"result\": -3, \"prize_idx\": -1, \"reason\": u\"抽奖活动已经结束,抽奖结束时间:%s\"%(ACT_START_TIME.strftime(\"%Y-%m-%d %H:%M:%S\")),\"have_num\":0}\n\n\t\t# if(checkUserInfo(bid,uid,pwd)):\n\t\thave_num =query_havelottery_num(bid, uid)\n\t\t# 测试账号,用于设置测试次数\n\t\txlog.info(u\"用户[%s]的抽奖次数为[%s]\"%(uid, have_num, ))\n\t\tif str(uid) in ('118379946','117550105','113898227'):\n\t\t\thave_num = 100\n\t\txlog.info(u\"用户[%s]的抽奖次数为[%s]\"%(uid, have_num, ))\n\t\tif have_num == 0:\n\t\t\t# 没有抽奖机会\n\t\t\treturn {\"result\": -1, \"prize_idx\": -1, \"reason\": LOTTERY_NO_ONE, \"have_num\":0}\n\n\t\tuser_lottery_num = get_user_lottery_num(bid, uid)\n\t\txlog.info(u\"用户[%s]的抽奖次数为[%s],已抽奖次数user_lottery_num[%s]\"%(uid, have_num,user_lottery_num, ))\n\t\tif (have_num - user_lottery_num) > 0:\n\t\t\tif user_lottery_num in (0,1,):\n\t\t\t\t# pass第一,二次抽奖,手机跟旅游现金卡不在奖品种\n\t\t\t\trandom_num = random.randint(1, 6100)\n\t\t\telif user_lottery_num == 2:\n\t\t\t\t# pass第三次抽奖\n\t\t\t\trandom_num = random.randint(1, 6140)\n\t\t\telif user_lottery_num == 3:\n\t\t\t\t# 第四次抽奖\n\t\t\t\trandom_num = random.randint(1, 6170)\n\t\t\telif user_lottery_num == 4:\n\t\t\t\t# 第五次抽奖\n\t\t\t\t# 判断前四次是否中过现金卡或手机\n\t\t\t\tif is_good_lucker(bid, uid):\n\t\t\t\t\trandom_num = random.randint(1, 6100)\n\t\t\t\telse:\n\t\t\t\t\trandom_num = random.randint(1, 6170)\n\n\t\t\telif user_lottery_num == 5:\n\t\t\t\t# pass第六次抽奖\n\t\t\t\t# 如果前五次有抽中过现金卡或手机,则不能再中了\n\t\t\t\tif is_good_lucker(bid, uid):\n\t\t\t\t\trandom_num = random.randint(1,6100)\n\t\t\t\telse:\n\t\t\t\t\trandom_num = random.randint(6101, 6170)\n\t\t\telse:\n\t\t\t\trandom_num = random.randint(1,6100)\n\n\t\t\txlog.info(u\"中奖号码为random_num[%s]\"%(random_num, ))\n\t\t\tfor key, value in prize_prop.items():\n\t\t\t\ta_range = value.get(\"range\")\n\t\t\t\tif random_num in a_range:\n\t\t\t\t\tprize_idx = int(key)\n\t\t\t\t\tname = value.get(\"name\")\n\t\t\t\t\t# 设置用户抽奖次数 +1\n\t\t\t\t\tset_user_lottery_num(bid, uid, user_lottery_num + 1)\n\t\t\t\t\tprize_idx = decrease_prize_num(bid, uid, prize_idx)\n\t\t\t\t\txlog.info(u\"品牌[%s]用户[%s]抽中奖品[%s][%s],中奖次数[%d]\"%(bid,uid,key,name.decode('utf-8'),(user_lottery_num + 1),))\n\n\t\t\t\t\tif prize_idx == -1:\n\t\t\t\t\t\treturn {\"result\": -99, \"prize_idx\": -1, \"reason\": LOTTERY_ERROR,\"have_num\":0}\n\t\t\t\t\t# 判断用户是否抽中的是500优惠卷,下发激活码短信\n\t\t\t\t\tif prize_idx == 6:\n\t\t\t\t\t\tif not send_msg(bid, uid):\n\t\t\t\t\t\t\tprize_idx = 0\n\t\t\t\t\tprize_info = BRAND_GOODS_INFO.get(bid).get(\"goods_list\").get(str(prize_idx))\n\t\t\t\t\tif prize_info:\n\t\t\t\t\t\tgift_goods(bid, uid, prize_info.get(\"id\"), prize_info.get(\"price\"), prize_info.get(\"name\"))\n\t\t\t\t\txlog.info(u\"中奖的key[%s]\"%(prize_idx,))\n\t\t\t\t\treturn {\"result\": 0, \"prize_idx\": prize_idx, \"reason\": (LOTTERY_PROMPT + prize_prop.get(str(prize_idx)).get('name')),\"have_num\":have_num - user_lottery_num}\n\t\telse:\n\t\t\treturn {\"result\": -1, \"prize_idx\": -1, \"reason\": LOTTERY_NO_ONE,\"have_num\":0}\n\texcept:\n\t\txlog.error(\"\", exc_info=True)\n\treturn {\"result\": -99, \"prize_idx\": -1, \"reason\": LOTTERY_ERROR, \"have_num\": 0}\n\n\ndef gift_goods(bid, uid, goods_id, goods_id_price, remarks):\n\t'''\n\t调用发货系统,\n\t:param bid: 品牌ID\n\t:param uid: 用户uid\n\t:param goods_id: 商品ID\n\t:param goods_id_price: 商品ID价格\n\t:return:\n\t'''\n\txlog.info(u\"准备给品牌[%s]用户[%s]赠送商品[%s][%s][%s]\"%(bid,uid,str(goods_id),str(goods_id_price),remarks,))\n\ttimestamp = str(int(time.time())) + str(uid)\n\tparams = {\n\t\t'bid': bid,\n\t\t'uid': uid,\n\t\t'goods_id': goods_id,\n\t\t'orderid': timestamp,\n\t\t'paymoney': goods_id_price,\n\t\t'way': 0,\n\t\t'pv': 'android',\n\t\t'v': '3.5.0',\n\t\t'remarks': remarks,\n\t\t'operparam': '',\n\t}\n\turl = 'http://127.0.0.1:8895/exec_goods'\n\tr = xhttp.get(url, params, threads=True)\n\treturn r\n\ndef checkUserInfo(bid, uid, account_type, pwd):\n\tuserInfo = ams.user_info(bid, uid, account_type)\n\tif pwd == userInfo.get(\"password\"):\n\t\t# return True\n\t\treturn {'result': 0, 'reason': '登录成功', 'uid': userInfo.get(\"uid\")}\n\telse:\n\t\t# return False\n\t\treturn {'result': -1, 'reason': '登录失败', 'uid': None}\n\n\ndef getUserInfo(bid, uid, account_type):\n\ttry:\n\t\tuserInfo = ams.user_info(bid, uid, account_type)\n\t\treturn userInfo\n\texcept:\n\t\txlog.error(\"\",exc_info=True)\n\treturn {}\n\ndef queryLottery(bid, uid):\n\t\"\"\"\n\t:param bid:\n\t:param uid:\n\t:return:\n\t\"\"\"\n\tlottery_log = []\n\ttry:\n\t\tlist_key = bid + \":\" + uid + \":travel_season\"\n\t\tlist_len = CACHE_REDIS.llen(list_key)\n\t\tif list_len > 0:\n\t\t\tlottery_list = CACHE_REDIS.lrange(list_key, 0, list_len)\n\n\t\t\tfor list in lottery_list:\n\t\t\t\tlotteryList = str(list).split(',')\n\t\t\t\tlotteryList.append(int(lotteryList[0])+1)\n\t\t\t\tlotteryList[0] = prize_prop.get(lotteryList[0]).get(\"name\")\n\t\t\t\tlottery_log.append(lotteryList)\n\texcept:\n\t\txlog.error(\"\", exc_info=True)\n\treturn lottery_log\n\n\n\n\ndef send_msg(brandid, uid):\n\t\"\"\"\n\t下发短信验证码,并存入redis\n\t:param phone:\n\t:return:\n\t\"\"\"\n\tif not ( brandid and uid):\n\t\txlog.error(u\"传入参数错误,brandid[%s],uid[%s]\"%(brandid, uid))\n\t\treturn False\n\tuserInfo = getUserInfo(brandid, uid, 'uid')\n\tif not userInfo:\n\t\txlog.error(u\"查询用户信息失败brandid[%s],uid[%s]\"%(brandid, uid))\n\t\treturn False\n\n\t# 生成发送短信信息\n\tphone = userInfo.get('number')\n\tcode = dao.get_code()\n\tif not code:\n\t\txlog.error(u\"没有未使用的优惠劵了\")\n\t\treturn False\n\txlog.info(u\"用户brandid[%s],uid[%s],phone[%s]优惠劵[%s]\"%(brandid, uid, phone, code))\n\tcode = code.get('code')\n\tup_bid = brandid.upper()\n\tmsg_content = u\"出境游500元优惠码:%s,可下载“游心旅行管家”APP进行注册使用,谢谢支持%s电话!\"%(code,up_bid)\n\tcontent_gbk = msg_content.encode('gb2312')\n\tSMS_URL = \"%s/sms_http.php\" % (config.SMS_HOST,)\n\tparam = {\n\t\t\"act\": \"send\",\n\t\t\"username\": config.SMS_USER,\n\t\t\"passwd\": config.SMS_PASSWORD,\n\t\t\"subuser\": 90020,\n\t\t\"phone\": phone,\n\t\t\"content\": content_gbk,\n\t}\n\n\t# 下发短信\n\txlog.info(u\"下发短信消息 param[%s]\" % (param,))\n\tparam_str = urllib.urlencode(param)\n\tsms_result = xhttp.get(SMS_URL, param_str)\n\tif not sms_result or sms_result != '1000':\n\t\txlog.error(u\"下发短信失败,phone[%s]\" % (phone,))\n\t\treturn False\n\tif not dao.update_t_active_code(brandid, uid, phone, code):\n\t\txlog.error(u\"更新优惠劵的状态不成功,brandid[%s], uid[%s], phone[%s], code[%s]\"%(brandid, uid , phone, code ))\n\n\treturn True\n\n\ndef queryLottery_id(bid, uid):\n\t\"\"\"\n\t:param bid:\n\t:param uid:\n\t:return:\n\t\"\"\"\n\tlottery_log = []\n\ttry:\n\t\tlist_key = bid + \":\" + uid + \":travel_season\"\n\t\tlist_len = CACHE_REDIS.llen(list_key)\n\t\tif list_len > 0:\n\t\t\tlottery_list = CACHE_REDIS.lrange(list_key, 0, list_len)\n\n\t\t\tfor list in lottery_list:\n\t\t\t\tlotteryList = str(list).split(',')\n\t\t\t\tlottery_log.append(lotteryList[0])\n\texcept:\n\t\txlog.error(\"\", exc_info=True)\n\treturn lottery_log\n\n\ndef init_prize_param():\n\t\"\"\"\n\t初始化奖品数据到Redis中,只手动执行一次\n\n\t:return:\n\t\"\"\"\n\tinit_redis()\n\tprize_num_key = \"travel_season_prize_info\"\n\t# \"0\": {\n\t# \t\"name\": \"【50元话费】\",\n\t# \t\"range\": range(2001,2501),\n\t# },\n\t#\n\t# \"1\": {\n\t# \t\"name\": \"【2年来显】\",\n\t# \t\"range\": range(4101,5101),\n\t# },\n\t#\n\t# \"2\": {\n\t# \t\"name\": \"【大屏手机】\",\n\t# \t\"range\": range(6161,6171),\n\t# },\n\t#\n\t# \"3\": {\n\t# \t\"name\": \"【20M流量】\",\n\t# \t\"range\": range(2501,3501),\n\t# },\n\t# \"4\": {\n\t# \t\"name\": \"【88元途牛旅游现金卡】\",\n\t# \t\"range\": range(6101,6141),\n\t# },\n\t# \"5\": {\n\t# \t\"name\": \"【100元话费】\",\n\t# \t\"range\": range(3501,3701),\n\t# },\n\t# \"6\": {\n\t# \t\"name\": \"【500元出境定制旅游现金抵扣券】\",\n\t# \t\"range\": range(5101,6101),\n\t# },\n\t# \"7\": {\n\t# \t\"name\": \"【100M流量包】\",\n\t# \t\"range\": range(3701,4101),\n\t# },\n\t# \"8\": {\n\t# \t\"name\": \"【1年来显】\",\n\t# \t\"range\": range(1,2001),\n\t# },\n\t# \"9\": {\n\t# \t\"name\": \"【188元途牛旅游现金卡】\",\n\t# \t\"range\": range(6141,6161),\n\t# },\n\tgoodslist = {\n\t\t\"goodsnum0\": 500,\n\t\t\"goodsnum1\": 1000,\n\t\t\"goodsnum2\": 10,\n\t\t\"goodsnum3\": 1000,\n\t\t\"goodsnum4\": 40,\n\t\t\"goodsnum5\": 200,\n\t\t\"goodsnum6\": 1000,\n\t\t\"goodsnum7\": 400,\n\t\t\"goodsnum8\": 2000,\n\t\t\"goodsnum9\": 20,\n\t}\n\n\txlog.info(u\"首次初始化奖品数量到Redis中\")\n\tfor key, value in goodslist.items():\n\t\tCACHE_REDIS.hset(prize_num_key, key, value)\n\n\tres = CACHE_REDIS.hgetall(prize_num_key)\n\txlog.info(u\"Redis中奖品数量参数:%s\" % (res,))\n\tprint(res)\n\n\tpass\n\n\n\ndef delete_lottery_list(bid, uid):\n\tglobal CACHE_REDIS\n\tlist_key = bid + \":\" + uid + \":travel_season\"\n\tCACHE_REDIS.delete(list_key)\n\n\ndef get_prize_record():\n\tpre_list = []\n\tfor operators , pre_name in config.OPERATORS_NAME.items():\n\t\tpre_list.extend(pre_name)\n\n\tindex_list = []\n\tfor i in range(50):\n\t\tindex = random.randint(0,len(pre_list)-1)\n\t\tindex_list.append(index)\n\n\trecord_list = []\n\tfor i in index_list:\n\t\t#print pre_list[i]\n\t\tphone_pre = pre_list[i][0:3]\n\t\tj = str(random.randint(0,9))\n\t\t#print j\n\t\tprize_name = prize_prop.get(j).get('name').decode(\"utf-8\")\n\t\tphone_end = random.randint(0,9999)\n\t\tstr_record = u\"恭喜%s****%04s获得 %s。\"%(phone_pre, phone_end, prize_name)\n\t\trecord_list.append(str_record)\n\treturn record_list\n\n\nif __name__ == \"__main__\":\n\n\tinit_prize_param()\n\tset_user_lottery_num(\"kc\",'118379946',0)\n\tdelete_lottery_list(\"kc\",'118379946')\n\tset_user_lottery_num('kc','117550105',0)\n\tdelete_lottery_list('kc','117550105')\n\tset_user_lottery_num('kc','113898227',0)\n\tdelete_lottery_list('kc','113898227')\n\t'113898227'\n\t# query_havelottery_num(\"kc\", \"117966359\")\n\t# print get_prize_record()\n\t# str_time = \"Jan 2, 2012 8:43:11 AM\"\n\t# order_time = datetime.datetime.strptime(str_time,\"%b %d, %Y %I:%M:%S %p\")\n\t# print(order_time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\t# time_now = datetime.datetime.now()\n\t# print(time_now.strftime(\"%b %d, %Y %I:%M:%S %p\"))\n\t# goodslist = {\n\t# \t\"goodsnum0\": 3000,\n\t# \t\"goodsnum6\": 1200,\n\t# \t\"goodsnum2\": 800,\n\t# \t\"goodsnum9\": 600,\n\t# \t\"goodsnum4\": 300,\n\t# \t\"goodsnum5\": 200,\n\t# \t\"goodsnum7\": 50,\n\t# \t\"goodsnum1\": 20,\n\t# \t\"goodsnum8\": 5,\n\t# \t\"goodsnum3\": 3,\n\t# }\n\t#\n\t# bid = [\n\t# \t\"kc\",\n\t# \t\"uu\",\n\t# \t\"3g\",\n\t# \t\"4g\",\n\t# \t\"sky\",\n\t# \t\"feiin\",\n\t# ]\n\n\t# for brandid in bid:\n\t# \tfor goodsid in goodslist:\n\t# \t\tprint(brandid+\":travel_season\")\n\n\n\t# for brandid in bid:\n\t# \tfor goodsid in goodslist:\n\t# \t\tCACHE_REDIS.hset(brandid + \":travel_season\", goodsid, goodslist.get(goodsid))\n\t# print brandid+\":travel_season,\"+str(goodsid)+\",\"+str(goodslist.get(goodsid))\n\n\t# a = CACHE_REDIS.hget(\"kc:travel_season\",\"kc_travel_season_123456_uselotterynum\")\n\t# a = 0\n\t# print a + 1\n\t# print CACHE_REDIS.hget(\"kc:travel_season\", \"goodsnum1\")\n\t#\n\t# print CACHE_REDIS.hgetall(\"kc:123\")\n\t# print BRAND_GOODS_INFO.get(\"kc\").get(\"goods_list\").get(\"0\").get(\"id\")\n\t# m = 0\n\t# n = 1000\n\t# prize_idx0 = 0\n\t# prize_idx1 = 0\n\t# prize_idx2 = 0\n\t# prize_idx3 = 0\n\t# prize_idx4 = 0\n\t# prize_idx5 = 0\n\t# prize_idx6 = 0\n\t# prize_idx7 = 0\n\t# prize_idx8 = 0\n\t# prize_idx9 = 0\n\t# prize_idx11 = 0\n\t# while (m < n):\n\t# \tdata = startLottery(\"kc\", \"108281633\")\n\t# \tif (data.get(\"prize_idx\") == 0):\n\t# \t\tprize_idx0 = prize_idx0 + 1\n\t# \telif (data.get(\"prize_idx\") == 1):\n\t# \t\tprize_idx1 = prize_idx1 + 1\n\t# \telif (data.get(\"prize_idx\") == 2):\n\t# \t\tprize_idx2 = prize_idx2 + 1\n\t# \telif (data.get(\"prize_idx\") == 3):\n\t# \t\tprize_idx3 = prize_idx3 + 1\n\t# \telif (data.get(\"prize_idx\") == 4):\n\t# \t\tprize_idx4 = prize_idx4 + 1\n\t# \telif (data.get(\"prize_idx\") == 5):\n\t# \t\tprize_idx5 = prize_idx5 + 1\n\t# \telif (data.get(\"prize_idx\") == 6):\n\t# \t\tprize_idx6 = prize_idx6 + 1\n\t# \telif (data.get(\"prize_idx\") == 7):\n\t# \t\tprize_idx7 = prize_idx7 + 1\n\t# \telif (data.get(\"prize_idx\") == 8):\n\t# \t\tprize_idx8 = prize_idx8 + 1\n\t# \telif (data.get(\"prize_idx\") == 9):\n\t# \t\tprize_idx9 = prize_idx9 + 1\n\t# \tm = m + 1\n\t# print \"prize_idx0=\" + str(prize_idx0) + \",prize_idx1=\" + str(prize_idx1) + \",prize_idx2=\" + str(\n\t# \tprize_idx2) + \",prize_idx3=\" + str(prize_idx3) + \",prize_idx4=\" + str(prize_idx4) + \",prize_idx5=\" + str(\n\t# \tprize_idx5) + \",prize_idx6=\" + str(prize_idx6) + \",prize_idx7=\" + str(prize_idx7) + \",prize_idx8=\" + str(\n\t# \tprize_idx8) + \",prize_idx9=\" + str(prize_idx9)\n\t# print \"prize_idx0=\" + str(float(prize_idx0) / 10000) + \",prize_idx1=\" + str(\n\t# \tfloat(prize_idx1) / 10000) + \",prize_idx2=\" + str(float(prize_idx2) / 10000) + \",prize_idx3=\" + str(\n\t# \tfloat(prize_idx3) / 10000) + \",prize_idx4=\" + str(float(prize_idx4) / 10000) + \",prize_idx5=\" + str(\n\t# \tfloat(prize_idx5) / 10000) + \",prize_idx6=\" + str(float(prize_idx6) / 10000) + \",prize_idx7=\" + str(\n\t# \tfloat(prize_idx7) / 10000) + \",prize_idx8=\" + str(float(prize_idx8) / 10000) + \",prize_idx9=\" + str(\n\t# \tfloat(prize_idx9) / 10000)\n\t# print checkUserInfo(\"kc\", \"108281633\", \"uid\", \"111111\")\n\t# CACHE_REDIS.rpush(\"kc:108281633:travel_season\",\n\t# \t\t\t\t \"0\" + \",\" + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time())))\n\t# init_redis()\n\t# list_key = \"kc:108281633:travel_season\"\n\t# list_len = CACHE_REDIS.llen(\"kc:108281633:travel_season\")\n\t# lottery_list = CACHE_REDIS.lrange(list_key, 0, list_len)\n\t# lottery_log = []\n\t# for list in lottery_list:\n\t# \tlotteryList = str(list).split(',')\n\t# \tlotteryList[0] = prize_prop.get(lotteryList[0]).get(\"name\")\n\t# \tlottery_log.append(lotteryList)\n\t# \tprint lottery_log\n\tpass\n", "sub_path": "src/main/travel_season_handler.py", "file_name": "travel_season_handler.py", "file_ext": "py", "file_size_in_byte": 28461, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 43, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 46, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "attribute"}, {"api_name": "libs_gl.cz_db_tools.create_redis", "line_number": 239, "usage_type": "call"}, {"api_name": "libs_gl.cz_db_tools", "line_number": 239, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 287, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 287, "usage_type": "name"}, {"api_name": "libs_gl.xhttp.get", "line_number": 295, "usage_type": "call"}, {"api_name": "libs_gl.xhttp", "line_number": 295, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 310, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 310, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 344, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 344, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 371, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 371, "usage_type": "attribute"}, {"api_name": "libs_gl.xlog.info", "line_number": 385, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 385, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 395, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 395, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 428, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 428, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 442, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 442, "usage_type": "call"}, {"api_name": "time.time", "line_number": 442, "usage_type": "call"}, {"api_name": "libs_gl.xlog.error", "line_number": 454, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 454, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 458, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 458, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 517, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 517, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 520, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 520, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 526, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 526, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 530, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 533, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 536, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 541, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 543, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 549, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 551, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 553, "usage_type": "call"}, {"api_name": "libs_gl.xlog.info", "line_number": 555, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 555, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 564, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 564, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 575, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 575, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 580, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 580, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 593, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 593, "usage_type": "name"}, {"api_name": "time.time", "line_number": 594, "usage_type": "call"}, {"api_name": "libs_gl.xhttp.get", "line_number": 608, "usage_type": "call"}, {"api_name": "libs_gl.xhttp", "line_number": 608, "usage_type": "name"}, {"api_name": "ams.user_info", "line_number": 612, "usage_type": "call"}, {"api_name": "ams.user_info", "line_number": 623, "usage_type": "call"}, {"api_name": "libs_gl.xlog.error", "line_number": 626, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 626, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 648, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 648, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 661, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 661, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 665, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 665, "usage_type": "name"}, {"api_name": "dao.get_code", "line_number": 670, "usage_type": "call"}, {"api_name": "libs_gl.xlog.error", "line_number": 672, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 672, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 674, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 674, "usage_type": "name"}, {"api_name": "config.SMS_HOST", "line_number": 679, "usage_type": "attribute"}, {"api_name": "config.SMS_USER", "line_number": 682, "usage_type": "attribute"}, {"api_name": "config.SMS_PASSWORD", "line_number": 683, "usage_type": "attribute"}, {"api_name": "libs_gl.xlog.info", "line_number": 690, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 690, "usage_type": "name"}, {"api_name": "urllib.urlencode", "line_number": 691, "usage_type": "call"}, {"api_name": "libs_gl.xhttp.get", "line_number": 692, "usage_type": "call"}, {"api_name": "libs_gl.xhttp", "line_number": 692, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 694, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 694, "usage_type": "name"}, {"api_name": "dao.update_t_active_code", "line_number": 696, "usage_type": "call"}, {"api_name": "libs_gl.xlog.error", "line_number": 697, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 697, "usage_type": "name"}, {"api_name": "libs_gl.xlog.error", "line_number": 719, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 719, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 787, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 787, "usage_type": "name"}, {"api_name": "libs_gl.xlog.info", "line_number": 792, "usage_type": "call"}, {"api_name": "libs_gl.xlog", "line_number": 792, "usage_type": "name"}, {"api_name": "config.OPERATORS_NAME.items", "line_number": 807, "usage_type": "call"}, {"api_name": "config.OPERATORS_NAME", "line_number": 807, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 812, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 819, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 822, "usage_type": "call"}]} +{"seq_id": "569272044", "text": "import base64\nimport pickle\n\nfrom django.shortcuts import render\nfrom django_redis import get_redis_connection\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n# Create your views here.\nfrom goods.models import SKU\nfrom . import serializers\n\n\nclass CartView(APIView):\n def perform_authentication(self, request):\n pass\n\n def delete(self,request):\n serializer = serializers.CartDeleteSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n sku_id = serializer.validated_data['sku_id']\n try:\n user = request.user\n except Exception:\n user = None\n\n if user is not None and user.is_authenticated:\n redis_conn = get_redis_connection('cart')\n pl = redis_conn.pipeline()\n pl.hdel('cart_%s'%user.id,sku_id)\n pl.srem('cart_selected_%s'%user.id,sku_id)\n pl.execute()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n else:\n response = Response(status=status.HTTP_204_NO_CONTENT)\n cart = request.COOKIES.get('cart')\n if cart is not None:\n cart = pickle.loads(base64.b64decode(cart.encode()))\n print(cart)\n if sku_id in cart:\n del cart[sku_id]\n cart = base64.b64encode(pickle.dumps(cart)).decode()\n # response = Response(serializer.data)\n response.set_cookie('cart',cart,max_age=60*60*60)\n return response\n\n def put(self,request):\n serializer =serializers.CatSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n sku_id = serializer.validated_data.get('sku_id')\n count = serializer.validated_data.get('count')\n selected = serializer.validated_data.get('selected')\n try:\n user = request.user\n except Exception:\n user = None\n if user is not None and user.is_authenticated:\n #用户已登录在redis中保存\n redis_conn = get_redis_connection('cart')\n #创建reids管道\n pl = redis_conn.pipeline()\n #将商品的数量修改为传递过来的参数的数量\n pl.hset('cart_%s'%user.id,sku_id,count)\n #判断商品的勾选状态\n if selected:\n #若勾选的话,将商品的数量添加到勾选的列表中\n pl.sadd('cart_selected_%s'%user.id,sku_id)\n #不勾选的话则在商品的勾选列表中,删除商品id\n else:\n pl.srem('cart_selected_%s'%user.id,sku_id)\n #执行管道\n pl.execute()\n #返回响应对象\n return Response(serializer.data)\n #如果用户没有登录\n else:\n #从cookies中获取购物车信息\n cart = request.COOKIES.get('cart')\n #判断购物车信息是否存在\n if cart:\n #转码获取购物车信息\n cart = pickle.loads(base64.b64decode(cart.encode()))\n #若购物车不存在,则创建空的字典\n else:\n cart = {}\n #创建购物车数据\n cart[sku_id] = {\n 'count':count,\n 'selected':selected\n }\n print(cart)\n #将购物车数据转化成要往cookies中存储的数据\n cart = base64.b64encode(pickle.dumps(cart)).decode('utf-8')\n #创建相应对象\n response = Response(serializer.data)\n #将cookie写入到cookie中\n response.set_cookie('cart',cart,max_age=60*60*60)\n\n #返回相应对象\n return response\n\n def get(self,request):\n #判断用户是否登录\n try:\n user = request.user\n except Exception:\n user = None\n if user is not None and user.is_authenticated:\n #获取redis链接对象 cart\n redis_conn = get_redis_connection('cart')\n #从redis中的hash中获取所有的商品id及数量\n cart_dict = redis_conn.hgetall('cart_%s'%user.id)\n #从redis中获取所有商品的勾选状态\n select_list = redis_conn.smembers('cart_selected_%s'%user.id)\n #创建空的字典\n cart = {}\n #遍历商品数据\n for sku_id,count in cart_dict.items():\n # 形成商品字典\n cart[int(sku_id)] = {\n 'count':int(count),\n 'selected':sku_id in select_list\n }\n #用户未登录\n else:\n #从cookie中获取商品信息\n cart = request.COOKIES.get('cart')\n if cart:\n #获取购物车数据\n cart = pickle.loads(base64.b64decode(cart.encode()))\n else:\n cart = {}\n #获取所有商品的对象查询集\n skus = SKU.objects.filter(id__in=cart.keys())\n #遍历商品对象\n for sku in skus:\n #更新商品的数量��及勾选状态\n sku.count = cart[sku.id]['count']\n sku.selected = cart[sku.id]['selected']\n #序列化商品数据\n serializer = serializers.CartSKUSerializer(skus,many=True)\n #返回商品数据信息\n return Response(serializer.data)\n\n def post(self,request):\n #获取序列化器\n serializer = serializers.CatSerializer(data=request.data)\n #让序列化器校验\n serializer.is_valid(raise_exception=True)\n #获取序列化器校验后的sku_id\n sku_id = serializer.validated_data['sku_id']\n #获取序列化器校验后的count\n count = serializer.validated_data['count']\n #获取序列化器校验后的selected\n selected = serializer.validated_data['selected']\n #尝试对请求的用户进行验证\n try:\n user = request.user\n except Exception:\n user = None\n if user is not None and user.is_authenticated:\n #创建redis连接对象,连接cart\n redis_conn = get_redis_connection('cart')\n #创建管道\n pl = redis_conn.pipeline()\n #记录购物车商品数量\n pl.hincrby('cart_%s'%user.id,sku_id,count)\n #记录购物车的勾选项\n if selected:\n pl.sadd('cart_selected_%s'%user.id,sku_id)\n pl.execute()\n #成功后返回\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n else:\n #如果用户未登录\n cart = request.COOKIES.get('cart')\n #使用cookie,获取cookie中的购物车数据\n # 判断购物车是否为空\n if cart is not None:\n # 购物车不为空,获取购物车里面的数据\n cart = pickle.loads(base64.b64decode(cart.encode()))\n print(cart)\n # 购物车为空\n else:\n # 创建空字典\n cart = {}\n #查询商品是否在购物车中\n sku = cart.get(sku_id)\n if sku:\n #如果商品在购物车中则,商品数量叠加\n count +=int(sku.get('count'))\n #商品不在购物车里则创建新的商品对象\n cart[sku_id] = {\n 'count':count,\n 'selected':selected\n }\n #将商品字典进行转码\n cart = base64.b64encode(pickle.dumps(cart)).decode()\n #设置相应对象\n response = Response(serializer.data,status=status.HTTP_201_CREATED)\n #将cookis设置到相应对象中\n response.set_cookie('cart',cart,max_age=60*60*60)\n #返回相应对象\n return response\n\n", "sub_path": "meiduo_mall/meiduo_mall/apps/carts/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 7973, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 14, "usage_type": "name"}, {"api_name": "django_redis.get_redis_connection", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 33, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 35, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 35, "usage_type": "name"}, {"api_name": "pickle.loads", "line_number": 38, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 38, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 42, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 42, "usage_type": "call"}, {"api_name": "django_redis.get_redis_connection", "line_number": 59, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 74, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 82, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 82, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 93, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 95, "usage_type": "call"}, {"api_name": "django_redis.get_redis_connection", "line_number": 110, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 130, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 130, "usage_type": "call"}, {"api_name": "goods.models.SKU.objects.filter", "line_number": 134, "usage_type": "call"}, {"api_name": "goods.models.SKU.objects", "line_number": 134, "usage_type": "attribute"}, {"api_name": "goods.models.SKU", "line_number": 134, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 143, "usage_type": "call"}, {"api_name": "django_redis.get_redis_connection", "line_number": 163, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 173, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 173, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 173, "usage_type": "name"}, {"api_name": "pickle.loads", "line_number": 181, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 181, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 198, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 198, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 200, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 200, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 200, "usage_type": "name"}]} +{"seq_id": "56070443", "text": "import psutil\r\nimport os\r\nimport sys\r\nimport time\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.base import MIMEBase\r\nfrom email.mime.text import MIMEText\r\n#from email.MIMEImage import MIMEImage\r\nfrom email import encoders\r\nimport pandas as pd\r\nfrom collections import defaultdict\r\n\r\n#Server-Client email details\r\nimport json\r\n\r\nwith open('details.json') as f:\r\n data = json.load(f)\r\n\r\ndef process():\r\n\tlog_dir = \"Log\"\r\n\tif not os.path.exists(log_dir):\r\n\t\ttry:\r\n\t\t\tos.mkdir(log_dir)\r\n\t\texcept:\r\n\t\t\tpass\r\n\tseparator = '-' * 80\r\n\tct = \"\"\r\n\tcurrtime = str(time.ctime())\r\n\tfor i in currtime:\r\n\t\tif i == ':':\r\n\t\t\ti = '.'\r\n\t\tct += i\r\n\t\r\n\tlog_path = os.path.join(log_dir, \"Process Log at %s.log\" %ct)\r\n\tfd = open(log_path, 'x')\r\n\tfd.write(separator + \"\\n\")\r\n\tfd.write(\"Process Log at \"+time.ctime()+\"\\n\")\r\n\tfd.write(separator + \"\\n\")\r\n\tprocesslist = []\r\n\tpid = []\r\n\tvms = []\r\n\tname = []\r\n\r\n\t#df = pd.read_csv('LogData.csv')\r\n\r\n\r\n\tfor proc in psutil.process_iter(['pid','ppid','name','username','create_time','memory_percent','num_handles','num_threads']):\r\n\t\ttry:\r\n\t\t\tpinfo = proc.as_dict(['pid','ppid','name','username','create_time','memory_percent','num_handles','num_threads'])\r\n\t\t\t\"\"\" for pin in pinfo:\r\n\t\t\t\tprint(pin, pinfo[pin]) \"\"\"\r\n\t\t\tpinfo['vms'] = proc.memory_info().vms / (1024*1024)\r\n\t\t\tprocesslist.append(pinfo)\r\n\t\t\tpid.append(pinfo['pid'])\r\n\t\t\tvms.append(pinfo['vms'])\r\n\t\t\tname.append(pinfo['name'])\r\n\r\n\t\texcept(psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):\r\n\t\t\tpass\r\n\r\n\tmaxmem = max(vms)\r\n\tfor element in range(len(name)):\r\n\t\tif vms[element] == maxmem:\r\n\t\t\tmaxname = name[element]\r\n\t\t\tmaxpid = pid[element]\r\n\t\t\t#maxindex = element\r\n\t\t\tbreak\r\n\r\n\timport matplotlib.pyplot as plt\r\n\tplt.plot(pid, vms, 'ro')\r\n\tplt.ylabel('Memory usage in MB')\r\n\tplt.xlabel('Process ID')\r\n\tplt.title(\"Memory consumption of processes wrt their PIDs\")\r\n\tplt.annotate(maxname, (maxpid, maxmem))\r\n\tplt.savefig('GraphicalLog.png')\r\n\timg_path = 'GraphicalLog.png'\r\n\r\n\tfor element in processlist:\r\n\t\tfd.write(\"%s\\n\"%element)\r\n\r\n\tdfDict = defaultdict(list)\r\n\tfor element in processlist:\r\n\t\tfor each in element:\r\n\t\t\tdfDict[each].append(element[each])\r\n\t\r\n\tdf = pd.DataFrame(dfDict)\r\n\tdf.to_csv('LogData.csv')\r\n\t\r\n\tprint(\"Process log succesfully created at \", ct)\r\n\treturn log_path, img_path\r\n\r\ndef maillog(emailid, attachpath, img_path):\r\n\tfromaddr = data['fromEmailId']\r\n\ttoaddr = emailid\r\n\r\n\tmsg = MIMEMultipart()\r\n\r\n\tmsg['From'] = fromaddr\r\n\tmsg['To'] = toaddr\r\n\tmsg['Subject'] = \"Process Log\"\r\n\r\n\ttry:\r\n\t\tbody = \"Process Log details for Acer Predator G3-571\"\r\n\t\tmsg.attach(MIMEText(body, 'plain'))\r\n\r\n# ======================== Attaching Log File ========================\r\n\r\n\t\tlogFileName = \"ProcessLog.log\"\r\n\t\r\n\t\tlogAttachment = open(attachpath, \"rb\")\r\n\r\n\t\tlog = MIMEBase('application', 'octet-stream')\r\n\r\n\t\tlog.set_payload((logAttachment).read())\r\n\r\n\t\tencoders.encode_base64(log)\r\n\r\n\t\tlog.add_header('Content-Disposition', \"attachement; filename = %s\" %logFileName)\r\n\r\n\t\tmsg.attach(log)\r\n\r\n# ======================== Attaching CSV File ========================\r\n\r\n\t\tcsvFileName = \"LogData.csv\"\r\n\t\r\n\t\tcsvAttachment = open('LogData.csv', \"rb\")\r\n\r\n\t\tcsv = MIMEBase('application', 'octet-stream')\r\n\r\n\t\tcsv.set_payload((csvAttachment).read())\r\n\r\n\t\tencoders.encode_base64(csv)\r\n\r\n\t\tcsv.add_header('Content-Disposition', \"attachement; filename = %s\" %csvFileName)\r\n\r\n\t\tmsg.attach(csv)\r\n\r\n\r\n# ======================== Sending Mail content over SMTP ========================\r\n\r\n\t\ts = smtplib.SMTP('smtp.gmail.com', 587)\r\n\t\ts.starttls()\r\n\t\ts.login(fromaddr, data['fromPassword'])\r\n\t\ttext = msg.as_string()\r\n\t\tstart = time.time()\r\n\t\ts.sendmail(fromaddr, toaddr, text)\r\n\t\tend = time.time()\r\n\t\tprint(\"Time to send mail: \", round(end-start, 2), \"seconds\")\r\n\t\ts.quit()\r\n\texcept Exception as err:\r\n\t\tprint(\"Error: \", err)\r\n\r\ndef main():\r\n\tprint(\"Process Log mail sender: \")\r\n\tattachpath, img_path = process()\r\n\tmaillog(data['toEmailId'], attachpath, img_path)\r\n\r\nif __name__ == '__main__':\r\n\tmain()\t\r\n\r\n\r\n\"\"\"\r\nnice None\r\nmemory_full_info None\r\ncpu_percent 0.0\r\nusername NT AUTHORITY\\SYSTEM\r\nnum_handles 0\r\ncpu_affinity None\r\nmemory_maps None\r\nppid 0\r\nnum_ctx_switches pctxsw(voluntary=79186790, involuntary=0)\r\ncmdline []\r\nnum_threads 8\r\ncpu_times pcputimes(user=0.0, system=168771.703125, children_user=0.0, children_system=0.0)\r\nenviron {}\r\nmemory_info pmem(rss=8192, vms=61440, num_page_faults=9, peak_wset=12288, wset=8192, peak_paged_pool=0, paged_pool=0, peak_nonpaged_pool=272, nonpaged_pool=272, pagefile=61440, peak_pagefile=61440, private=61440)\r\nmemory_percent 4.802491532607116e-05\r\nstatus running\r\ncreate_time 1597001987.0\r\nexe None\r\npid 0\r\nionice None\r\nname System Idle Process\r\nthreads None\r\ncwd None\r\nio_counters pio(read_count=0, write_count=0, read_bytes=0, write_bytes=0, other_count=0, other_bytes=0)\r\nopen_files []\r\nconnections [pconn(fd=-1, family=, type=1, laddr=addr(ip='192.168.0.104', port=53762), raddr=addr(ip='13.74.179.117', port=443), status='TIME_WAIT'), pconn(fd=-1, family=, type=1, laddr=addr(ip='192.168.0.104', port=53763), raddr=addr(ip='52.114.77.33', port=443), status='TIME_WAIT')]\r\n\"\"\"", "sub_path": "ProcessLog.py", "file_name": "ProcessLog.py", "file_ext": "py", "file_size_in_byte": 5205, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 24, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "time.ctime", "line_number": 38, "usage_type": "call"}, {"api_name": "psutil.process_iter", "line_number": 48, "usage_type": "call"}, {"api_name": "psutil.NoSuchProcess", "line_number": 59, "usage_type": "attribute"}, {"api_name": "psutil.AccessDenied", "line_number": 59, "usage_type": "attribute"}, {"api_name": "psutil.ZombieProcess", "line_number": 59, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 82, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 87, "usage_type": "call"}, {"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 97, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 105, "usage_type": "call"}, {"api_name": "email.mime.base.MIMEBase", "line_number": 113, "usage_type": "call"}, {"api_name": "email.encoders.encode_base64", "line_number": 117, "usage_type": "call"}, {"api_name": "email.encoders", "line_number": 117, "usage_type": "name"}, {"api_name": "email.mime.base.MIMEBase", "line_number": 129, "usage_type": "call"}, {"api_name": "email.encoders.encode_base64", "line_number": 133, "usage_type": "call"}, {"api_name": "email.encoders", "line_number": 133, "usage_type": "name"}, {"api_name": "smtplib.SMTP", "line_number": 142, "usage_type": "call"}, {"api_name": "time.time", "line_number": 146, "usage_type": "call"}, {"api_name": "time.time", "line_number": 148, "usage_type": "call"}]} +{"seq_id": "321891527", "text": "from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.urls import reverse\n\nfrom .models import Habit, TodayHabitList\nfrom django.views import generic\n\n# Create your views here.\n\ndef index(request):\n\treturn render(request, 'BuildHabits/index.html')\n\ndef addHabit(request):\n\tif request.method == \"GET\":\n\t\tprint(\"addHabit get method\")\n\t\treturn render(request, 'BuildHabits/addhabit.html')\n\telif request.method == \"POST\":\n\t\ttry:\n\t\t\tnewHabit = Habit(habit_text=request.POST['activity'], occurrence=request.POST['occurrence'], date_added=timezone.localtime(getTodaysDate()))\n\t\texcept KeyError:\n\t\t\tprint(KeyError)\n\t\telse:\n\t\t\tnewHabit.save()\n\t\t\treturn render(request, 'BuildHabits/index.html')\n\n\nclass viewHabits(generic.ListView):\n\ttemplate_name = 'BuildHabits/viewhabits.html'\n\tcontext_object_name = 'allHabits'\n\n\tdef get_queryset(self):\n\t\treturn Habit.objects.order_by('-date_added')\n\nclass habitDetails(generic.DetailView):\n\tmodel = Habit\n\ttemplate_name = 'BuildHabits/habitdetails.html'\n\ndef viewToday(request):\n\ttoday = getTodaysDate()\n\tcheckhabits = TodayHabitList.objects.filter(track_date=today)\n\tif(request.method == \"GET\"):\n\t\ttodayshabits=[]\n\t\tif len(checkhabits) == 0:\n\t\t\thabits = Habit.objects.all()\n\t\t\tfor currHabit in habits:\n\t\t\t\thabit_date = currHabit.date_added\n\t\t\t\tif((habit_date-today).days % currHabit.occurrence == 0):\n\t\t\t\t\tnewHabitToday = TodayHabitList.objects.create(habit_id=currHabit.id,track_date=today, completed=False)\n\t\t\t\t\t# Line 50: Trying to create a database entry into the TodayHabitList table with the parent's id from Habit table\n\t\t\t\t\ttodayshabits.append(newHabitToday)\n\t\telse:\n\t\t\ttodayshabits = checkhabits\n\t\treturn render(request,'BuildHabits/viewtoday.html', {'todayshabits':todayshabits})\n\n\telif(request.method == \"POST\"):\n\t\tcheckboxTicked = request.POST.getlist('checkbox')\n\t\tfor i in checkhabits:\n\t\t\tif str(i.id) in checkboxTicked:\n\t\t\t\ti.completed = True\n\t\t\telse:\n\t\t\t\ti.completed = False\n\t\t\ti.save()\n\n\t\treturn HttpResponseRedirect(reverse('buildhabits:viewtoday'))\n\n\n# A method to get the current date with time set to 0\ndef getTodaysDate():\n\treturn timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)\n\n\nclass editHabitDetails(generic.DetailView):\n\tmodel = Habit\n\ttemplate_name = 'BuildHabits/edithabitdetails.html'\n\t# template_name = 'BuildHabits/viewtoday.html'\n\t# context_object_name = 'todayshabits'\n\n\t# def get_queryset(self):\n\t# \treturn Habit.objects.order_by('-date_added')\n\n#def habitDetails(request, habit_id):\n#\thabit = get_object_or_404(Habit, pk=habit_id)\n#\treturn render(request, 'BuildHabits/habitdetails.html', {'habit': habit})\n", "sub_path": "BuildHabits/views.pyt", "file_name": "views.pyt", "file_ext": "pyt", "file_size_in_byte": 2718, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.shortcuts.render", "line_number": 12, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 17, "usage_type": "call"}, {"api_name": "models.Habit", "line_number": 20, "usage_type": "call"}, {"api_name": "django.utils.timezone.localtime", "line_number": 20, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 20, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 25, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.views.generic", "line_number": 28, "usage_type": "name"}, {"api_name": "models.Habit.objects.order_by", "line_number": 33, "usage_type": "call"}, {"api_name": "models.Habit.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "models.Habit", "line_number": 33, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.views.generic", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Habit", "line_number": 36, "usage_type": "name"}, {"api_name": "models.TodayHabitList.objects.filter", "line_number": 41, "usage_type": "call"}, {"api_name": "models.TodayHabitList.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "models.TodayHabitList", "line_number": 41, "usage_type": "name"}, {"api_name": "models.Habit.objects.all", "line_number": 45, "usage_type": "call"}, {"api_name": "models.Habit.objects", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.Habit", "line_number": 45, "usage_type": "name"}, {"api_name": "models.TodayHabitList.objects.create", "line_number": 49, "usage_type": "call"}, {"api_name": "models.TodayHabitList.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.TodayHabitList", "line_number": 49, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 54, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 65, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 65, "usage_type": "call"}, {"api_name": "django.utils.timezone.localtime", "line_number": 70, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 70, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 70, "usage_type": "call"}, {"api_name": "django.views.generic.DetailView", "line_number": 73, "usage_type": "attribute"}, {"api_name": "django.views.generic", "line_number": 73, "usage_type": "name"}, {"api_name": "models.Habit", "line_number": 74, "usage_type": "name"}]} +{"seq_id": "298950043", "text": "import random\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom secondapp.models import PartQuestion, Contact_Us, Register, Question, AnswerQuestion, Result, \\\n Question_Lang, Education, SchoolRegister, Science, Language\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nimport datetime\nimport time\nfrom django.core.mail import EmailMessage, send_mail\nfrom django.utils import timezone\n\n\ndef index(request):\n context={}\n data = Question_Lang.objects.filter(id=1)\n for start in data:\n time=start.start_time\n current_time = timezone.now()\n start = time-current_time\n day=str(start)[:2]\n hour=str(start)[9:11]\n minute=str(start)[12:14]\n secund=str(start)[15:17]\n\n context={'day':day,'hour':hour,'minute':minute,'secund':secund}\n return render(request, 'index.html',context)\n\n\n# About template uchun\n\ndef aboutpage(request):\n return render(request, 'about.html')\n\n\n# Contact_Page template uchun\n\n\ndef contactpage(request):\n # bazadagi malumotlarni bitta ozgaruvchiga ozlashtrib templatega junatish\n\n # Post qilib malumotlarni bazaga saqlash\n if request.method == 'POST':\n country_cod = '+998'\n # post orqali jonatilvotgan qiymatlarni ozgaruvchilarga ozlashtirish\n name = request.POST['name']\n contact = request.POST['contact']\n email = request.POST['email']\n subject = request.POST['subject']\n message = request.POST['message']\n contact_number = country_cod + contact\n\n data = Contact_Us(name=name, contact_number=contact_number,\n email=email, subject=subject,\n message=message) # Bazadagi tablelar nomini bizadagi yani post dagi qiymatlarni tenglash\n data.save() # post orqali junatilvotgan qiymatlarni bazaga saqlash\n\n res = f\"Hurmatli {name} Fikringiz uchun katta rahmat 😊\"\n\n return render(request, \"index.html\", {'status': res})\n\n return render(request, 'contact.html')\n\n\n# Ruyxatdan otish qismi uchun Post orqali bazaga yuklash\n\ndef register(request):\n country_cod = '+998'\n if request.method == 'POST': # post orqali jonatilvotgan qiymatlarni ozgaruvchilarga ozlashtirish\n fname = request.POST['fname']\n lname = request.POST['lname']\n gender = request.POST['gtype']\n birth = request.POST['birth']\n uname = request.POST['uname']\n password1 = request.POST['password1']\n password2 = request.POST['password2']\n email = request.POST['email']\n cnumber = request.POST['pnumber']\n st = request.POST['state']\n prov = request.POST['province']\n ct = request.POST['district']\n train_center = request.POST['train_center']\n mobnumber = country_cod + cnumber\n mobnumber2 = str(mobnumber[4:6] + '***' + mobnumber[9:13])\n print(mobnumber2)\n usr = User.objects.create_user(uname, email, password1)\n usr.first_name = fname\n usr.last_name = lname\n usr.sert_id = \"%05i\" % (usr.id,)\n usr.save()\n reg = Register(user=usr, gender=gender, dateofbirth=birth,\n contact_number=mobnumber, state=st, provin=prov, city=ct, balance=True,\n training_center=train_center, contact_number2=mobnumber2)\n # Bazadagi tablelar nomini bizadagi yani post dagi qiymatlarni tenglash\n reg.sert_id = \"%05i\" % (usr.id,)\n reg.save() # post orqali junatilvotgan qiymatlarni bazaga saqlash\n\n return render(request, 'register.html',\n {'status': 'Tabriklaymiz! Hurmatli , {} Siz ro`yxatdan muvaffaqiyatli o`tdingiz'.format(fname)})\n # else:\n # messages.info(request, 'Password not matching')\n # return render(request,'register.html')\n\n return render(request, 'register.html')\n\n\n# Login qismi uchun username va passwordni bazadagi malumotlar bn solishtirish\ndef check_user(request):\n if request.method == 'GET':\n un = request.GET['usern']\n check = User.objects.filter(username=un)\n if len(check) == 1:\n return HttpResponse('Exists')\n else:\n return HttpResponse('No exists')\n\n\ndef user_login(request):\n if request.method == 'POST':\n un = request.POST['email']\n pwd = request.POST['password']\n\n user = authenticate(username=un, password=pwd)\n if user:\n login(request, user)\n if user.is_superuser:\n return HttpResponseRedirect('/admin')\n elif user.is_staff:\n return HttpResponseRedirect('/teacher_dash')\n else:\n res = HttpResponseRedirect('/')\n if 'rememberme' in request.POST:\n res.set_cookie('user__id', user.id)\n res.set_cookie('date_login', datetime.datetime.now())\n return res\n\n else:\n return render(request, 'index.html', {'status': 'Foydaluvchi nomi yoki paroli xato'})\n\n return HttpResponse('called')\n\n\n@login_required\ndef student_dash(request):\n data = Register.objects.get(user__id=request.user.id)\n return render(request, 'student_dashboard.html', {'data': data})\n\n\n@login_required\ndef teacher_dash(request):\n data = SchoolRegister.objects.get(creator__id=request.user.id)\n return render(request, 'teacher_dashboard.html', {'data': data})\n\n\n@login_required\ndef user_logout(request):\n logout(request)\n res = HttpResponseRedirect('/')\n res.delete_cookie('user_id')\n res.delete_cookie('date_login')\n return res\n\n\ndef edit_profile(request):\n context = {}\n data = Register.objects.get(user__id=request.user.id)\n context = {'data': data}\n if request.method == 'POST':\n fn = request.POST['fname']\n ln = request.POST['lname']\n em = request.POST['email']\n con = request.POST['contact']\n ct = request.POST['city']\n gen = request.POST['gender']\n occ = request.POST['occ']\n abt = request.POST['about']\n\n usr = User.objects.get(id=request.user.id)\n usr.first_name = fn\n usr.last_name = ln\n usr.email = em\n usr.save()\n\n data.contact_number = con\n data.city = ct\n data.gender = gen\n data.occupation = occ\n data.about = abt\n\n data.save()\n\n if \"image\" in request.FILES:\n img = request.FILES[\"image\"]\n data.profile_pic = img\n data.save()\n\n context['status'] = 'O`zgarishlar muvaffaqiyatli saqlandi'\n return render(request, 'edit_profile.html', context)\n\n\ndef edit_profile_teacher(request):\n context = {}\n data = SchoolRegister.objects.get(creator__id=request.user.id)\n context = {'data': data}\n if request.method == 'POST':\n sn = request.POST['sname']\n pn = request.POST['provin']\n add = request.POST['address']\n science = request.POST['science']\n lang = request.POST['lang']\n contact = request.POST['contact']\n state = request.POST['state']\n website = request.POST['website']\n telegram = request.POST['telegram']\n youtube = request.POST['youtube']\n facebook = request.POST['facebook']\n instagram = request.POST['instagram']\n email = request.POST['email']\n\n usr = User.objects.get(id=request.user.id)\n usr.first_name =sn\n usr.email = email\n usr.save()\n\n data.contact_number = contact\n data.provin = pn\n data.address = add\n data.science = science\n data.lang = lang\n data.state = state\n data.website = website\n data.youtube = youtube\n data.facebook = facebook\n data.instagram = instagram\n data.telegram = telegram\n data.save()\n\n context['status'] = 'O`zgarishlar muvaffaqiyatli saqlandi'\n return render(request, 'edit_profile_teacher.html',context)\n\n\ndef languages(request):\n langs = Question_Lang.objects.all()\n context = {'data': langs}\n if request.method == 'POST':\n name_lang = request.POST['langs']\n user = request.user\n reg = Register.objects.get(user=request.user.id)\n balance = reg.balance\n is_exists = Result.objects.filter(\n user_id=user.id, question_langid__name_lang=name_lang).exists()\n langs = Question_Lang.objects.get(name_lang=name_lang)\n question = Question.objects.filter(question_langid=langs).exists()\n start_time = langs.start_time.strftime(\"%m/%d/%Y, %H:%M:%S\")\n end_time = langs.end_time.strftime(\"%m/%d/%Y, %H:%M:%S\")\n current_time = datetime.datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n if is_exists:\n messages.error(\n request, f'Siz oldin {langs} ga doir testni yechib bo`lgansiz')\n else:\n if question == 0:\n messages.error(\n request, f'{langs} Tez orada 2021 yil uchun')\n elif (balance < 50000):\n messages.error(\n request, f'Hisobingizda yetarli miqdorda pul {balance} yo`q      To`lov qiling')\n elif current_time < start_time:\n messages.error(\n request, f'Imtixon soat {start_time} da boshlanadi')\n elif current_time > end_time:\n messages.error(\n request, f'Kechirasiz,Imtixon soat {end_time} da yakunlandi.')\n else:\n return redirect('rules', name_lang=name_lang)\n return render(request, 'languages.html', context)\n\n\ndef rules(request, name_lang):\n context = {}\n name_lang = Question_Lang.objects.get(name_lang=name_lang)\n print(name_lang)\n if request.method == 'POST':\n din = request.POST['din']\n print(din)\n if din == 'Islom':\n messages.error(\n request,\n f\"

Alloh taolo Nahil surasining 105-oyatida marhamat qiladi.

«Yolg`onni faqat Allohning oyatlariga imon keltirmaydiganlargina to`qirlar. Ana o`shalar o`zlari yolg`onchilardir», degan.

Shunday ekan siz ham ustoz yoki do`stlarning yordamisiz faqat o`z bilmingizga tayangan holda sinovdan o`ting.

Hurmatli foydalanuvchi rostgo`y bo`ling! Testni mustaqil o`zingiz yeching!


  
\"\n )\n elif din == 'Xristian':\n messages.error(\n request,\n f\"Ayub 15:31

Behuda narsalarga umid bog`lab,o`zlarini aldamasinlar,ularning mukofoti o`sha behuda narsalar bo`ladi.

Ayub 15:32

Vaqti soati yetmay turib, ular to`liq jazo oladilar,novdalari gullab-yashnamaydi.

Hurmatli foydalanuvchi rostgo`y bo`ling! Testni mustaqil o`zingiz yeching!


  
\"\n )\n elif din == 'Yahudiy':\n messages.error(\n request,\n f\"

Hurmatli foydalanuvchi rostgo`y bo`ling! Testni mustaqil o`zingiz yeching!


  
\"\n )\n else:\n messages.error(\n request,\n f\"

Hurmatli foydalanuvchi rostgo`y bo`ling! Testni mustaqil o`zingiz yeching!


  
\"\n )\n return render(request, 'rules.html', context)\n\n\n@login_required\ndef exam_page(request, name_lang):\n user = User.objects.filter(id=request.user.id)\n reg = Register.objects.get(user_id=request.user.id)\n balance = reg.balance\n question_lang = Question_Lang.objects.get(name_lang=name_lang)\n audio = Question_Lang.objects.filter(name_lang=name_lang)\n current_time = timezone.now()\n start_time = question_lang.start_time\n end_time = question_lang.end_time\n leftime = end_time - current_time\n context = {}\n if start_time < current_time and end_time > current_time:\n global t\n x = time.strptime(str(leftime).split('.')[0], '%H:%M:%S')\n t = int(datetime.timedelta(hours=x.tm_hour,\n minutes=x.tm_min, seconds=x.tm_sec).total_seconds())\n for z in audio:\n audio = z.audio\n datapart = PartQuestion.objects.filter(question_langid=question_lang)\n data = Question.objects.filter(question_langid=question_lang)\n context = {'data': data, 'datapart': datapart,\n 'name_lang': name_lang, 'audio': audio, 'dif_time': t}\n if request.method == 'POST':\n user = request.user\n for item in data:\n try:\n res = request.POST[f'optradio{item.id}']\n if res in item.answer:\n difference = balance - 50000\n reg.balance = difference\n reg.save()\n\n result = AnswerQuestion.objects.create(\n ansa=res, question_id_id=item.id, user_id=user, is_true=True, question_langid=question_lang)\n else:\n result = AnswerQuestion.objects.create(\n ansa=res, question_id_id=item.id, user_id=user, is_true=False,\n question_langid=question_lang)\n except:\n result = AnswerQuestion.objects.create(\n ansa='zero', question_id_id=item.id, user_id=user, is_true=False, question_langid=question_lang)\n result.save()\n return redirect('result', name_lang=name_lang)\n return render(request, 'exam.html', context)\n\n\n@login_required\ndef result(request, name_lang):\n ball = 3.5\n user = User.objects.filter(id=request.user.id).first()\n is_exists = Result.objects.filter(user_id=user, question_langid__name_lang=name_lang).exists()\n if is_exists:\n return redirect('/')\n else:\n register = Register.objects.get(user=request.user)\n question_lang = Question_Lang.objects.get(name_lang=name_lang)\n data = Question.objects.filter(question_langid=question_lang)\n answers = AnswerQuestion.objects.filter(\n user_id=user.id, question_langid=question_lang, is_true=True)\n num_an = len(answers)\n num_qu = len(data)\n score = num_an * ball\n context = {'user': user.last_name + ' ' + user.first_name, 'email': user.email}\n result = Result.objects.create(\n user_id=user, total_questions=num_qu, correct_answers=num_an, result=score,\n question_langid=question_lang, register_id=register)\n result.save()\n return render(request, 'result.html', context)\n\n\n@login_required\ndef change_password(request):\n context = {}\n ch = Register.objects.filter(user__id=request.user.id)\n if len(ch) > 0:\n data = Register.objects.get(user__id=request.user.id)\n context = {'data': data}\n if request.method == 'POST':\n current = request.POST['cpwd']\n newpass = request.POST['npwd']\n\n user = User.objects.get(id=request.user.id)\n un = user.username\n check = user.check_password(current)\n if check == True:\n user.set_password(newpass)\n user.save()\n context['msz'] = 'Parol muvaffaqiyatli yangilandi!!!'\n context['col'] = 'alert alert-success'\n user = User.objects.get(username=un)\n login(request, user)\n else:\n context['msz'] = 'Amaldagi Parol Xato'\n context['col'] = 'alert alert-danger'\n return render(request, 'change_password.html', context)\n\n\n@login_required\ndef sendemail(request):\n context = {}\n user = User.objects.get(id=request.user.id)\n if user.is_superuser:\n if request.method == 'POST':\n rec = request.POST['to'].split(',')\n sub = request.POST['sub']\n msz = request.POST['msz']\n try:\n em = EmailMessage(sub, msz, to=rec)\n em.send()\n context['status'] = 'Xabar muvaffaqiyatli yuborildi'\n context['cls'] = 'alert-success'\n except:\n context[\n 'status'] = 'Xabar yuborish amalga oshmadi.Iltimos internetingizni tekshirib qaytadan xarakat qilib ko`ring'\n context['cls'] = 'alert-danger'\n return render(request, 'sendemail.html', context)\n\n\ndef forgotpass(request):\n context = {}\n if request.method == \"POST\":\n un = request.POST[\"username\"]\n pwd = request.POST[\"npass\"]\n\n user = get_object_or_404(User, username=un)\n user.set_password(pwd)\n user.save()\n\n login(request, user)\n if user.is_superuser:\n return HttpResponseRedirect(\"/admin\")\n else:\n return HttpResponseRedirect(\"/student_dash\")\n # context[\"status\"] = \"Password Changed Successfully!!!\"\n\n return render(request, \"forgot_pass.html\", context)\n\n\ndef reset_password(request):\n username = request.GET[\"username\"]\n try:\n user = get_object_or_404(User, username=username)\n otp = random.randint(1000, 9999)\n msz = \"Janob/Honim {} \\n{} sizning bir martalik tasdiqlash kodingiz \\nBuni hech kimga ko`rsatmang \\nRahmat va Ehtirom bilan \\nAction.uz Jamoasi\".format(\n user.username, otp)\n try:\n email = EmailMessage(\"Account Tekshirish\", msz, to=[user.email])\n email.send()\n return JsonResponse({\"status\": \"sent\", \"email\": user.email, \"rotp\": otp})\n except:\n return JsonResponse({\"status\": \"error\", \"email\": user.email})\n except:\n return JsonResponse({\"status\": \"failed\"})\n\n\ndef result_section(request):\n provinces = ['Toshkent', 'Andijon', 'Buxoro', 'Fargʻona', 'Jizzax', 'Namangan',\n 'Xorazm', 'Navoiy', 'Qashqadaryo', 'Qoraqalpogʻiston', 'Samarqand', 'Sirdaryo', 'Surxondaryo']\n data = Question_Lang.objects.all()\n context = {'data': data, 'provinces': provinces}\n if request.method == 'POST':\n name_lang = request.POST['langs']\n province = request.POST['province']\n is_exists = Result.objects.filter(\n question_langid__name_lang=name_lang, register_id__provin=province).exists()\n if is_exists:\n return redirect('result_view', name_lang=name_lang, province=province)\n\n else:\n messages.error(\n request,\n f'{province} viloyati bo`yicha hech kim {name_lang} bo`yicha testda qatnashmagan'\n )\n return render(request, 'result_section.html', context)\n\n\ndef result_section_country(request):\n data = Question_Lang.objects.all()\n context = {'data': data}\n if request.method == 'POST':\n name_lang = request.POST['langs']\n is_exists = Result.objects.filter(\n question_langid__name_lang=name_lang).exists()\n if is_exists:\n return redirect('result_view_country', name_lang=name_lang)\n else:\n messages.error(\n request, f' Hech kim {name_lang} bo`yicha testda qatnashmagan'\n )\n return render(request, 'result_section_country.html', context)\n\n\ndef result_view(request, name_lang, province):\n results = Result.objects.filter(\n question_langid__name_lang=name_lang, register_id__provin=province)\n data = Result.objects.filter(\n question_langid__name_lang=name_lang)\n context = {'data': results, 'resultes': data}\n return render(request, 'result_view.html', context)\n\n\ndef result_view_country(request, name_lang):\n data = Result.objects.filter(question_langid__name_lang=name_lang)\n context = {'data': data}\n return render(request, 'result_view_country.html', context)\n\n\ndef place_number(request):\n data = []\n provinces = ['Toshkent', 'Andijon', 'Buxoro', 'Fargʻona', 'Jizzax', 'Namangan',\n 'Xorazm', 'Navoiy', 'Qashqadaryo', 'Qoraqalpogʻiston', 'Samarqand', 'Sirdaryo', 'Surxondaryo']\n langs = Question_Lang.objects.all()\n for provin in provinces:\n print(provin)\n for lang in langs:\n results = Result.objects.filter(\n register_id__provin=provin, question_langid__name_lang=lang.name_lang).order_by('result').reverse()\n print(results)\n data.append(results)\n for index, result in enumerate(results):\n result.place_number = index + 1\n result.save()\n\n context = {'data': data}\n return redirect('/success')\n return render(request, 'place_number.html', context)\n\n\ndef place_number_country(request):\n data = []\n langs = Question_Lang.objects.all()\n for lang in langs:\n results = Result.objects.filter(\n question_langid__name_lang=lang.name_lang).order_by('result').reverse()\n data.append(results)\n for index, result in enumerate(results):\n result.place_number_country = index + 1\n result.save()\n\n context = {'data': data}\n return redirect('/success')\n return render(request, 'place_number_country.html', context)\n\n\ndef success(request):\n return render(request, 'success.html')\n\n\ndef search(request):\n context = {}\n if request.method == 'GET':\n query = request.GET['username']\n queryn=query.capitalize()\n edu=SchoolRegister.objects.filter(school_name=queryn)\n data = Result.objects.filter(user_id__username=queryn)\n is_exists = Result.objects.filter(user_id__username=queryn).exists()\n if is_exists:\n context = {'data': data,'query':queryn}\n elif edu:\n context = {'edu': edu,'query':queryn}\n else:\n messages.error(\n request,\n f'Kechirasiz, {queryn} bu so`rov bo`yicha xech qanday ma`lumot topilmadi .'\n )\n\n return render(request, 'search.html', context)\n\n\ndef news(request):\n return render(request, 'news.html')\n\n\ndef education_center(request):\n context={}\n edu_center=[]\n data_provin=[]\n data = SchoolRegister.objects.all() \n provinces = ['Toshkent', 'Andijon', 'Buxoro', 'Fargʻona', 'Jizzax', 'Namangan',\n 'Xorazm', 'Navoiy', 'Qashqadaryo', 'Qoraqalpogʻiston', 'Samarqand', 'Sirdaryo', 'Surxondaryo']\n for provin in provinces:\n data_provin.append(provin)\n if request.method=='POST':\n name=request.POST['pro']\n edu_center=SchoolRegister.objects.filter(provin=name)\n \n context = {'data': data,'data_provin':data_provin,'edu_center':edu_center}\n return render(request, 'education_center.html', context)\n\n\ndef register_corporate(request):\n country_cod = '+998'\n science = Science.objects.all()\n lang = Language.objects.all()\n context = {'data': science, 'lang': lang}\n if request.method == 'POST': # post orqali jonatilvotgan qiymatlarni ozgaruvchilarga ozlashtirish\n schoolname = request.POST['schoolname']\n science = request.POST.getlist('science')\n science1 = request.POST['science']\n print(science1)\n lang_ = request.POST.getlist('slang')\n print(lang_)\n uname = request.POST['uname']\n password1 = request.POST['password1']\n password2 = request.POST['password2']\n email = request.POST['email']\n cnumber = request.POST['pnumber']\n st = request.POST['state']\n prov = request.POST['province']\n website=request.POST['website']\n address = request.POST['address']\n mobnumber = country_cod + cnumber\n mobnumber2 = str(mobnumber[4:6] + '***' + mobnumber[9:13])\n usr = User.objects.create_user(uname, email, password1)\n usr.first_name = schoolname\n # usr.last_name = lname\n usr.save()\n reg = SchoolRegister.objects.create(creator=usr, contact_number=mobnumber, state=st, provin=prov,\n contact_number2=mobnumber2, science=science, lang=lang_,\n address=address, school_name=schoolname,website=website)\n if \"image\" in request.FILES:\n img = request.FILES[\"image\"]\n reg.school_logo = img\n reg.save()\n return render(request, 'register_corporate.html',\n {'status': 'Tabriklaymiz! Hurmatli , {} Siz ro`yxatdan muvaffaqiyatli o`tdingiz'.format(\n schoolname)})\n\n return render(request, 'register_corporate.html', context)\n\ndef topic(request):\n return render(request,'topik.html')\n\ndef ielts(request):\n return render(request,'ielts.html')\n\ndef hsk(request):\n return render(request,'hsk.html')\n\ndef act(request):\n return render(request,'act.html')\n\ndef ap(request):\n return render(request,'ap.html')\n\ndef ept(request):\n return render(request,'ept.html')\n\ndef cae(request):\n return render(request,'cae.html')\n\ndef caeli(request):\n return render(request,'caeli.html')\n\ndef duolingo(request):\n return render(request,'duolingo.html')\n\ndef gmat(request):\n return render(request,'gmat.html')\n\ndef jlpt(request):\n return render(request,'jlpt.html')\n\ndef klat(request):\n return render(request,'klat.html')\n\ndef cefr(request):\n return render(request,'cefr.html')\n\ndef sat(request):\n return render(request,'sat.html')\n\ndef toefl(request):\n return render(request,'toefl.html')\n\ndef gre(request):\n return render(request,'gre.html')\n\ndef psat(request):\n return render(request,'psat.html')", "sub_path": "secondapp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 26662, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "secondapp.models.Question_Lang.objects.filter", "line_number": 18, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 18, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 21, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 21, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 29, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 35, "usage_type": "call"}, {"api_name": "secondapp.models.Contact_Us", "line_number": 55, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 62, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 64, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 88, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 88, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 88, "usage_type": "name"}, {"api_name": "secondapp.models.Register", "line_number": 93, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 100, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 106, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 113, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 113, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 113, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 115, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 117, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 125, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 127, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 129, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 131, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 133, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 136, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 136, "usage_type": "attribute"}, {"api_name": "django.shortcuts.render", "line_number": 140, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 142, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 147, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 147, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 147, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 148, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 145, "usage_type": "name"}, {"api_name": "secondapp.models.SchoolRegister.objects.get", "line_number": 153, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 153, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 153, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 154, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 151, "usage_type": "name"}, {"api_name": "django.contrib.auth.logout", "line_number": 159, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 160, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 157, "usage_type": "name"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 168, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 168, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 168, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 180, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 180, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 180, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 200, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects.get", "line_number": 205, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 205, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 205, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 222, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 222, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 222, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 241, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.all", "line_number": 245, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 245, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 245, "usage_type": "name"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 250, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 250, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 250, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 252, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 252, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 252, "usage_type": "name"}, {"api_name": "secondapp.models.Question_Lang.objects.get", "line_number": 254, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 254, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 254, "usage_type": "name"}, {"api_name": "secondapp.models.Question.objects.filter", "line_number": 255, "usage_type": "call"}, {"api_name": "secondapp.models.Question.objects", "line_number": 255, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question", "line_number": 255, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 258, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 258, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.error", "line_number": 260, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 260, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 264, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 264, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 267, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 267, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 270, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 270, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 273, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 273, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 276, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 277, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.get", "line_number": 282, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 282, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 282, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 288, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 288, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 293, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 293, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 298, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 298, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 303, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 303, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 307, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 312, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 312, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 312, "usage_type": "name"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 313, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 313, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 313, "usage_type": "name"}, {"api_name": "secondapp.models.Question_Lang.objects.get", "line_number": 315, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 315, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 315, "usage_type": "name"}, {"api_name": "secondapp.models.Question_Lang.objects.filter", "line_number": 316, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 316, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 316, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 317, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 317, "usage_type": "name"}, {"api_name": "time.strptime", "line_number": 324, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 325, "usage_type": "call"}, {"api_name": "secondapp.models.PartQuestion.objects.filter", "line_number": 329, "usage_type": "call"}, {"api_name": "secondapp.models.PartQuestion.objects", "line_number": 329, "usage_type": "attribute"}, {"api_name": "secondapp.models.PartQuestion", "line_number": 329, "usage_type": "name"}, {"api_name": "secondapp.models.Question.objects.filter", "line_number": 330, "usage_type": "call"}, {"api_name": "secondapp.models.Question.objects", "line_number": 330, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question", "line_number": 330, "usage_type": "name"}, {"api_name": "secondapp.models.AnswerQuestion.objects.create", "line_number": 343, "usage_type": "call"}, {"api_name": "secondapp.models.AnswerQuestion.objects", "line_number": 343, "usage_type": "attribute"}, {"api_name": "secondapp.models.AnswerQuestion", "line_number": 343, "usage_type": "name"}, {"api_name": "secondapp.models.AnswerQuestion.objects.create", "line_number": 346, "usage_type": "call"}, {"api_name": "secondapp.models.AnswerQuestion.objects", "line_number": 346, "usage_type": "attribute"}, {"api_name": "secondapp.models.AnswerQuestion", "line_number": 346, "usage_type": "name"}, {"api_name": "secondapp.models.AnswerQuestion.objects.create", "line_number": 350, "usage_type": "call"}, {"api_name": "secondapp.models.AnswerQuestion.objects", "line_number": 350, "usage_type": "attribute"}, {"api_name": "secondapp.models.AnswerQuestion", "line_number": 350, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 353, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 354, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 310, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 360, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 360, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 360, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 361, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 361, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 361, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 363, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 365, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 365, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 365, "usage_type": "name"}, {"api_name": "secondapp.models.Question_Lang.objects.get", "line_number": 366, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 366, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 366, "usage_type": "name"}, {"api_name": "secondapp.models.Question.objects.filter", "line_number": 367, "usage_type": "call"}, {"api_name": "secondapp.models.Question.objects", "line_number": 367, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question", "line_number": 367, "usage_type": "name"}, {"api_name": "secondapp.models.AnswerQuestion.objects.filter", "line_number": 368, "usage_type": "call"}, {"api_name": "secondapp.models.AnswerQuestion.objects", "line_number": 368, "usage_type": "attribute"}, {"api_name": "secondapp.models.AnswerQuestion", "line_number": 368, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.create", "line_number": 374, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 374, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 374, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 378, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 357, "usage_type": "name"}, {"api_name": "secondapp.models.Register.objects.filter", "line_number": 384, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 384, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 384, "usage_type": "name"}, {"api_name": "secondapp.models.Register.objects.get", "line_number": 386, "usage_type": "call"}, {"api_name": "secondapp.models.Register.objects", "line_number": 386, "usage_type": "attribute"}, {"api_name": "secondapp.models.Register", "line_number": 386, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 392, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 392, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 392, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 400, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 400, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 400, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 401, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 405, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 381, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 411, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 411, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 411, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 418, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 426, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 408, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 435, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 435, "usage_type": "argument"}, {"api_name": "django.contrib.auth.login", "line_number": 439, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 441, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 443, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 446, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 452, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 452, "usage_type": "argument"}, {"api_name": "random.randint", "line_number": 453, "usage_type": "call"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 457, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 459, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 461, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 463, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.all", "line_number": 469, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 469, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 469, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 474, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 474, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 474, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 477, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 480, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 480, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 484, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.all", "line_number": 488, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 488, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 488, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 492, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 492, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 492, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 495, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 497, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 497, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 500, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 504, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 504, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 504, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 506, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 506, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 506, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 509, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 513, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 513, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 513, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 515, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.all", "line_number": 522, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 522, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 522, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 526, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 526, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 526, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 535, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 536, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects.all", "line_number": 541, "usage_type": "call"}, {"api_name": "secondapp.models.Question_Lang.objects", "line_number": 541, "usage_type": "attribute"}, {"api_name": "secondapp.models.Question_Lang", "line_number": 541, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 543, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 543, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 543, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 551, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 552, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 556, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects.filter", "line_number": 564, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 564, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 564, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 565, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 565, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 565, "usage_type": "name"}, {"api_name": "secondapp.models.Result.objects.filter", "line_number": 566, "usage_type": "call"}, {"api_name": "secondapp.models.Result.objects", "line_number": 566, "usage_type": "attribute"}, {"api_name": "secondapp.models.Result", "line_number": 566, "usage_type": "name"}, {"api_name": "django.contrib.messages.error", "line_number": 572, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 572, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 577, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 581, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects.all", "line_number": 588, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 588, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 588, "usage_type": "name"}, {"api_name": "secondapp.models.SchoolRegister.objects.filter", "line_number": 595, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 595, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 595, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 598, "usage_type": "call"}, {"api_name": "secondapp.models.Science.objects.all", "line_number": 603, "usage_type": "call"}, {"api_name": "secondapp.models.Science.objects", "line_number": 603, "usage_type": "attribute"}, {"api_name": "secondapp.models.Science", "line_number": 603, "usage_type": "name"}, {"api_name": "secondapp.models.Language.objects.all", "line_number": 604, "usage_type": "call"}, {"api_name": "secondapp.models.Language.objects", "line_number": 604, "usage_type": "attribute"}, {"api_name": "secondapp.models.Language", "line_number": 604, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 624, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 624, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 624, "usage_type": "name"}, {"api_name": "secondapp.models.SchoolRegister.objects.create", "line_number": 628, "usage_type": "call"}, {"api_name": "secondapp.models.SchoolRegister.objects", "line_number": 628, "usage_type": "attribute"}, {"api_name": "secondapp.models.SchoolRegister", "line_number": 628, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 635, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 639, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 642, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 645, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 648, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 651, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 654, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 657, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 660, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 663, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 666, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 669, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 672, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 675, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 678, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 681, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 684, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 687, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 690, "usage_type": "call"}]} +{"seq_id": "552824615", "text": "from django.shortcuts import render, redirect\nfrom django.views import View\nfrom apps.suara import forms\nfrom apps.suara import models\nfrom apps.kecamatan.models import Kecamatan\nfrom apps.kelurahan.models import Kelurahan\nfrom apps.partai.models import Partai\nfrom apps.caleg.models import Caleg\nfrom apps.tps.models import Tps\nfrom apps.suara.models import Suara\nfrom .forms import SuaraForm\n\nfrom django.views.generic import FormView\n\nfrom braces.views import LoginRequiredMixin, SuperuserRequiredMixin\n\nfrom django.http import HttpResponse\n# Create your views here.\n\n\nclass TambahSuaraView(LoginRequiredMixin, SuperuserRequiredMixin, View):\n login_url = '/login'\n template_name = 'tambah_suara.html'\n\n def get(self, request):\n form = forms.SuaraForm(request.POST)\n partai = Partai.objects.all()\n caleg = Caleg.objects.all()\n kecamatan = Kecamatan.objects.all()\n kelurahan = Kelurahan.objects.all()\n tps = Tps.objects.all()\n suara = Suara.objects.all()\n\n return render(request, self.template_name, {\n \"form\": form,\n \"partai\": partai,\n \"caleg\": caleg,\n \"kecamatan\": kecamatan,\n \"kelurahan\": kelurahan,\n \"tps\": tps,\n \"suara\": suara,\n\n })\n\n\nclass SuaraView(LoginRequiredMixin, SuperuserRequiredMixin, View):\n login_url = '/login'\n template_name = 'suara.html'\n\n def get(self, request):\n form = forms.SuaraForm(request.POST)\n suara = models.Suara.objects.all()\n\n return render(request, self.template_name, {\n \"form\": form,\n \"suaras\": suara,\n })\n\n\nclass SaveSuaraView(LoginRequiredMixin, View):\n login_url = '/login'\n\n def post(self, request):\n form = forms.SuaraForm(request.POST, request.FILES)\n if form.is_valid():\n # pt_id = form.cleaned_data['partai']\n # partai = Partai.objects.get(id=pt_id)\n\n # kc_id =form.cleaned_data['kecamatan']\n # kecamatan = Kecamatan.objects.get(id=kc_id)\n\n # tp_id = form.cleaned_data['tps']\n # tps = Tps.objects.get(id = tp_id)\n\n # ca_id = form.cleaned_data['caleg']\n # caleg = Caleg.objects.get(id = ca_id)\n\n suara = models.Suara()\n suara.partai = form.cleaned_data['partai']\n suara.caleg = form.cleaned_data['caleg']\n suara.kecamatan = form.cleaned_data['kecamatan']\n suara.kelurahan = form.cleaned_data['kelurahan']\n print(suara.kelurahan)\n suara.tps = form.cleaned_data['tps']\n suara.jumlah_suara = form.cleaned_data['jumlah_suara']\n if request.FILES.getlist('pict'):\n suara.pict = request.FILES.getlist('pict')\n suara.save()\n\n return redirect('/suara')\n return HttpResponse(form.errors)\n\n\nclass EditSuaraView(LoginRequiredMixin, SuperuserRequiredMixin, View):\n login_url = '/login'\n template_name = 'edit_suara.html'\n\n def get(self, request, id):\n obj = Suara.objects.get(id=id)\n data = {\n 'id': obj.id,\n 'partai': obj.caleg.partai,\n 'caleg': obj.caleg,\n 'kecamatan': obj.kecamatan,\n 'kelurahan': obj.kelurahan,\n 'tps': obj.tps,\n 'jumlah_suara': obj.jumlah_suara,\n 'pict': obj.pict\n }\n\n form = forms.SuaraForm(initial=data)\n suara = Suara.objects.all()\n\n return render(request, self.template_name, {\n 'form': form,\n 'suara': suara\n })\n\n\nclass UpdateSuaraView(LoginRequiredMixin, SuperuserRequiredMixin, View):\n login_url = '/login'\n\n def post(self, request):\n form = forms.SuaraForm(request.POST)\n if form.is_valid():\n suara = Suara.objects.get(id=form.cleaned_data['id'])\n suara.partai = form.cleaned_data['partai']\n suara.caleg = form.cleaned_data['caleg']\n suara.kecamatan = form.cleaned_data['kecamatan']\n suara.kelurahan = form.cleaned_data['kelurahan']\n suara.tps = form.cleaned_data['tps']\n suara.jumlah_suara = form.cleaned_data['jumlah_suara']\n if request.FILES.getlist('pict'):\n suara.pict = request.FILES.getlist('pict')\n suara.save(force_update=True)\n\n return redirect('/suara')\n\n\nclass DeleteSuaraView(LoginRequiredMixin, SuperuserRequiredMixin, View):\n login_url = '/login'\n\n def get(self, request, id):\n obj = Suara.objects.get(id=id)\n obj.delete()\n\n return redirect('/suara')\n\n# relawan\n\n\n \n", "sub_path": "apps/suara/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4645, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "braces.views.LoginRequiredMixin", "line_number": 21, "usage_type": "name"}, {"api_name": "braces.views.SuperuserRequiredMixin", "line_number": 21, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 21, "usage_type": "name"}, {"api_name": "apps.suara.forms.SuaraForm", "line_number": 26, "usage_type": "call"}, {"api_name": "apps.suara.forms", "line_number": 26, "usage_type": "name"}, {"api_name": "apps.partai.models.Partai.objects.all", "line_number": 27, "usage_type": "call"}, {"api_name": "apps.partai.models.Partai.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "apps.partai.models.Partai", "line_number": 27, "usage_type": "name"}, {"api_name": "apps.caleg.models.Caleg.objects.all", "line_number": 28, "usage_type": "call"}, {"api_name": "apps.caleg.models.Caleg.objects", "line_number": 28, "usage_type": "attribute"}, {"api_name": "apps.caleg.models.Caleg", "line_number": 28, "usage_type": "name"}, {"api_name": "apps.kecamatan.models.Kecamatan.objects.all", "line_number": 29, "usage_type": "call"}, {"api_name": "apps.kecamatan.models.Kecamatan.objects", "line_number": 29, "usage_type": "attribute"}, {"api_name": "apps.kecamatan.models.Kecamatan", "line_number": 29, "usage_type": "name"}, {"api_name": "apps.kelurahan.models.Kelurahan.objects.all", "line_number": 30, "usage_type": "call"}, {"api_name": "apps.kelurahan.models.Kelurahan.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "apps.kelurahan.models.Kelurahan", "line_number": 30, "usage_type": "name"}, {"api_name": "apps.tps.models.Tps.objects.all", "line_number": 31, "usage_type": "call"}, {"api_name": "apps.tps.models.Tps.objects", "line_number": 31, "usage_type": "attribute"}, {"api_name": "apps.tps.models.Tps", "line_number": 31, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.all", "line_number": 32, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "apps.suara.models.Suara", "line_number": 32, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}, {"api_name": "braces.views.LoginRequiredMixin", "line_number": 46, "usage_type": "name"}, {"api_name": "braces.views.SuperuserRequiredMixin", "line_number": 46, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 46, "usage_type": "name"}, {"api_name": "apps.suara.forms.SuaraForm", "line_number": 51, "usage_type": "call"}, {"api_name": "apps.suara.forms", "line_number": 51, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.all", "line_number": 52, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara", "line_number": 52, "usage_type": "attribute"}, {"api_name": "apps.suara.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 54, "usage_type": "call"}, {"api_name": "braces.views.LoginRequiredMixin", "line_number": 60, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 60, "usage_type": "name"}, {"api_name": "apps.suara.forms.SuaraForm", "line_number": 64, "usage_type": "call"}, {"api_name": "apps.suara.forms", "line_number": 64, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara", "line_number": 78, "usage_type": "call"}, {"api_name": "apps.suara.models", "line_number": 78, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 90, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 91, "usage_type": "call"}, {"api_name": "braces.views.LoginRequiredMixin", "line_number": 94, "usage_type": "name"}, {"api_name": "braces.views.SuperuserRequiredMixin", "line_number": 94, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 94, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.get", "line_number": 99, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara.objects", "line_number": 99, "usage_type": "attribute"}, {"api_name": "apps.suara.models.Suara", "line_number": 99, "usage_type": "name"}, {"api_name": "apps.suara.forms.SuaraForm", "line_number": 111, "usage_type": "call"}, {"api_name": "apps.suara.forms", "line_number": 111, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.all", "line_number": 112, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara.objects", "line_number": 112, "usage_type": "attribute"}, {"api_name": "apps.suara.models.Suara", "line_number": 112, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 114, "usage_type": "call"}, {"api_name": "braces.views.LoginRequiredMixin", "line_number": 120, "usage_type": "name"}, {"api_name": "braces.views.SuperuserRequiredMixin", "line_number": 120, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 120, "usage_type": "name"}, {"api_name": "apps.suara.forms.SuaraForm", "line_number": 124, "usage_type": "call"}, {"api_name": "apps.suara.forms", "line_number": 124, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.get", "line_number": 126, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara.objects", "line_number": 126, "usage_type": "attribute"}, {"api_name": "apps.suara.models.Suara", "line_number": 126, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 137, "usage_type": "call"}, {"api_name": "braces.views.LoginRequiredMixin", "line_number": 140, "usage_type": "name"}, {"api_name": "braces.views.SuperuserRequiredMixin", "line_number": 140, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 140, "usage_type": "name"}, {"api_name": "apps.suara.models.Suara.objects.get", "line_number": 144, "usage_type": "call"}, {"api_name": "apps.suara.models.Suara.objects", "line_number": 144, "usage_type": "attribute"}, {"api_name": "apps.suara.models.Suara", "line_number": 144, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 147, "usage_type": "call"}]} +{"seq_id": "142375453", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 06 10:14:53 2017\n\n@author: theri\n\"\"\"\n\nimport cv2\nimport os, os.path\nfrom sys import argv\n\nscript, filename, angle = argv\n\n\n\nos.chdir('c:/Python27/Trevor_timelapse/')\n\n\nimg = cv2.imread(filename)\n#cv2.imshow('original', img)\n#cv2.waitKey(0)\n \n\n\nrows,cols = img.shape[:2]\nM = cv2.getRotationMatrix2D((cols/2, rows/2),-float(angle),1)\ndst = cv2.warpAffine(img,M,(cols,rows))\ncv2.namedWindow('rotated', cv2.WINDOW_NORMAL)\ncv2.imshow('rotated', dst)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n", "sub_path": "rotate_ht.py", "file_name": "rotate_ht.py", "file_ext": "py", "file_size_in_byte": 531, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 12, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "424242119", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nm = 128\nexperi_n = 5000\nstep_n = 30\nperiod_n = 2\ntotal_step = step_n*period_n\nq = 16\nloglamb = np.linspace(0,period_n, total_step)\nlamb = np.power(q, loglamb)\noffset = np.power(q, np.linspace(0, 1, m, endpoint=False))\nresult = np.zeros((total_step, experi_n))\n\nfor n,scale in enumerate(lamb):\n for i in range(experi_n):\n sketch = np.random.exponential(1/scale, size=(m)) * offset\n logsketch = np.ceil(-np.log(sketch)/np.log(q))\n esti = m/np.sum(np.power(q,-logsketch)/offset)\n result[n,i] = esti/scale\n\n# avg = np.mean(result,axis=1)\n# result = result/avg[:,None]\navg = np.mean(result)\nresult = result/avg\n\n\nplt.figure()\nplt.rcParams.update({'font.size': 15})\nfor n,scale in enumerate(loglamb):\n plt.scatter(np.ones(experi_n)*scale, result[n], color='black', s=0.1)\n\nplt.title('q='+str(q)+' with uniform offsets')\nplt.xlabel(r'$\\log_q\\lambda$')\nplt.ylabel('relative error')\nplt.ylim([0,2.5])\n\nplt.tight_layout()\nplt.savefig('q_'+str(q)+'_uniform.jpg')", "sub_path": "hll_uniform.py", "file_name": "hll_uniform.py", "file_ext": "py", "file_size_in_byte": 1037, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.linspace", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.random.exponential", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.ceil", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 29, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}]} +{"seq_id": "443235021", "text": "import json\n\nconfig = None\nclass Config:\n config_dict = None\n\n def load_from_file(self):\n print(\"loading config from file\")\n try:\n with open(\"config.json\") as config_file:\n self.config_dict = json.load(config_file)\n except FileNotFoundError:\n print(\"Could not file config.json!\")\n exit(0)\n except json.decoder.JSONDecodeError as e:\n print(\"Could not parse config.json\")\n print(e)\n\n def get(self, *args):\n config_pointer = self.config_dict\n for a in args:\n if a not in config_pointer:\n return None\n config_pointer = config_pointer[a]\n return config_pointer\n\n\nif config is None:\n config = Config()\n config.load_from_file()\n", "sub_path": "conf.py", "file_name": "conf.py", "file_ext": "py", "file_size_in_byte": 792, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 11, "usage_type": "call"}, {"api_name": "json.decoder", "line_number": 15, "usage_type": "attribute"}]} +{"seq_id": "392239877", "text": "\"\"\"\n============\n3D animation\n============\n\nA simple example of an animated plot... In 3D!\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport matplotlib.animation as animation\nimport pandas as pd\n\ndef Gen_RandLine(length, dims=2):\n \"\"\"\n Create a line using a random walk algorithm\n\n length is the number of points for the line.\n dims is the number of dimensions the line has.\n \"\"\"\n lineData = np.empty((dims, length))\n lineData[:, 0] = np.random.rand(dims) # 初始化起点\n for index in range(1, length):\n # scaling the random numbers by 0.1 so\n # movement is small compared to position.\n # subtraction by 0.5 is to change the range to [-0.5, 0.5]\n # to allow a line to move backwards.\n step = ((np.random.rand(dims) - 0.5) * 0.1) # 步长\n # 下一步的位置\n lineData[:, index] = lineData[:, index - 1] + step\n\n return lineData # 返回一个shape为(3,25)的数组,3维坐标25帧\n\n\ndef update_lines(num, dataLines, lines):\n for line, data in zip(lines, dataLines):\n # NOTE: there is no .set_data() for 3 dim data...\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n return lines\n\nplt.rcParams['font.family'] = ['sans-serif']\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n# Attaching 3D axis to the figure\nfig = plt.figure()\nax = p3.Axes3D(fig)\n\n# Fifty lines of random 3-D lines (长为50的数组,每个元素为shape为3,25的ndarray,最后实际效果就是50条路径)\n# data = [Gen_RandLine(25, 3) for index in range(50)]\n# print(np.array(data).shape)\ndf1 = pd.read_csv(\"20日相关.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf2 = pd.read_csv(\"20日涨幅.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf3 = pd.read_csv(\"20日交易.csv\", engine=\"python\", encoding=\"utf-8\").dropna()\ndf1.set_index(\"date\", drop=True, inplace=True)\ndf2.set_index(\"date\", drop=True, inplace=True)\ndf3.set_index(\"date\", drop=True, inplace=True)\ndf1=df1['2020':]\ndf2=df2['2020':]\ndf3=df3['2020':]\n\ndata=[]\nfor column in df1.columns:\n try:\n # d1=(df1[column].values-np.min(df1[column].values))/(np.max(df1[column].values)-np.min(df1[column].values))\n # d2=(df2[column].values-np.min(df2[column].values))/(np.max(df2[column].values)-np.min(df2[column].values))\n # d3=(df3[column].values-np.min(df3[column].values))/(np.max(df3[column].values)-np.min(df3[column].values))\n d1=df1[column].values-0\n d2=df2[column].values-0\n d3=df3[column].values-0\n dt=np.array([d1,d2,d3])\n print(d3)\n data.append(dt)\n except :\n continue\n# Creating fifty line objects.\n# NOTE: Can't pass empty arrays into 3d version of plot()\nlines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data[:20]] # 每条路径的起始点\n\n# Setting the axes properties\nax.set_xlabel('相关')\nax.set_xlim(-0.5,1)\nax.set_ylabel('涨跌')\nax.set_ylim(-0.75,1)\nax.set_zlabel('收益')\nax.set_zlim(-0.75,0.75)\n\n\n\nax.set_title('3D Test')\n\n# Creating the Animation object\nline_ani = animation.FuncAnimation(fig, update_lines, 199, fargs=(data, lines),\n interval=200, blit=False,repeat=False)\n\nplt.show()", "sub_path": "三维时空 直接.py", "file_name": "三维时空 直接.py", "file_ext": "py", "file_size_in_byte": 3319, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.empty", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 42, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 43, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 44, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "mpl_toolkits.mplot3d.axes3d.Axes3D", "line_number": 47, "usage_type": "call"}, {"api_name": "mpl_toolkits.mplot3d.axes3d", "line_number": 47, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 53, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}]} +{"seq_id": "310629416", "text": "DEBUG = 8\n\nimport argparse\nimport numpy as np\nimport os\nfrom os.path import dirname\nimport torch\nimport torchvision\nfrom torch.utils.tensorboard import SummaryWriter\nimport tqdm\n\nif DEBUG>0:\n from utils.models1 import Classifier\nelse:\n from utils.models import Classifier\nfrom utils.dataset import NCaltech101\nfrom utils.loader import Loader\nfrom utils.train_eval import train_one_epoch, eval_one_epoch\n\nif DEBUG==9:\n import time\n seed = int( time.time())\n print(\"Seed: %d\" % seed)\n random.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n\ndef FLAGS():\n parser = argparse.ArgumentParser(\"\"\"Train classifier using a learnt quantization layer.\"\"\")\n\n # training / validation dataset\n parser.add_argument(\"--validation_dataset\", default=\"\", required=True)\n parser.add_argument(\"--training_dataset\", default=\"\", required=True)\n\n # Event frame dimension\n parser.add_argument(\"--height\", type=int, default=180)\n parser.add_argument(\"--width\", type=int, default=240)\n\n # logging options\n parser.add_argument(\"--log_dir\", default=\"\", required=True)\n\n # loader and device options\n parser.add_argument(\"--device\", default=\"cuda:0\")\n parser.add_argument(\"--num_workers\", type=int, default=4)\n parser.add_argument(\"--pin_memory\", type=bool, default=True)\n parser.add_argument(\"--batch_size\", type=int, default=8)\n\n parser.add_argument(\"--num_epochs\", type=int, default=300)\n parser.add_argument(\"--save_every_n_epochs\", type=int, default=5)\n\n flags = parser.parse_args()\n\n assert os.path.isdir(dirname(flags.log_dir)), f\"Log directory root {dirname(flags.log_dir)} not found.\"\n assert os.path.isdir(flags.validation_dataset), f\"Validation dataset directory {flags.validation_dataset} not found.\"\n assert os.path.isdir(flags.training_dataset), f\"Training dataset directory {flags.training_dataset} not found.\"\n\n print(f\"----------------------------\\n\"\n f\"Starting training with \\n\"\n f\"height: {flags.height}\\n\"\n f\"width: {flags.width}\\n\"\n f\"num_epochs: {flags.num_epochs}\\n\"\n f\"batch_size: {flags.batch_size}\\n\"\n f\"device: {flags.device}\\n\"\n f\"log_dir: {flags.log_dir}\\n\"\n f\"training_dataset: {flags.training_dataset}\\n\"\n f\"validation_dataset: {flags.validation_dataset}\\n\"\n f\"num_workers: {flags.num_workers}\\n\"\n f\"pin_memory: {flags.pin_memory}\\n\"\n f\"----------------------------\")\n\n return flags\n\nif __name__ == '__main__':\n flags = FLAGS()\n dim = (flags.height, flags.width)\n\n # datasets, add augmentation to training set\n training_dataset = NCaltech101(flags.training_dataset, augmentation=True, resolution=dim)\n validation_dataset = NCaltech101(flags.validation_dataset, resolution=dim)\n\n datasetClasses = training_dataset.getClasses()\n\n # construct loader, handles data streaming to gpu\n training_loader = Loader(training_dataset, flags, device=flags.device)\n validation_loader = Loader(validation_dataset, flags, device=flags.device)\n\n # model, and put to device\n model = Classifier(device=flags.device, dimension=dim)\n model = model.to(flags.device)\n\n # optimizer and lr scheduler\n optimizerSelect = 'adam'\n if optimizerSelect == 'sgd':\n optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-4, momentum=0.9, weight_decay=1e-5)\n elif optimizerSelect == 'adam':\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, 0.5)\n\n iteration = 0\n min_validation_loss = 1000\n\n for i in range(flags.num_epochs):\n \n print(f\"Training step [{i:3d}/{flags.num_epochs:3d}]\")\n model = model.train()\n model.setMode(0)\n training_loss, training_accuracy, iteration = train_one_epoch(model, flags.device, optimizer, training_loader, iteration)\n print(f\"Training Iteration {iteration:5d} Loss {training_loss:.4f} Accuracy {training_accuracy:.4f}\")\n\n if i%10 == 9:\n if optimizerSelect == 'adam':\n lr_scheduler.step()\n\n if i%5 == 0:\n print(f\"Validation step [{i:3d}/{flags.num_epochs:3d}]\")\n model = model.eval()\n model.setMode(1)\n validation_loss, validation_accuracy = eval_one_epoch(model, flags.device, validation_loader)\n print(f\"Validation Loss {validation_loss:.4f} Accuracy {validation_accuracy:.4f}\")\n \n if validation_loss < min_validation_loss:\n min_validation_loss = validation_loss\n state_dict = model.state_dict()\n torch.save({\n \"state_dict\": state_dict,\n \"min_val_loss\": min_validation_loss,\n \"iteration\": iteration\n }, \"log/model_best.pth\")\n print(\"New best at \", validation_loss)\n if i % flags.save_every_n_epochs == 0:\n state_dict = model.state_dict()\n torch.save({\n \"state_dict\": state_dict,\n \"min_val_loss\": min_validation_loss,\n \"iteration\": iteration\n }, \"log/checkpoint_%05d_%.4f.pth\" % (iteration, min_validation_loss))", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5306, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "time.time", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "utils.dataset.NCaltech101", "line_number": 78, "usage_type": "call"}, {"api_name": "utils.dataset.NCaltech101", "line_number": 79, "usage_type": "call"}, {"api_name": "utils.loader.Loader", "line_number": 84, "usage_type": "call"}, {"api_name": "utils.loader.Loader", "line_number": 85, "usage_type": "call"}, {"api_name": "utils.models.Classifier", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 94, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.ExponentialLR", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 97, "usage_type": "attribute"}, {"api_name": "utils.train_eval.train_one_epoch", "line_number": 107, "usage_type": "call"}, {"api_name": "utils.train_eval.eval_one_epoch", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 124, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 132, "usage_type": "call"}]} +{"seq_id": "442221346", "text": "from google.appengine.ext import db\n\nclass User(db.Model):\n \"\"\"user\n\n username\n projects - list of projects\n \"\"\"\n username = db.StringProperty()\n projects = db.ListProperty(db.Key)\n\n\nclass Project(db.Model):\n \"\"\"user's project\"\"\"\n name = db.StringProperty(required=True)\n description = db.TextProperty(default=\"\")\n graph_url = db.TextProperty(default=\"\")\n url = db.URLProperty(required=True)\n\n # projects of given user\n @property\n def projects(self):\n return User.gql(\"WHERE projects = :1\", self.key()) # pass key of the instance, get user\n\nclass Visit(db.Model):\n date = db.DateTimeProperty(auto_now_add=True)\n user = db.ReferenceProperty(User,\n verbose_name='user')\n\ndef add_visit(username):\n \"\"\"insert visit to datastore\"\"\"\n visit = Visit()\n\n user = User.gql('WHERE username = :1', username).get()\n if not user:\n user = User()\n user.username = username\n user.put()\n\n visit.user = user.key()\n visit.put()", "sub_path": "models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1031, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "google.appengine.ext.db.Model", "line_number": 3, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db", "line_number": 3, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.StringProperty", "line_number": 9, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 9, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.ListProperty", "line_number": 10, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 10, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.Key", "line_number": 10, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db.Model", "line_number": 13, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db", "line_number": 13, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.StringProperty", "line_number": 15, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 15, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.TextProperty", "line_number": 16, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 16, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.TextProperty", "line_number": 17, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 17, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.URLProperty", "line_number": 18, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 18, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.Model", "line_number": 25, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.db", "line_number": 25, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.DateTimeProperty", "line_number": 26, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 26, "usage_type": "name"}, {"api_name": "google.appengine.ext.db.ReferenceProperty", "line_number": 27, "usage_type": "call"}, {"api_name": "google.appengine.ext.db", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "79324687", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 20 19:39:30 2018\n\n@author: Akshay\n\"\"\"\n\n# data generator\nimport os \nimport numpy as np\nimport pickle\nimport random\nimport re\nimport collections\ndef batch_gen(batch_size,folder,feature_shape,target_shape,c,val):\n beta=list(set(os.listdir(folder))-set(val))[:-3]\n batch_features=np.zeros([batch_size,*feature_shape])\n batch_target=np.zeros([batch_size,*target_shape])\n coll=pickle.load(open(r\"sorted_no_of_data2.plk\",\"rb\"))\n l=beta.copy()\n print(\"train:-\",len(beta))\n print(\"val:-\",len(val))\n gama=[re.findall(r\"\\D+\",x)[0] for x in val]\n print(collections.Counter(gama))\n while True:\n if len(l)==0:\n l=beta.copy()\n try:\n batch=random.sample(l,batch_size)\n except ValueError:\n batch=l.copy()\n l=list(set(l)-set(batch))\n \n for i,j in enumerate(batch):\n alpha=open(r\"{0}/{1}\".format(folder,j),\"rb\")\n data=pickle.load(alpha)\n alpha.close()\n batch_features[i]=data[0].reshape(feature_shape)\n z=np.zeros(c)\n for k,g in enumerate(coll[:c]):\n if g[0]==re.findall(r\"\\D+\",data[1])[0]:\n z[k]=1 \n \n batch_target[i]=z\n \n yield batch_features,batch_target\n ", "sub_path": "models/crnn/batch.py", "file_name": "batch.py", "file_ext": "py", "file_size_in_byte": 1363, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 18, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 19, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 24, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 29, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 39, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "545030948", "text": "__author__ = 'rpereira'\n\nimport os\nimport datetime\n\nfrom googleapiclient.discovery import build\nfrom oauth2client.client import GoogleCredentials\n\n\ndef launch_ps_to_gcs(topic, bucket_name, output_prefix, output_suffix, gcsPath='gs://dataflow-templates/latest/Cloud_PubSub_to_GCS_Text'):\n \"\"\"Lauch DataFlow template job to import data from PubSub into a GCS bucket\n\n :param topic: PubSub topic\n :param bucket_name: The path and filename prefix for writing output files. This value must end in a slash.\n :param output_prefix: The prefix to place on each windowed file. For example, output-\n :param output_suffix: The suffix to place on each windowed file, typically a file extension such as .txt or .csv.\n :return: None\n \"\"\"\n\n if os.environ[\"project_id\"]:\n credentials = GoogleCredentials.get_application_default()\n service = build('dataflow', 'v1b3', credentials=credentials)\n project_id = os.environ.get(\"project_id\")\n print(project_id)\n\n input_topic = \"projects/{project_id}/topics/{topic}\".format(project_id=project_id, topic=topic)\n time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n jobname = \"Import from topic{inputTopic} at {time}\"\\\n .format(inputTopic=input_topic, time=time)\n\n body = {\n \"jobName\": \"{jobname}\".format(jobname=jobname),\n \"parameters\": {\n \"inputTopic\": input_topic,\n \"outputDirectory\": \"gs://{bucket_name}/output/\".format(bucket_name=bucket_name),\n \"outputFilenamePrefix\": output_prefix,\n \"outputFilenameSuffix\": output_suffix,\n },\n \"environment\": {\"zone\": \"us-central1-f\"}\n }\n\n request = service.projects().templates().launch(projectId=project_id, gcsPath=gcsPath, body=body)\n response = request.execute()\n\n print(response)\n\n return {\"outputDirectory\": \"gs://{bucket_name}/output/\".format(bucket_name=bucket_name),\n \"outputFilenamePrefix\": output_prefix,\n \"outputFilenameSuffix\": output_suffix}\n\n", "sub_path": "dataflowps_to_bq/utils/dataflow.py", "file_name": "dataflow.py", "file_ext": "py", "file_size_in_byte": 2093, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 20, "usage_type": "attribute"}, {"api_name": "oauth2client.client.GoogleCredentials.get_application_default", "line_number": 21, "usage_type": "call"}, {"api_name": "oauth2client.client.GoogleCredentials", "line_number": 21, "usage_type": "name"}, {"api_name": "googleapiclient.discovery.build", "line_number": 22, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 23, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 23, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "attribute"}]} +{"seq_id": "616285911", "text": "from .pages.login_page import LoginPage\nfrom .pages.base_page import BasePage\nfrom .pages.basket_page import BasketPage\nimport pytest\n\nlink = \"http://selenium1py.pythonanywhere.com/\"\n\n\n@pytest.mark.login_guest\nclass TestLoginFromMainPage():\n def test_guest_can_go_to_login_page(self, browser):\n page = BasePage(browser, link)\n page.open()\n page.go_to_login_page()\n\n def test_guest_should_see_login_link(self, browser):\n page = BasePage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\ndef test_guest_can_go_to_login_page(browser):\n page = BasePage(browser, link)\n page.open()\n page.go_to_login_page()\n login = LoginPage(browser, link)\n login.should_be_login_page()\n\n\ndef test_guest_cant_see_product_in_basket_opened_from_main_page(browser):\n page = BasketPage(browser, link)\n page.open()\n page.go_to_button_basket()\n page.should_be_empty_basket()\n page.should_not_disappear()\n", "sub_path": "test_main_page.py", "file_name": "test_main_page.py", "file_ext": "py", "file_size_in_byte": 964, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pages.base_page.BasePage", "line_number": 12, "usage_type": "call"}, {"api_name": "pages.base_page.BasePage", "line_number": 17, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pages.base_page.BasePage", "line_number": 23, "usage_type": "call"}, {"api_name": "pages.login_page.LoginPage", "line_number": 26, "usage_type": "call"}, {"api_name": "pages.basket_page.BasketPage", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "557445512", "text": "from mpi4py import MPI\n\ndef hello_world(rank, size):\n print(\"Hello World from Process {0} out of {1}\").format(rank, size)\n\ndef conditional_hello(rank):\n if(rank % 2):\n print(\"Hello from process {0}\").format(rank)\n else:\n print(\"Goodbye from process {0}\").format(rank)\n\ndef main():\n rank = MPI.COMM_WORLD.Get_rank()\n size = MPI.COMM_WORLD.Get_size()\n\n print(\"---- Exercise 1 ---\")\n hello_world(rank,size)\n print(\"==== Exercise 2 ===\")\n conditional_hello(rank)\n print(\"---- Exercise 3 ---\")\n\n", "sub_path": "CSC 486 - Parallel and Distributed Systems/hello_world.py", "file_name": "hello_world.py", "file_ext": "py", "file_size_in_byte": 534, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "mpi4py.MPI.COMM_WORLD.Get_rank", "line_number": 13, "usage_type": "call"}, {"api_name": "mpi4py.MPI.COMM_WORLD", "line_number": 13, "usage_type": "attribute"}, {"api_name": "mpi4py.MPI", "line_number": 13, "usage_type": "name"}, {"api_name": "mpi4py.MPI.COMM_WORLD.Get_size", "line_number": 14, "usage_type": "call"}, {"api_name": "mpi4py.MPI.COMM_WORLD", "line_number": 14, "usage_type": "attribute"}, {"api_name": "mpi4py.MPI", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "221860258", "text": "# -*- coding: utf-8 -*-\nimport pygame\nfrom pygame.locals import *\nfrom src.data.utility import load_image\nfrom src.data.utility import set_colorkey\n\nclass SpriteSheet:\n def __init__(self, file_name):\n self.sheet = load_image(file_name)\n\n def img_at(self, rect, colorkey = None):\n rect = Rect(rect)\n image = pygame.Surface(rect.size).convert()\n image.blit(self.sheet, (0, 0), rect)\n return set_colorkey(image, colorkey)\n\n def imgs_at(self, rects, colorkey = None):\n imgs = []\n for rect in rects:\n imgs.append(self.img_at(rect, colorkey))\n return imgs\n", "sub_path": "1945/src/data/sprite_sheet.py", "file_name": "sprite_sheet.py", "file_ext": "py", "file_size_in_byte": 626, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "src.data.utility.load_image", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 13, "usage_type": "call"}, {"api_name": "src.data.utility.set_colorkey", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "647143007", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/3/6 18:32\n# @Author : duwenzhi\n# @Site : \n# @File : InputSystem.py\n# @Software: PyCharm\n\nimport sys\nimport cv2\nimport os\nimport time\nimport tensorflow as tf\nimport mysql.connector\nimport numpy as np\nimport facenet\nfrom scipy.misc import imresize\nfrom align import detect_face\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import QMainWindow\nfrom UI_Main import Ui_MainWindow\n\nflags = tf.app.flags\nroot_path = os.getcwd() + os.sep\n#初始化命令行参数\nflags.DEFINE_string('img_dir', os.path.join(root_path + '', 'img/'), '图片保存目录')\nflags.DEFINE_string('file_name', os.path.join(root_path + 'logs', 'data.txt'), '图片与中文姓名关联信息文件名称')\nflags.DEFINE_string('model_path', os.path.join(root_path + '', '20170512-110547'), '预训练模型位置')\n\n#初始化mysql数据库参数\nconfig = {\n 'user': 'root',\n 'password': 'root',\n 'host': '127.0.0.1',\n 'database': 'test',\n 'charset': 'utf8',\n 'pool_size': 10,\n \"pool_name\": \"server\",\n \"pool_reset_session\": False\n}\n\nclass PyQtMainEntry(QMainWindow, Ui_MainWindow):\n\n def __init__(self,FLAGS,mydb,is_save_mysql):\n super().__init__()\n with tf.Graph().as_default():\n with tf.Session() as sess:\n #加载预训练模型\n facenet.load_model(FLAGS.model_path)\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n #创建MTCNN模型,初始化pnet,rnet,onet网络,为摄像头获取的图片进行人脸对齐做准备\n self.pnet, self.rnet, self.onet = detect_face.create_mtcnn(sess, None)\n\n #初始化UI界面\n self.setupUi(self)\n #打开摄像头\n self.camera = cv2.VideoCapture(0)\n #判断摄像头是否打开\n self.is_camera_opened = False\n\n # 定时器:30ms捕获一帧\n self._timer = QtCore.QTimer(self)\n self._timer.timeout.connect(self._queryFrame)\n self._timer.setInterval(30)\n\n self.FLAGS = FLAGS\n self.mydb = mydb\n # 是否保存到数据库\n self.is_save_mysql = is_save_mysql\n\n def btnOpenCamera_Clicked(self):\n '''\n 打开和关闭摄像头\n '''\n self.is_camera_opened = ~self.is_camera_opened\n if self.is_camera_opened:\n self.btnOpenCamera.setText('关闭摄像头')\n self._timer.start()\n else:\n self.btnOpenCamera.setText('打开摄像头')\n self._timer.stop()\n\n def btnCapture_Clicked(self):\n '''\n 捕获图片\n '''\n # 摄像头未打开,不执行任何操作\n if not self.is_camera_opened:\n return\n\n self.captured = self.frame\n # OpenCV图像以BGR通道存储,显示时需要从BGR转到RGB\n self.save_captured = cv2.cvtColor(self.captured, cv2.COLOR_BGR2RGB)\n t = time.time()\n #创建时间戳,由于opencv对中文支持存在问题,所以保存的图片名称都是去当前时间戳,精确到毫秒\n local_time = int(round(t * 1000))\n img_name = str(local_time)\n #对摄像头拍摄的图片进行人脸对齐、裁剪并保存\n self.image_array_align_data(self.save_captured,img_name)\n if not self.name_list :\n self.name_list.append('张三')\n name = self.name_list[0]\n save_name_info = name + '=' + img_name\n #保存每张人脸图片和对应姓名的关联关系\n self.save_data(save_name_info)\n rows, cols, channels = self.captured.shape\n bytesPerLine = channels * cols\n # 使用Qt显示摄像头拍摄的图片,Qt显示图片时,需要先转换成QImgage类型\n QImg = QImage(self.captured.data, cols, rows, bytesPerLine, QImage.Format_RGB888)\n self.labelCapture.setPixmap(QPixmap.fromImage(QImg).scaled(\n self.labelCapture.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))\n\n def image_array_align_data(self, image_arr,img_name, image_size=160, margin=32,detect_multiple_faces=True):\n minsize = 20\n threshold = [0.6, 0.7, 0.7]\n factor = 0.709\n img = image_arr\n bounding_boxes, _ = detect_face.detect_face(img, minsize, self.pnet, self.rnet, self.onet, threshold, factor)\n nrof_faces = bounding_boxes.shape[0]\n\n if nrof_faces > 0:\n det = bounding_boxes[:, 0:4]\n det_arr = []\n img_size = np.asarray(img.shape)[0:2]\n if nrof_faces > 1:\n if detect_multiple_faces:\n for i in range(nrof_faces):\n det_arr.append(np.squeeze(det[i]))\n else:\n bounding_box_size = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])\n img_center = img_size / 2\n offsets = np.vstack(\n [(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:, 3]) / 2 - img_center[0]])\n offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)\n index = np.argmax(\n bounding_box_size - offset_dist_squared * 2.0)\n det_arr.append(det[index, :])\n else:\n det_arr.append(np.squeeze(det))\n\n for i, det in enumerate(det_arr):\n det = np.squeeze(det)\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0] - margin / 2, 0)\n bb[1] = np.maximum(det[1] - margin / 2, 0)\n bb[2] = np.minimum(det[2] + margin / 2, img_size[1])\n bb[3] = np.minimum(det[3] + margin / 2, img_size[0])\n cropped = img[bb[1]:bb[3], bb[0]:bb[2], :]\n # 进行图片缩放 cv2.resize(img,(w,h))\n scaled = imresize(cropped, (image_size, image_size), interp='bilinear')\n #保存人脸对齐、裁剪后的人脸图片\n cv2.imwrite(self.FLAGS.img_dir + img_name + '.jpg',scaled)\n\n def save_data(self,info):\n if self.is_save_mysql:\n mycursor = self.mydb.cursor()\n sql = 'INSERT INTO my_facenet_table (n_name,n_img_name) VALUES (%s, %s)'\n split = str(info).split('=')\n val = (str(split[0]), str(split[1]))\n mycursor.execute(sql, val)\n self.mydb.commit()\n print(mycursor.rowcount, '记录插入成功。')\n else:\n with open(self.FLAGS.file_name, 'a+', encoding='utf8') as f:\n f.write(info + '\\n')\n print(info)\n\n @QtCore.pyqtSlot()\n def _queryFrame(self):\n '''\n 循环获取图片\n '''\n ret, self.frame = self.camera.read()\n img_rows, img_cols, channels = self.frame.shape\n bytesPerLine = channels * img_cols\n cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB, self.frame)\n QImg = QImage(self.frame.data, img_cols, img_rows, bytesPerLine, QImage.Format_RGB888)\n self.labelCamera.setPixmap(QPixmap.fromImage(QImg).scaled(\n self.labelCamera.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))\n\nif __name__ == \"__main__\":\n #创建mysqlDB\n mydb = mysql.connector.connect(**config)\n #创建FLAGS\n FLAGS = tf.app.flags.FLAGS\n #是否保存到数据库\n is_save_mysql = True\n #创建PyQt5对象\n app = QtWidgets.QApplication(sys.argv)\n window = PyQtMainEntry(FLAGS,mydb,is_save_mysql)\n window.show()\n sys.exit(app.exec_())\n", "sub_path": "InputSystem.py", "file_name": "InputSystem.py", "file_ext": "py", "file_size_in_byte": 7739, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "tensorflow.app", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 26, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 44, "usage_type": "name"}, {"api_name": "UI_Main.Ui_MainWindow", "line_number": 44, "usage_type": "name"}, {"api_name": "tensorflow.Graph", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 49, "usage_type": "call"}, {"api_name": "facenet.load_model", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.GPUOptions", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 53, "usage_type": "call"}, {"api_name": "align.detect_face.create_mtcnn", "line_number": 55, "usage_type": "call"}, {"api_name": "align.detect_face", "line_number": 55, "usage_type": "name"}, {"api_name": "cv2.VideoCapture", "line_number": 60, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QTimer", "line_number": 65, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 65, "usage_type": "name"}, {"api_name": "cv2.cvtColor", "line_number": 96, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 96, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 97, "usage_type": "call"}, {"api_name": "align.detect_face.detect_face", "line_number": 121, "usage_type": "call"}, {"api_name": "align.detect_face", "line_number": 121, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 146, "usage_type": "attribute"}, {"api_name": "numpy.maximum", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 150, "usage_type": "call"}, {"api_name": "scipy.misc.imresize", "line_number": 153, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 155, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 179, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 179, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 171, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 171, "usage_type": "name"}, {"api_name": "mysql.connector.connector.connect", "line_number": 186, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 186, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 186, "usage_type": "name"}, {"api_name": "tensorflow.app", "line_number": 188, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 192, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 192, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 192, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 195, "usage_type": "call"}]} +{"seq_id": "327969496", "text": "import tensorflow as tf\n\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D, Activation, BatchNormalization\nfrom tensorflow.keras.layers import Input, Flatten, Dense, Dropout, Lambda\nfrom typing import Dict\n\n\ndef create_cnn(conf: Dict, input_dim: tuple) -> tf.keras.Model:\n def conv_block(input_, num_filters):\n x = Conv2D(num_filters, 5, strides=2, padding=\"same\")(input_)\n x = BatchNormalization()(x)\n x = Activation(\"tanh\")(x)\n return MaxPool2D(2)(x)\n\n input_ = Input(shape=input_dim)\n x = Lambda(lambda x: tf.expand_dims(x, axis=-1))(input_)\n for i in range(0, conf.get(\"num_conv_blocks\")):\n num_filters = min(2**(5 + i), 512)\n x = conv_block(x, num_filters)\n x = Flatten()(x)\n x = Dropout(0.4)(x)\n x = Dense(128, activation=\"relu\")(x)\n model = tf.keras.models.Model(input_, x)\n return model\n\n\ndef create_mlp(input_dim: tuple) -> tf.keras.Model:\n input_ = Input(shape=input_dim)\n\n x = Flatten()(input_)\n x = tf.keras.layers.Dense(1024, activation=\"relu\")(x)\n x = tf.keras.layers.Dropout(0.5)(x)\n x = tf.keras.layers.Dense(128, activation=\"relu\")(x)\n model = tf.keras.models.Model(input_, x)\n return model\n\n\ndef create_model(conf: Dict, input_shapes, show_summary: bool = False) -> tf.keras.Model:\n cnn = create_cnn(conf, input_shapes[\"spec\"])\n mlp = create_mlp(input_shapes[\"hpss\"])\n\n input_spec = Input(shape=input_shapes[\"spec\"], name=\"spec\")\n input_hpss = Input(shape=input_shapes[\"hpss\"], name=\"hpss\")\n\n cnn_out = cnn(input_spec)\n mlp_out = mlp(input_hpss)\n\n input_ = tf.keras.layers.concatenate([cnn_out, mlp_out])\n\n x = Dense(128, activation=\"relu\")(input_)\n x = Dropout(0.4)(x)\n output_ = Dense(conf.get(\"num_classes\"), activation=\"softmax\", name=\"output\")(x)\n\n model = tf.keras.models.Model([input_spec, input_hpss], output_)\n\n opt = tf.keras.optimizers.Adam(learning_rate=conf.get(\"learning_rate\"))\n model.compile(\n optimizer=opt,\n loss=\"binary_crossentropy\",\n metrics=[\"accuracy\"]\n )\n\n if show_summary:\n print(model.summary())\n return model\n", "sub_path": "members/amit/clf/create_model_fb.py", "file_name": "create_model_fb.py", "file_ext": "py", "file_size_in_byte": 2124, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.Dict", "line_number": 8, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 10, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 11, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Activation", "line_number": 12, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPool2D", "line_number": 13, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Lambda", "line_number": 16, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 16, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Flatten", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 8, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Flatten", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 27, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 38, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.concatenate", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 54, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 38, "usage_type": "attribute"}]} +{"seq_id": "551158555", "text": "# Copyright (c) 2011 Leif Johnson \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n'''Code for generating white and pink noise.'''\n\nimport numpy\nimport numpy.random as rng\n\n\ndef iterwhite():\n '''Generate a sequence of samples of white noise.\n\n Generates a never-ending sequence of floating-point values.\n '''\n while True:\n for n in rng.randn(100):\n yield n\n\n\ndef iterpink(depth=20):\n '''Generate a sequence of samples of pink noise.\n\n Based on the Voss-McCartney algorithm, discussion and code examples at\n http://www.firstpr.com.au/dsp/pink-noise/\n\n depth: Use this many samples of white noise to calculate the output. A\n higher number is slower to run, but renders low frequencies with more\n correct power spectra.\n\n Generates a never-ending sequence of floating-point values. Any continuous\n set of these samples will tend to have a 1/f power spectrum.\n '''\n values = rng.randn(depth)\n smooth = rng.randn(depth)\n source = rng.randn(depth)\n sum = values.sum()\n i = 0\n while True:\n yield sum + smooth[i]\n\n # advance the index by 1. if the index wraps, generate noise to use in\n # the calculations, but do not update any of the pink noise values.\n i += 1\n if i == depth:\n i = 0\n smooth = rng.randn(depth)\n source = rng.randn(depth)\n continue\n\n # count trailing zeros in i\n c = 0\n while not (i >> c) & 1:\n c += 1\n\n # replace value c with a new source element\n sum += source[i] - values[c]\n values[c] = source[i]\n\n\ndef _asarray(source, shape):\n noise = source()\n if shape is None:\n return noise.next()\n count = reduce(operator.mul, shape)\n return numpy.asarray([noise.next() for _ in range(count)]).reshape(shape)\n\n\ndef white(shape=None):\n '''Generate white noise.\n\n shape: If given, returns a numpy array of white noise with this shape. If\n not given, return just one sample of white noise.\n '''\n return _asarray(iterwhite, shape)\n\n\ndef pink(shape=None, depth=20):\n '''Generate an array of pink noise.\n\n shape: If given, returns a numpy array of noise with this shape. If not\n given, return just one sample of noise.\n depth: Use this many samples of white noise to calculate pink noise. A\n higher number is slower to run, but renders low frequencies with more\n correct power spectra.\n '''\n return _asarray(lambda: iterpink(depth), shape)\n\n\nif __name__ == '__main__':\n from matplotlib import pylab\n\n k = numpy.ones(100.) / 10.\n def spectrum(s):\n a = abs(numpy.fft.rfft(list(s))) ** 2\n return numpy.convolve(a, k, 'valid')\n\n ax = pylab.gca()\n\n w = iterwhite()\n ax.loglog(spectrum(w.next() for _ in range(10000)), 'k')\n\n for p, a in enumerate(numpy.logspace(-0.5, 0, 7)):\n p = iterpink(2 ** (p + 1))\n ax.loglog(spectrum(p.next() for _ in range(10000)), 'r', alpha=a)\n\n ax.grid(linestyle=':')\n ax.set_xlim(10., None)\n ax.set_ylim(None, 1e8)\n\n pylab.show()\n", "sub_path": "lmj/sound/noise.py", "file_name": "noise.py", "file_ext": "py", "file_size_in_byte": 4121, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.random.randn", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "name"}, {"api_name": "numpy.random.randn", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.fft.rfft", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.convolve", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pylab.gca", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.logspace", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pylab.show", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 127, "usage_type": "name"}]} +{"seq_id": "638405227", "text": "# Copyright (c) 2013 Per Unneberg\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\nimport os\nimport luigi\nimport time\nimport shutil\nimport random\nimport logging\nfrom ratatosk.job import InputJobTask, JobTask, DefaultShellJobRunner, DefaultGzShellJobRunner\nfrom cement.utils import shell\n\nlogger = logging.getLogger('luigi-interface')\n\n# NB: Now subclass DefaultGzShellJobRunner\nclass CutadaptJobRunner(DefaultGzShellJobRunner):\n pass\n\nclass InputFastqFile(InputJobTask):\n _config_section = \"cutadapt\"\n _config_subsection = \"InputFastqFile\"\n parent_task = luigi.Parameter(default=\"ratatosk.lib.files.external.FastqFile\")\n \n\n# NB: cutadapt is a non-hiearchical tool. Group under, say, utils?\nclass CutadaptJobTask(JobTask):\n _config_section = \"cutadapt\"\n label = luigi.Parameter(default=\".trimmed\")\n executable = luigi.Parameter(default=\"cutadapt\")\n parent_task = luigi.Parameter(default=\"ratatosk.lib.utils.cutadapt.InputFastqFile\")\n # Use Illumina TruSeq adapter sequences as default\n threeprime = luigi.Parameter(default=\"AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC\")\n fiveprime = luigi.Parameter(default=\"AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC\")\n read1_suffix = luigi.Parameter(default=\"_R1_001\")\n read2_suffix = luigi.Parameter(default=\"_R2_001\")\n\n def read1(self):\n # Assume read 2 if no match...\n return self.input().fn.find(self.read1_suffix) > 0\n\n def job_runner(self):\n return CutadaptJobRunner()\n\n def args(self):\n seq = self.threeprime if self.read1() else self.fiveprime\n return [\"-a\", seq, self.input(), \"-o\", self.output(), \">\", self.input().fn.replace(\".fastq.gz\", \".trimmed.fastq.cutadapt_metrics\")]\n", "sub_path": "ratatosk/lib/utils/cutadapt.py", "file_name": "cutadapt.py", "file_ext": "py", "file_size_in_byte": 2181, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "ratatosk.job.DefaultGzShellJobRunner", "line_number": 26, "usage_type": "name"}, {"api_name": "ratatosk.job.InputJobTask", "line_number": 29, "usage_type": "name"}, {"api_name": "luigi.Parameter", "line_number": 32, "usage_type": "call"}, {"api_name": "ratatosk.job.JobTask", "line_number": 36, "usage_type": "name"}, {"api_name": "luigi.Parameter", "line_number": 38, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 39, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 40, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 42, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 43, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 44, "usage_type": "call"}, {"api_name": "luigi.Parameter", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "372067999", "text": "import plux\nimport datetime\n\nclass GlobalFunction():\n \n def exampleFindDevices():\n devices = plux.BaseDev.findDevices()\n print(\"Found devices: \", devices)\n \n def exampleStart(dev):\n try: # MAC address of device\n props = dev.getProperties()\n print('Properties:', props)\n dev.start(1000, 0xFF, 16) # 1000 Hz, ports 1-8, 16 bits\n dev.loop() # returns after receiving 10000 frames (onRawFrame() returns True)\n dev.stop()\n dev.close()\n except Exception as e:\n print(e)\n if (dev):\n dev.close()\n \n def exampleStartSources(dev):\n srcx = plux.Source()\n srcx.port = 1\n # nBits defaults to 16\n # freqDivisor defaults to 1\n # chMask defaults to 1\n \n srcy = plux.Source()\n srcy.port = 2\n srcy.nBits = 8\n srcy.freqDivisor = 3 # divide base frequency by 3 for this source\n \n srcz = plux.Source()\n srcz.port = 3\n srcz.freqDivisor = 2 # divide base frequency by 2 for this source\n \n dev.start(1000, (srcx, srcy, srcz)) # base freq: 1000 Hz, ports 1-3 as defined by sources\n dev.loop() # returns after receiving 10000 frames (onRawFrame() returns True)\n dev.stop()\n dev.close()\n \n def exampleAddSchedule(dev):\n srcx = plux.Source()\n srcx.port = 1\n \n srcy = plux.Source()\n srcy.port = 2\n \n srcz = plux.Source()\n srcz.port = 3\n \n dev.setTime() # adjust device RTC\n \n sch = plux.Schedule()\n sch.baseFreq = 1000 # in Hz\n sch.startTime = datetime.datetime.now() + datetime.timedelta(0,10) # start an internal acquisition 10 seconds from now \n #sch.startTime = 1 # decomment this line to start an internal acquisition with external trigger\n sch.duration = 30 # maximum duration of 30 seconds\n sch.sources = (srcx, srcy, srcz)\n \n dev.addSchedule(sch)\n dev.close()\n \n def exampleReplaySessions(dev):\n sessions = dev.getSessions()\n for s in sessions:\n dev.replaySession(s.startTime) # replay all sessions on device\n dev.close\n", "sub_path": "PLUX_API_Python2.7_v1.1/DeviceFunction.py", "file_name": "DeviceFunction.py", "file_ext": "py", "file_size_in_byte": 2281, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "plux.BaseDev.findDevices", "line_number": 7, "usage_type": "call"}, {"api_name": "plux.BaseDev", "line_number": 7, "usage_type": "attribute"}, {"api_name": "plux.Source", "line_number": 24, "usage_type": "call"}, {"api_name": "plux.Source", "line_number": 30, "usage_type": "call"}, {"api_name": "plux.Source", "line_number": 35, "usage_type": "call"}, {"api_name": "plux.Source", "line_number": 45, "usage_type": "call"}, {"api_name": "plux.Source", "line_number": 48, "usage_type": "call"}, {"api_name": "plux.Source", "line_number": 51, "usage_type": "call"}, {"api_name": "plux.Schedule", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 58, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "547646131", "text": "# Databricks notebook source\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC
\n# MAGIC \"Databricks\n# MAGIC
\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC # Exercise #2 - Batch Ingestion\n# MAGIC \n# MAGIC In this exercise you will be ingesting three batches of orders, one for 2017, 2018 and 2019.\n# MAGIC \n# MAGIC As each batch is ingested, we are going to append it to a new Delta table, unifying all the datasets into one single dataset.\n# MAGIC \n# MAGIC Each year, different individuals and different standards were used resulting in datasets that vary slightly:\n# MAGIC * In 2017 the backup was written as fixed-width text files\n# MAGIC * In 2018 the backup was written a tab-separated text files\n# MAGIC * In 2019 the backup was written as a \"standard\" comma-separted text files but the format of the column names was changed\n# MAGIC \n# MAGIC Our only goal here is to unify all the datasets while tracking the source of each record (ingested file name and ingested timestamp) should additional problems arise.\n# MAGIC \n# MAGIC Because we are only concerned with ingestion at this stage, the majority of the columns will be ingested as simple strings and in future exercises we will address this issue (and others) with various transformations.\n# MAGIC \n# MAGIC As you progress, several \"reality checks\" will be provided to you help ensure that you are on track - simply run the corresponding command after implementing the corresponding solution.\n# MAGIC \n# MAGIC This exercise is broken up into 3 steps:\n# MAGIC * Exercise 2.A - Ingest Fixed-Width File\n# MAGIC * Exercise 2.B - Ingest Tab-Separated File\n# MAGIC * Exercise 2.C - Ingest Comma-Separated File\n\n# COMMAND ----------\n\n# MAGIC %md

Setup Exercise #2

\n# MAGIC \n# MAGIC To get started, we first need to configure your Registration ID and then run the setup notebook.\n\n# COMMAND ----------\n\n# MAGIC %md ### Setup - Registration ID\n# MAGIC \n# MAGIC In the next commmand, please update the variable **`registration_id`** with the Registration ID you received when you signed up for this project.\n# MAGIC \n# MAGIC For more information, see [Registration ID]($./Registration ID)\n\n# COMMAND ----------\n\nregistration_id = \"1898866\"\n\n# COMMAND ----------\n\n# MAGIC %md ### Setup - Run the exercise setup\n# MAGIC \n# MAGIC Run the following cell to setup this exercise, declaring exercise-specific variables and functions.\n\n# COMMAND ----------\n\n# MAGIC %run ./_includes/Setup-Exercise-02\n\n# COMMAND ----------\n\n# MAGIC %md Run the following cell to preview a list of the files you will be processing in this exercise.\n\n# COMMAND ----------\n\nfiles = dbutils.fs.ls(f\"{working_dir}/raw/orders/batch\") # List all the files\ndisplay(files) # Display the list of files\n\n# COMMAND ----------\n\n# MAGIC %md

Exercise #2.A - Ingest Fixed-Width File

\n# MAGIC \n# MAGIC **In this step you will need to:**\n# MAGIC 1. Use the variable **`batch_2017_path`**, and **`dbutils.fs.head`** to investigate the 2017 batch file, if needed.\n# MAGIC 2. Configure a **`DataFrameReader`** to ingest the text file identified by **`batch_2017_path`** - this should provide one record per line, with a single column named **`value`**\n# MAGIC 3. Using the information in **`fixed_width_column_defs`** (or the dictionary itself) use the **`value`** column to extract each new column of the appropriate length.
\n# MAGIC * The dictionary's key is the column name\n# MAGIC * The first element in the dictionary's value is the starting position of that column's data\n# MAGIC * The second element in the dictionary's value is the length of that column's data\n# MAGIC 4. Once you are done with the **`value`** column, remove it.\n# MAGIC 5. For each new column created in step #3, remove any leading whitespace\n# MAGIC * The introduction of \\[leading\\] white space should be expected when extracting fixed-width values out of the **`value`** column.\n# MAGIC 6. For each new column created in step #3, replace all empty strings with **`null`**.\n# MAGIC * After trimming white space, any column for which a value was not specified in the original dataset should result in an empty string.\n# MAGIC 7. Add a new column, **`ingest_file_name`**, which is the name of the file from which the data was read from.\n# MAGIC * This should not be hard coded.\n# MAGIC * For the proper function, see the pyspark.sql.functions module\n# MAGIC 8. Add a new column, **`ingested_at`**, which is a timestamp of when the data was ingested as a DataFrame.\n# MAGIC * This should not be hard coded.\n# MAGIC * For the proper function, see the pyspark.sql.functions module\n# MAGIC 9. Write the corresponding **`DataFrame`** in the \"delta\" format to the location specified by **`batch_target_path`**\n# MAGIC \n# MAGIC **Special Notes:**\n# MAGIC * It is possible to use the dictionary **`fixed_width_column_defs`** and programatically extract
\n# MAGIC each column but, it is also perfectly OK to hard code this step and extract one column at a time.\n# MAGIC * The **`SparkSession`** is already provided to you as an instance of **`spark`**.\n# MAGIC * The classes/methods that you will need for this exercise include:\n# MAGIC * **`pyspark.sql.DataFrameReader`** to ingest data\n# MAGIC * **`pyspark.sql.DataFrameWriter`** to ingest data\n# MAGIC * **`pyspark.sql.Column`** to transform data\n# MAGIC * Various functions from the **`pyspark.sql.functions`** module\n# MAGIC * Various transformations and actions from **`pyspark.sql.DataFrame`**\n# MAGIC * The following methods can be used to investigate and manipulate the Databricks File System (DBFS)\n# MAGIC * **`dbutils.fs.ls(..)`** for listing files\n# MAGIC * **`dbutils.fs.rm(..)`** for removing files\n# MAGIC * **`dbutils.fs.head(..)`** to view the first N bytes of a file\n# MAGIC \n# MAGIC **Additional Requirements:**\n# MAGIC * The unified batch dataset must be written to disk in the \"delta\" format\n# MAGIC * The schema for the unified batch dataset must be:\n# MAGIC * **`submitted_at`**:**`string`**\n# MAGIC * **`order_id`**:**`string`**\n# MAGIC * **`customer_id`**:**`string`**\n# MAGIC * **`sales_rep_id`**:**`string`**\n# MAGIC * **`sales_rep_ssn`**:**`string`**\n# MAGIC * **`sales_rep_first_name`**:**`string`**\n# MAGIC * **`sales_rep_last_name`**:**`string`**\n# MAGIC * **`sales_rep_address`**:**`string`**\n# MAGIC * **`sales_rep_city`**:**`string`**\n# MAGIC * **`sales_rep_state`**:**`string`**\n# MAGIC * **`sales_rep_zip`**:**`string`**\n# MAGIC * **`shipping_address_attention`**:**`string`**\n# MAGIC * **`shipping_address_address`**:**`string`**\n# MAGIC * **`shipping_address_city`**:**`string`**\n# MAGIC * **`shipping_address_state`**:**`string`**\n# MAGIC * **`shipping_address_zip`**:**`string`**\n# MAGIC * **`product_id`**:**`string`**\n# MAGIC * **`product_quantity`**:**`string`**\n# MAGIC * **`product_sold_price`**:**`string`**\n# MAGIC * **`ingest_file_name`**:**`string`**\n# MAGIC * **`ingested_at`**:**`timestamp`**\n\n# COMMAND ----------\n\n# MAGIC %md ### Fixed-Width Meta Data \n# MAGIC \n# MAGIC The following dictionary is provided for reference and/or implementation
\n# MAGIC (depending on which strategy you choose to employ).\n# MAGIC \n# MAGIC Run the following cell to instantiate it.\n\n# COMMAND ----------\n\nfixed_width_column_defs = {\n \"submitted_at\": (1, 15),\n \"order_id\": (16, 40),\n \"customer_id\": (56, 40),\n \"sales_rep_id\": (96, 40),\n \"sales_rep_ssn\": (136, 15),\n \"sales_rep_first_name\": (151, 15),\n \"sales_rep_last_name\": (166, 15),\n \"sales_rep_address\": (181, 40),\n \"sales_rep_city\": (221, 20),\n \"sales_rep_state\": (241, 2),\n \"sales_rep_zip\": (243, 5),\n \"shipping_address_attention\": (248, 30),\n \"shipping_address_address\": (278, 40),\n \"shipping_address_city\": (318, 20),\n \"shipping_address_state\": (338, 2),\n \"shipping_address_zip\": (340, 5),\n \"product_id\": (345, 40),\n \"product_quantity\": (385, 5),\n \"product_sold_price\": (390, 20)\n}\n\n# COMMAND ----------\n\n# MAGIC %md ### Implement Exercise #2.A\n# MAGIC \n# MAGIC Implement your solution in the following cell:\n\n# COMMAND ----------\n\n# TODO\n# Use this cell to complete your solution\nbatch_2017_path = \"dbfs:/user/txu@guidehouse.com/dbacademy/developer-foundations-capstone/raw/orders/batch/2017.txt\"\ndbutils.fs.head(batch_2017_path)\nspark.read.csv(batch_2017_path)\n\n# COMMAND ----------\n\ndf = spark.read.text(batch_2017_path)\ndf.show()\n\n\n# COMMAND ----------\n\ndf_2017 = df\nfor colname, coltuple in fixed_width_column_defs.items():\n df_2017 = df_2017.withColumn(colname, df_2017.value.substr(coltuple[0],coltuple[1]))\ndf_2017.show()\n\n# COMMAND ----------\n\ndf_2017 = df_2017.select([column for column in df_2017.columns if column in fixed_width_column_defs])\ndf_2017.show()\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import trim, col\ndf_2017a = df_2017.select(*[trim(col(column)).alias(column) for column in df_2017.columns])\ndf_2017a.show()\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import lit, when, col\ndef blank_as_null(x):\n return when(col(x) != \"\", col(x)).otherwise(lit(None))\nexprs = [blank_as_null(x).alias(x) for x in df_2017a.columns]\ndf_2017b = df_2017a.select(*exprs)\ndisplay(df_2017b)\n\n# COMMAND ----------\n\nschema = df_2017b.schema\nschema\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import input_file_name, current_timestamp\ndf_2017c = df_2017b.withColumn(\"ingest_file_name\", when(input_file_name().isNotNull(), input_file_name()).otherwise(lit(None)))\ndf_2017d = df_2017c.withColumn(\"ingested_at\", when(current_timestamp().isNotNull(), current_timestamp()).otherwise(lit(None)))\n\n# COMMAND ----------\n\ndf_2017d.printSchema()\nbatch_target_path = \"dbfs:/user/txu@guidehouse.com/dbacademy/developer-foundations-capstone/batch_orders_dirty.delta\"\ndf_2017d.write.format(\"delta\").mode(\"overwrite\").save(batch_target_path)\n\n# COMMAND ----------\n\n# MAGIC %md ### Reality Check #2.A\n# MAGIC Run the following command to ensure that you are on track:\n\n# COMMAND ----------\n\nreality_check_02_a()\n\n# COMMAND ----------\n\n# MAGIC %md

Exercise #2.B - Ingest Tab-Separted File

\n# MAGIC \n# MAGIC **In this step you will need to:**\n# MAGIC 1. Use the variable **`batch_2018_path`**, and **`dbutils.fs.head`** to investigate the 2018 batch file, if needed.\n# MAGIC 2. Configure a **`DataFrameReader`** to ingest the tab-separated file identified by **`batch_2018_path`**\n# MAGIC 3. Add a new column, **`ingest_file_name`**, which is the name of the file from which the data was read from - note this should not be hard coded.\n# MAGIC 4. Add a new column, **`ingested_at`**, which is a timestamp of when the data was ingested as a DataFrame - note this should not be hard coded.\n# MAGIC 5. **Append** the corresponding **`DataFrame`** to the previously created datasets specified by **`batch_target_path`**\n# MAGIC \n# MAGIC **Additional Requirements**\n# MAGIC * Any **\"null\"** strings in the CSV file should be replaced with the SQL value **null**\n\n# COMMAND ----------\n\n# MAGIC %md ### Implement Exercise #2.b\n# MAGIC \n# MAGIC Implement your solution in the following cell:\n\n# COMMAND ----------\n\n# TODO\n# Use this cell to complete your solution\nbatch_2018_path = \"dbfs:/user/txu@guidehouse.com/dbacademy/developer-foundations-capstone/raw/orders/batch/2018.csv\"\n\n# COMMAND ----------\n\ndf_2018 = spark.read.format(\"csv\").option(\"header\", \"true\").option(\"delimiter\", \"\\t\").load(batch_2018_path)\ndisplay(df_2018)\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import input_file_name, current_timestamp\n\ndf_2018 = df_2018.withColumn(\"ingest_file_name\", when(input_file_name().isNotNull(), input_file_name()).otherwise(lit(None)))\ndf_2018 = df_2018.withColumn(\"ingested_at\", when(current_timestamp().isNotNull(), current_timestamp()).otherwise(lit(None)))\n\n\n# COMMAND ----------\n\ndisplay(df_2018)\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import lit, when, col\ndef blank_as_null(x):\n return when((col(x) != \"\") & (col(x) != \"null\"), col(x)).otherwise(lit(None))\nexprs = [blank_as_null(x).alias(x) for x in df_2018.columns]\ndf_2018a = df_2018.select(*exprs)\n\n# COMMAND ----------\n\ndf_2018a.write.format(\"delta\").mode(\"append\").save(batch_target_path)\n\n# COMMAND ----------\n\n# MAGIC %md ### Reality Check #2.B\n# MAGIC Run the following command to ensure that you are on track:\n\n# COMMAND ----------\n\nreality_check_02_b()\n\n# COMMAND ----------\n\n# MAGIC %md

Exercise #2.C - Ingest Comma-Separted File

\n# MAGIC \n# MAGIC **In this step you will need to:**\n# MAGIC 1. Use the variable **`batch_2019_path`**, and **`dbutils.fs.head`** to investigate the 2019 batch file, if needed.\n# MAGIC 2. Configure a **`DataFrameReader`** to ingest the comma-separated file identified by **`batch_2019_path`**\n# MAGIC 3. Add a new column, **`ingest_file_name`**, which is the name of the file from which the data was read from - note this should not be hard coded.\n# MAGIC 4. Add a new column, **`ingested_at`**, which is a timestamp of when the data was ingested as a DataFrame - note this should not be hard coded.\n# MAGIC 5. **Append** the corresponding **`DataFrame`** to the previously created dataset specified by **`batch_target_path`**
\n# MAGIC Note: The column names in this dataset must be updated to conform to the schema defined for Exercise #2.A - there are several strategies for this:\n# MAGIC * Provide a schema that alters the names upon ingestion\n# MAGIC * Manually rename one column at a time\n# MAGIC * Use **`fixed_width_column_defs`** programaticly rename one column at a time\n# MAGIC * Use transformations found in the **`DataFrame`** class to rename all columns in one operation\n# MAGIC \n# MAGIC **Additional Requirements**\n# MAGIC * Any **\"null\"** strings in the CSV file should be replaced with the SQL value **null**
\n\n# COMMAND ----------\n\n# MAGIC %md ### Implement Exercise #2.C\n# MAGIC \n# MAGIC Implement your solution in the following cell:\n\n# COMMAND ----------\n\n# TODO\n# Use this cell to complete your solution\nbatch_2019_path = \"dbfs:/user/txu@guidehouse.com/dbacademy/developer-foundations-capstone/raw/orders/batch/2019.csv\"\n\n# COMMAND ----------\n\ndf_2019 = spark.read.format(\"csv\").option(\"header\", \"true\").option(\"delimiter\", \",\").schema(schema).load(batch_2019_path)\ndisplay(df_2019)\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import input_file_name, current_timestamp\ndf_2019 = df_2019.withColumn(\"ingest_file_name\", when(input_file_name().isNotNull(), input_file_name()).otherwise(lit(None)))\ndf_2019 = df_2019.withColumn(\"ingested_at\", when(current_timestamp().isNotNull(), current_timestamp()).otherwise(lit(None)))\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import lit, when, col\ndef blank_as_null(x):\n return when((col(x) != \"\") & (col(x) != \"null\"), col(x)).otherwise(lit(None))\nexprs = [blank_as_null(x).alias(x) for x in df_2019.columns]\ndf_2019a = df_2019.select(*exprs)\n\n# COMMAND ----------\n\ndf_2019a.write.format(\"delta\").mode(\"append\").save(batch_target_path)\n\n# COMMAND ----------\n\n# MAGIC %md ### Reality Check #2.C\n# MAGIC Run the following command to ensure that you are on track:\n\n# COMMAND ----------\n\nreality_check_02_c()\n\n# COMMAND ----------\n\n# MAGIC %md

Exercise #2 - Final Check

\n# MAGIC \n# MAGIC Run the following command to make sure this exercise is complete:\n\n# COMMAND ----------\n\nreality_check_02_final()", "sub_path": "Developer-Foundations-Capstone/Exercise 02 - Batch Ingestion.py", "file_name": "Exercise 02 - Batch Ingestion.py", "file_ext": "py", "file_size_in_byte": 16093, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pyspark.sql.functions.trim", "line_number": 202, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 202, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 209, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 209, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 209, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 222, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.input_file_name", "line_number": 222, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 222, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 223, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.current_timestamp", "line_number": 223, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 223, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 275, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.input_file_name", "line_number": 275, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 275, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 276, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.current_timestamp", "line_number": 276, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 276, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 287, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 287, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 287, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 343, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.input_file_name", "line_number": 343, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 343, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 344, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.current_timestamp", "line_number": 344, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 344, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 350, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 350, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 350, "usage_type": "call"}]} +{"seq_id": "232960739", "text": "#直接从网页爬取有些网站会拒绝urllib反复请求,所以用requests库\r\n#用同一个ip频繁请求同一个网页时会被服务器屏蔽\r\n#这个程序还是能用的,但是有的时候不稳定,可能需要频繁更换代理ip\r\n#频繁换ip也不行\r\n#让循环之内有0.5秒的间隔也不行,真是他妈的烂透了!!!\r\n#建立起一个UA池,让每次请求拥有的UA随机分配。以此来防止UA限制。但好像还是没什么卵用,好像每天中午都不太行,不知道是不是时间的原因。\r\n#最后一次尝试,就是把协程并发改成每隔0.1秒发一个,然后pagetotxt内部请求的间隔是0.1到0.15之间的随机数\r\n#现在终于可行了,当前代码下,漏爬率率大概1.33%,每秒爬出3个文件,每100文件换一个ip地址,每个网页请求会在一个拥有586个UA池中随机选取一个UA。\r\n#就现在的观察,漏爬率可能与换ip频繁程度有关,每150个文件换一个ip,漏爬率为5%。\r\n#睡眠时间与漏爬率也可能有关,可能睡眠时间越短,漏爬率越高。\r\n#我决定开发2.2,改用selenium模拟浏览器环境读取了\r\nimport requests\r\nimport urllib.request\r\nimport chardet \r\nimport re \r\nfrom multiprocessing import Pool\r\nimport gevent\r\nfrom gevent import monkey; monkey.patch_all()\r\nfrom gevent.pool import Group \r\nimport time\r\nimport random#导入随机数模块 \r\nstart = time.time()\r\nip = requests.get('http://www.xdaili.cn/ipagent//newExclusive/getIp?spiderId=0a4b8956ad274e579822b533d27f79e1&orderno=DX20177252748hBxtZI&returnType=1&count=1&machineArea=').content#API接口链接\r\nip = str(ip)\r\nip = re.search('(b\\')(.*?)(\\\\\\\\n\\')',ip)[2]\r\nrequests.Session().proxies = {\"http\":\"http://\"+ip,}#使用代理ip\r\nprint(ip)\r\nUAcontent = urllib.request.urlopen('file:///C:/Users/dell/Desktop/useragentswitcher.xml').read()\r\nUAcontent = str(UAcontent)\r\nUAname = re.findall('(useragent=\")(.*?)(\")',UAcontent)\r\nUAlist = list()\r\nfor i in range(0,int(len(UAname))): \r\n UAlist.append(UAname[i][1])\r\n\r\nUAlist = UAlist[0:586]#这样就得到了一个拥有586个UA的UA池\r\ntime.sleep(20)\r\ndef pagetotxt(urlnum):\r\n #先读取主网页\r\n url1 = 'http://odds.500.com/fenxi/ouzhi-'+str(urlnum)+'.shtml'\r\n #print(url1)\r\n originalcontent = requests.get(url1,headers = {'user-agent': UAlist[random.randint(0,585)]}).content#random.randint(0,586)每次都会返回一个不同的0到585之间的随机整数\r\n time.sleep(random.uniform(0.15,0.2))\r\n content = originalcontent.decode('gb18030')\r\n date = re.search('(

比赛时间)(.*?)(

)',content).group(2)\r\n date = date[0:10]\r\n rawtitle = re.search('()(.*?)(-百家欧赔-500彩票网)',content)\r\n title = rawtitle.group(2)\r\n title = re.sub('/','',title)\r\n title = re.sub('\\d','',title)\r\n saishi = re.search('(\\()(.*?)(\\))',title).group(2)\r\n bifen = re.search('()(.*?)()',content).group(2)\r\n #接下来提取列表\r\n sucker1 = '(\"display:;\">)(.*?)( list:\n \"\"\"\n Deduplicate a list while keeping order\n \n If only_neighbors is True, dedupe will only check neighboring values\n \"\"\"\n ret = []\n for item in items:\n if (only_neighbors and ret and ret[-1] != item) or item not in ret:\n ret.append(item)\n return ret\n\n\ndef is_unknown(val: str) -> bool:\n \"\"\"\n Returns True if val represents and unknown value\n \"\"\"\n if not isinstance(val, str):\n raise TypeError\n if not val or val.upper() in (\"UNKN\",):\n return True\n for char in val:\n if char not in (\"/\", \"X\", \".\"):\n break\n else:\n return True\n return False\n\n\ndef get_digit_list(alist: [str], from_index: int) -> ([str], [str]):\n \"\"\"\n Returns a list of items removed from a given list of strings\n that are all digits from 'from_index' until hitting a non-digit item\n \"\"\"\n ret = []\n alist.pop(from_index)\n while len(alist) > from_index and alist[from_index].isdigit():\n ret.append(alist.pop(from_index))\n return alist, ret\n\n\ndef unpack_fraction(num: str) -> str:\n \"\"\"\n Returns unpacked fraction string 5/2 -> 2 1/2\n \"\"\"\n nums = [int(n) for n in num.split(\"/\") if n]\n if len(nums) == 2 and nums[0] > nums[1]:\n over = nums[0] // nums[1]\n rem = nums[0] % nums[1]\n return f\"{over} {rem}/{nums[1]}\"\n return num\n\n\ndef remove_leading_zeros(num: str) -> str:\n \"\"\"\n Strips zeros while handling -, M, and empty strings\n \"\"\"\n if not num:\n return num\n if num.startswith(\"M\"):\n ret = \"M\" + num[1:].lstrip(\"0\")\n elif num.startswith(\"-\"):\n ret = \"-\" + num[1:].lstrip(\"0\")\n else:\n ret = num.lstrip(\"0\")\n return \"0\" if ret in (\"\", \"M\", \"-\") else ret\n\n\ndef spoken_number(num: str) -> str:\n \"\"\"\n Returns the spoken version of a number\n\n Ex: 1.2 -> one point two\n 1 1/2 -> one and one half\n \"\"\"\n ret = []\n for part in num.split():\n if part in FRACTIONS:\n ret.append(FRACTIONS[part])\n else:\n ret.append(\n \" \".join(NUMBER_REPL[char] for char in part if char in NUMBER_REPL)\n )\n return \" and \".join(ret)\n\n\ndef make_number(num: str, repr: str = None, speak: str = None) -> Number:\n \"\"\"\n Returns a Number or Fraction dataclass for a number string\n\n NOTE: Numerators are assumed to have a single digit. Additional are whole numbers\n \"\"\"\n if not num or is_unknown(num):\n return\n # Check special\n if num in SPECIAL_NUMBERS:\n return Number(repr or num, *SPECIAL_NUMBERS[num])\n # Check cardinal direction\n if num in CARDINALS:\n if not repr:\n repr = num\n num = str(CARDINALS[num])\n # Remove spurious characters from the end\n num = num.rstrip(\"M.\")\n num = num.replace(\"O\", \"0\")\n num = num.replace(\"+\", \"\")\n # Create Fraction\n if \"/\" in num:\n nmr, dnm = num.split(\"/\")\n dnm = int(dnm)\n # Multiply multi-digit numerator\n if len(nmr) > 1:\n nmr = int(nmr[:-1]) * dnm + int(nmr[-1])\n num = f\"{nmr}/{dnm}\"\n else:\n nmr = int(nmr)\n unpacked = unpack_fraction(num)\n spoken = spoken_number(unpacked)\n return Fraction(repr or num, nmr / dnm, spoken, nmr, dnm, unpacked)\n # Handle Minus values with errors like 0M04\n if \"M\" in num:\n val = num.replace(\"M\", \"-\")\n while val[0] != \"-\":\n val = val[1:]\n else:\n val = num\n # Create Number\n if not val:\n return\n val = float(val) if \".\" in num else int(val)\n return Number(repr or num, val, spoken_number(speak or str(val)))\n\n\ndef find_first_in_list(txt: str, str_list: [str]) -> int:\n \"\"\"\n Returns the index of the earliest occurrence of an item from a list in a string\n\n Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3\n \"\"\"\n start = len(txt) + 1\n for item in str_list:\n if start > txt.find(item) > -1:\n start = txt.find(item)\n return start if len(txt) + 1 > start > -1 else -1\n\n\ndef is_timestamp(item: str) -> bool:\n \"\"\"\n Returns True if the item matches the timestamp format\n \"\"\"\n return len(item) == 7 and item[-1] == \"Z\" and item[:-1].isdigit()\n\n\ndef is_timerange(item: str) -> bool:\n \"\"\"\n Returns True if the item is a TAF to-from time range\n \"\"\"\n return (\n len(item) == 9 and item[4] == \"/\" and item[:4].isdigit() and item[5:].isdigit()\n )\n\n\nSTR_REPL = {\n \" C A V O K \": \" CAVOK \",\n \"?\": \" \",\n '\"': \"\",\n \"'\": \"\",\n \"`\": \"\",\n \".\": \"\",\n \" VTB\": \" VRB\",\n \" VBR\": \" VRB\",\n \" VBB\": \" VRB\",\n \" ERB\": \" VRB\",\n \" VRV\": \" VRB\",\n \" BRV\": \" VRB\",\n \" VRN\": \" VRB\",\n \" BRB\": \" VRB\",\n \" VEB\": \" VRB\",\n \" VFB\": \" VRB\",\n \" VAB\": \" VRB\",\n \" VAR\": \" VRB\",\n \" VRG\": \" VRB\",\n \" VRR\": \" VRB\",\n \" VGB\": \" VRB\",\n \" VRC\": \" VRB\",\n \" WBB\": \" VRB\",\n \" VR0\": \" VRB0\",\n \" VB0\": \" VRB0\",\n \" RB0\": \" VRB0\",\n \" V0\": \" VRB0\",\n \" 0I0\": \" 090\",\n # \"Z/ \": \"Z \", NOTE: Too broad re pirep\n \"KKT \": \"KT \",\n \"KLT \": \"KT \",\n \"CALMKT \": \"CALM \",\n \"N0SIG\": \"NOSIG\",\n \" <1/\": \" M1/\", # <1/4SM <1/8SM\n \" /34SM\": \"3/4SM\",\n}\n\n\ndef sanitize_report_string(txt: str) -> str:\n \"\"\"\n Provides sanitization for operations that work better when the report is a string\n\n Returns the first pass sanitized report string\n \"\"\"\n txt = txt.upper()\n if len(txt) < 4:\n return txt\n # Standardize whitespace\n txt = \" \".join(txt.split())\n # Prevent changes to station ID\n stid, txt = txt[:4], txt[4:]\n # Replace invalid key-value pairs\n for key, rep in STR_REPL.items():\n txt = txt.replace(key, rep)\n # Check for missing spaces in front of cloud layers\n # Ex: TSFEW004SCT012FEW///CBBKN080\n for cloud in CLOUD_LIST:\n if cloud in txt and \" \" + cloud not in txt:\n start, counter = 0, 0\n while txt.count(cloud) != txt.count(\" \" + cloud):\n cloud_index = start + txt[start:].find(cloud)\n if len(txt[cloud_index:]) >= 3:\n target = txt[\n cloud_index + len(cloud) : cloud_index + len(cloud) + 3\n ]\n if target.isdigit() or not target.strip(\"/\"):\n txt = txt[:cloud_index] + \" \" + txt[cloud_index:]\n start = cloud_index + len(cloud) + 1\n # Prevent infinite loops\n if counter > txt.count(cloud):\n break\n counter += 1\n return stid + txt\n\n\ndef extra_space_exists(str1: str, str2: str) -> bool:\n \"\"\"\n Return True if a space shouldn't exist between two items\n \"\"\"\n ls1, ls2 = len(str1), len(str2)\n if str1.isdigit():\n # 10 SM\n if str2 in [\"SM\", \"0SM\"]:\n return True\n # 12 /10\n if ls2 > 2 and str2[0] == \"/\" and str2[1:].isdigit():\n return True\n if str2.isdigit():\n # OVC 040\n if str1 in CLOUD_LIST:\n return True\n # 12/ 10\n if ls1 > 2 and str1.endswith(\"/\") and str1[:-1].isdigit():\n return True\n # 12/1 0\n if (\n ls2 == 1\n and ls1 > 3\n and str1[:2].isdigit()\n and \"/\" in str1\n and str1[3:].isdigit()\n ):\n return True\n # Q 1001\n if str1 in [\"Q\", \"A\"]:\n return True\n # 36010G20 KT\n if (\n str2 == \"KT\"\n and str1[-1].isdigit()\n and (str1[:5].isdigit() or (str1.startswith(\"VRB\") and str1[3:5].isdigit()))\n ):\n return True\n # 36010K T\n if (\n str2 == \"T\"\n and ls1 >= 6\n and (str1[:5].isdigit() or (str1.startswith(\"VRB\") and str1[3:5].isdigit()))\n and str1[-1] == \"K\"\n ):\n return True\n # OVC022 CB\n if (\n str2 in CLOUD_TRANSLATIONS\n and str2 not in CLOUD_LIST\n and ls1 >= 3\n and str1[:3] in CLOUD_LIST\n ):\n return True\n # FM 122400\n if str1 in [\"FM\", \"TL\"] and (\n str2.isdigit() or (str2.endswith(\"Z\") and str2[:-1].isdigit())\n ):\n return True\n # TX 20/10\n if str1 in [\"TX\", \"TN\"] and str2.find(\"/\") != -1:\n return True\n return False\n\n\n_cloud_group = \"(\" + \"|\".join(CLOUD_LIST) + \")\"\nCLOUD_SPACE_PATTERNS = [\n re.compile(pattern)\n for pattern in (\n r\"(?=.+)\" + _cloud_group + r\"\\d{3}(\\w{2,3})?$\", # SCT010BKN021\n r\"M?\\d{2}\\/M?\\d{2}$\", # BKN01826/25\n )\n]\n\n\ndef extra_space_needed(item: str) -> int:\n \"\"\"\n Returns the index where the string should be separated or None\n \"\"\"\n # For items starting with cloud list\n if item[:3] in CLOUD_LIST:\n for pattern in CLOUD_SPACE_PATTERNS:\n sep = pattern.search(item)\n if sep is None:\n continue\n if sep.start():\n return sep.start()\n # Connected timestamp\n for loc, check in ((7, is_timestamp), (9, is_timerange)):\n if len(item) > loc and check(item[:loc]):\n return loc\n # Connected to wind\n if len(item) > 5 and \"KT\" in item and not item.endswith(\"KT\"):\n sep = item.find(\"KT\")\n if sep > 4:\n return sep + 2\n # TAF newline connected to previous element\n for key in TAF_NEWLINE:\n if key in item and not item.startswith(key):\n return item.find(key)\n for key in TAF_NEWLINE_STARTSWITH:\n if key in item and not item.startswith(key):\n sep = item.find(key)\n if item[sep + len(key) :].isdigit():\n return sep\n\n\nITEM_REMV = [\n \"AUTO\",\n \"COR\",\n \"NSC\",\n \"NCD\",\n \"$\",\n \"KT\",\n \"M\",\n \".\",\n \"RTD\",\n \"SPECI\",\n \"METAR\",\n \"CORR\",\n \"TTF\",\n]\nITEM_REPL = {\"CALM\": \"00000KT\"}\nVIS_PERMUTATIONS = [\"\".join(p) for p in permutations(\"P6SM\")]\nVIS_PERMUTATIONS.remove(\"6MPS\")\n\n\ndef sanitize_report_list(wxdata: [str], remove_clr_and_skc: bool = True) -> [str]:\n \"\"\"\n Sanitize wxData\n\n We can remove and identify \"one-off\" elements and fix other issues before parsing a line\n \"\"\"\n for i, item in reversed(list(enumerate(wxdata))):\n ilen = len(item)\n # Remove elements containing only '/'\n if is_unknown(item):\n wxdata.pop(i)\n continue\n # Remove empty wind /////KT\n if item.endswith(\"KT\") and is_unknown(item[:-2]):\n wxdata.pop(i)\n continue\n # Remove RE from wx codes, REVCTS -> VCTS\n elif ilen in [4, 6] and item.startswith(\"RE\"):\n wxdata[i] = item[2:]\n # Fix a slew of easily identifiable conditions where a space does not belong\n elif i and extra_space_exists(wxdata[i - 1], item):\n wxdata[i - 1] += wxdata.pop(i)\n # Remove spurious elements\n elif item in ITEM_REMV:\n wxdata.pop(i)\n # Remove 'Sky Clear' from METAR but not TAF\n elif remove_clr_and_skc and item in [\"CLR\", \"SKC\"]:\n wxdata.pop(i)\n # Replace certain items\n elif item in ITEM_REPL:\n wxdata[i] = ITEM_REPL[item]\n # Remove amend signifier from start of report ('CCA', 'CCB',etc)\n elif ilen == 3 and item.startswith(\"CC\") and item[2].isalpha():\n wxdata.pop(i)\n # Fix inconsistent 'P6SM' Ex: TP6SM or 6PSM -> P6SM\n elif ilen > 3 and item[-4:] in VIS_PERMUTATIONS:\n wxdata[i] = \"P6SM\"\n # Fix misplaced KT 22022KTG40\n elif ilen == 10 and \"KTG\" in item and item[:5].isdigit():\n wxdata[i] = item.replace(\"KTG\", \"G\") + \"KT\"\n # Fix backwards KT Ex: 06012G22TK\n if (\n ilen >= 7\n and (item[:3].isdigit() or item[:3] == \"VRB\")\n and item.endswith(\"TK\")\n ):\n wxdata[i] = item[:-2] + \"KT\"\n # Fix gust double G Ex: 360G17G32KT\n elif ilen > 10 and item.endswith(\"KT\") and item[3] == \"G\":\n wxdata[i] = item[:3] + item[4:]\n # Fix leading character mistypes in wind\n elif (\n ilen > 7\n and not item[0].isdigit()\n and not item.startswith(\"VRB\")\n and item.endswith(\"KT\")\n and not item.startswith(\"WS\")\n ):\n while not item[0].isdigit() and not item.startswith(\"VRB\"):\n item = item[1:]\n wxdata[i] = item\n # Fix non-G gust Ex: 14010-15KT\n elif ilen == 10 and item.endswith(\"KT\") and item[5] != \"G\":\n wxdata[i] = item[:5] + \"G\" + item[6:]\n # Fix leading digits on VRB wind Ex: 2VRB02KT\n elif (\n ilen > 7\n and item.endswith(\"KT\")\n and \"VRB\" in item\n and item[0].isdigit()\n and \"Z\" not in item\n ):\n while item[0].isdigit():\n item = item[1:]\n wxdata[i] = item\n # Fix wind T\n elif not item.endswith(\"KT\") and (\n (\n ilen == 6\n and item[5] in [\"K\", \"T\"]\n and (\n item[:5].isdigit()\n or (item.startswith(\"VRB\") and item[:3].isdigit())\n )\n )\n or (\n ilen == 9\n and item[8] in [\"K\", \"T\"]\n and item[5] == \"G\"\n and (item[:5].isdigit() or item.startswith(\"VRB\"))\n )\n ):\n wxdata[i] = item[:-1] + \"KT\"\n # Fix joined TX-TN\n elif ilen > 16 and len(item.split(\"/\")) == 3:\n if item.startswith(\"TX\") and \"TN\" not in item:\n tn_index = item.find(\"TN\")\n wxdata.insert(i + 1, item[:tn_index])\n wxdata[i] = item[tn_index:]\n elif item.startswith(\"TN\") and item.find(\"TX\") != -1:\n tx_index = item.find(\"TX\")\n wxdata.insert(i + 1, item[:tx_index])\n wxdata[i] = item[tx_index:]\n # Fix situations where a space is missing\n sep = extra_space_needed(item)\n if sep:\n wxdata.insert(i + 1, item[sep:])\n wxdata[i] = item[:sep]\n wxdata = dedupe(wxdata, only_neighbors=True)\n return wxdata\n\n\ndef is_possible_temp(temp: str) -> bool:\n \"\"\"\n Returns True if all characters are digits or 'M' (for minus)\n \"\"\"\n for char in temp:\n if not (char.isdigit() or char == \"M\"):\n return False\n return True\n\n\ndef get_station_and_time(wxdata: [str]) -> ([str], str, str):\n \"\"\"\n Returns the report list and removed station ident and time strings\n \"\"\"\n if not wxdata:\n return wxdata, None, None\n station = wxdata.pop(0)\n if not wxdata:\n return wxdata, station, None\n qtime = wxdata[0]\n if wxdata and qtime.endswith(\"Z\") and qtime[:-1].isdigit():\n rtime = wxdata.pop(0)\n elif wxdata and len(qtime) == 6 and qtime.isdigit():\n rtime = wxdata.pop(0) + \"Z\"\n else:\n rtime = None\n return wxdata, station, rtime\n\n\ndef get_wind(wxdata: [str], units: Units) -> ([str], Number, Number, Number, [Number]):\n \"\"\"\n Returns the report list and removed:\n Direction string, speed string, gust string, variable direction list\n \"\"\"\n direction, speed, gust = \"\", \"\", \"\"\n variable = []\n if wxdata:\n item = copy(wxdata[0])\n for rep in [\"(E)\"]:\n item = item.replace(rep, \"\")\n for replacements in ((\"O\", \"0\"), (\"/\", \"\"), (\"LKT\", \"KT\"), (\"GG\", \"G\")):\n item = item.replace(*replacements)\n # 09010KT, 09010G15KT\n if (\n item.endswith(\"KT\")\n or item.endswith(\"KTS\")\n or item.endswith(\"MPS\")\n or item.endswith(\"KMH\")\n or (\n (\n len(item) == 5\n or (len(item) >= 8 and item.find(\"G\") != -1)\n and item.find(\"/\") == -1\n )\n and (\n item[:5].isdigit()\n or (item.startswith(\"VRB\") and item[3:5].isdigit())\n )\n )\n ):\n # In order of frequency\n if item.endswith(\"KT\"):\n item = item.replace(\"KT\", \"\")\n elif item.endswith(\"KTS\"):\n item = item.replace(\"KTS\", \"\")\n elif item.endswith(\"MPS\"):\n units.wind_speed = \"m/s\"\n item = item.replace(\"MPS\", \"\")\n elif item.endswith(\"KMH\"):\n units.wind_speed = \"km/h\"\n item = item.replace(\"KMH\", \"\")\n direction = item[:3]\n if \"G\" in item:\n g_index = item.find(\"G\")\n gust = item[g_index + 1 :]\n speed = item[3:g_index]\n else:\n speed = item[3:]\n direction = item[:3]\n wxdata.pop(0)\n # Separated Gust\n if (\n wxdata\n and 1 < len(wxdata[0]) < 4\n and wxdata[0][0] == \"G\"\n and wxdata[0][1:].isdigit()\n ):\n gust = wxdata.pop(0)[1:]\n # Variable Wind Direction\n if (\n wxdata\n and len(wxdata[0]) == 7\n and wxdata[0][:3].isdigit()\n and wxdata[0][3] == \"V\"\n and wxdata[0][4:].isdigit()\n ):\n variable = [make_number(i, speak=i) for i in wxdata.pop(0).split(\"V\")]\n # Convert to Number\n direction = make_number(direction, speak=direction)\n speed = make_number(speed.strip(\"BV\"))\n gust = make_number(gust)\n return wxdata, direction, speed, gust, variable\n\n\ndef get_visibility(wxdata: [str], units: Units) -> ([str], Number):\n \"\"\"\n Returns the report list and removed visibility string\n \"\"\"\n visibility = \"\"\n if wxdata:\n item = copy(wxdata[0])\n # Vis reported in statue miles\n if item.endswith(\"SM\"): # 10SM\n if item in (\"P6SM\", \"M1/4SM\", \"M1/8SM\"):\n visibility = item[:-2]\n elif item[:-2].isdigit():\n visibility = str(int(item[:-2]))\n elif \"/\" in item:\n visibility = item[: item.find(\"SM\")] # 1/2SM\n wxdata.pop(0)\n units.visibility = \"sm\"\n # Vis reported in meters\n elif len(item) == 4 and item.isdigit():\n visibility = wxdata.pop(0)\n units.visibility = \"m\"\n elif (\n 7 >= len(item) >= 5\n and item[:4].isdigit()\n and (item[4] in [\"M\", \"N\", \"S\", \"E\", \"W\"] or item[4:] == \"NDV\")\n ):\n visibility = wxdata.pop(0)[:4]\n units.visibility = \"m\"\n elif len(item) == 5 and item[1:].isdigit() and item[0] in [\"M\", \"P\", \"B\"]:\n visibility = wxdata.pop(0)[1:]\n units.visibility = \"m\"\n elif item.endswith(\"KM\") and item[:-2].isdigit():\n visibility = item[:-2] + \"000\"\n wxdata.pop(0)\n units.visibility = \"m\"\n # Vis statute miles but split Ex: 2 1/2SM\n elif (\n len(wxdata) > 1\n and wxdata[1].endswith(\"SM\")\n and \"/\" in wxdata[1]\n and item.isdigit()\n ):\n vis1 = wxdata.pop(0) # 2\n vis2 = wxdata.pop(0).replace(\"SM\", \"\") # 1/2\n visibility = str(int(vis1) * int(vis2[2]) + int(vis2[0])) + vis2[1:] # 5/2\n units.visibility = \"sm\"\n return wxdata, make_number(visibility)\n\n\ndef sanitize_cloud(cloud: str) -> str:\n \"\"\"\n Fix rare cloud layer issues\n \"\"\"\n if len(cloud) < 4:\n return cloud\n if not cloud[3].isdigit() and cloud[3] not in (\"/\", \"-\"):\n if cloud[3] == \"O\":\n cloud = cloud[:3] + \"0\" + cloud[4:] # Bad \"O\": FEWO03 -> FEW003\n elif cloud[3] != \"U\": # Move modifiers to end: BKNC015 -> BKN015C\n cloud = cloud[:3] + cloud[4:] + cloud[3]\n return cloud\n\n\ndef make_cloud(cloud: str) -> Cloud:\n \"\"\"\n Returns a Cloud dataclass for a cloud string\n\n This function assumes the input is potentially valid\n \"\"\"\n els = {\"type\": None, \"base\": None, \"top\": None, \"modifier\": None}\n _c = sanitize_cloud(cloud).replace(\"/\", \"\")\n # Separate top\n topi = _c.find(\"-TOP\")\n if topi > -1:\n els[\"top\"], _c = _c[topi + 4 :], _c[:topi]\n # Separate type\n ## VV003\n if _c.startswith(\"VV\"):\n els[\"type\"], _c = _c[:2], _c[2:]\n ## FEW010\n elif len(_c) >= 3 and _c[:3] in CLOUD_LIST:\n els[\"type\"], _c = _c[:3], _c[3:]\n ## BKN-OVC065\n if len(_c) > 4 and _c[0] == \"-\" and _c[1:4] in CLOUD_LIST:\n els[\"type\"] += _c[:4]\n _c = _c[4:]\n # Separate base\n if len(_c) >= 3 and _c[:3].isdigit():\n els[\"base\"], _c = _c[:3], _c[3:]\n elif len(_c) >= 4 and _c[:4] == \"UNKN\":\n _c = _c[4:]\n # Remainder is considered modifiers\n if _c:\n els[\"modifier\"] = _c\n # Nullify unknown elements and convert ints\n for k, v in els.items():\n if not isinstance(v, str):\n continue\n if is_unknown(v):\n els[k] = None\n elif v.isdigit():\n els[k] = int(v)\n # Make Cloud\n return Cloud(cloud, **els)\n\n\ndef get_clouds(wxdata: [str]) -> ([str], list):\n \"\"\"\n Returns the report list and removed list of split cloud layers\n \"\"\"\n clouds = []\n for i, item in reversed(list(enumerate(wxdata))):\n if item[:3] in CLOUD_LIST or item[:2] == \"VV\":\n cloud = wxdata.pop(i)\n clouds.append(make_cloud(cloud))\n # Attempt cloud sort. Fails if None values are present\n try:\n clouds.sort(key=lambda cloud: (cloud.base, cloud.type))\n except TypeError:\n clouds.reverse() # Restores original report order\n return wxdata, clouds\n\n\ndef get_flight_rules(vis: Number, ceiling: Cloud) -> int:\n \"\"\"\n Returns int based on current flight rules from parsed METAR data\n\n 0=VFR, 1=MVFR, 2=IFR, 3=LIFR\n\n Note: Common practice is to report IFR if visibility unavailable\n \"\"\"\n # Parse visibility\n if not vis:\n return 2\n if vis.repr == \"CAVOK\" or vis.repr.startswith(\"P6\"):\n vis = 10\n elif vis.repr.startswith(\"M\"):\n vis = 0\n # Convert meters to miles\n elif len(vis.repr) == 4:\n vis = vis.value * 0.000621371\n else:\n vis = vis.value\n # Parse ceiling\n cld = ceiling.base if ceiling else 99\n # Determine flight rules\n if (vis <= 5) or (cld <= 30):\n if (vis < 3) or (cld < 10):\n if (vis < 1) or (cld < 5):\n return 3 # LIFR\n return 2 # IFR\n return 1 # MVFR\n return 0 # VFR\n\n\ndef get_ceiling(clouds: [Cloud]) -> Cloud:\n \"\"\"\n Returns ceiling layer from Cloud-List or None if none found\n\n Assumes that the clouds are already sorted lowest to highest\n\n Only 'Broken', 'Overcast', and 'Vertical Visibility' are considered ceilings\n\n Prevents errors due to lack of cloud information (eg. '' or 'FEW///')\n \"\"\"\n for cloud in clouds:\n if cloud.base and cloud.type in (\"OVC\", \"BKN\", \"VV\"):\n return cloud\n return None\n\n\ndef parse_date(\n date: str, hour_threshold: int = 200, time_only: bool = False\n) -> datetime:\n \"\"\"\n Parses a report timestamp in ddhhZ or ddhhmmZ format\n\n If time_only, assumes hhmm format with current or previous day\n\n This function assumes the given timestamp is within the hour threshold from current date\n \"\"\"\n # Format date string\n date = date.strip(\"Z\")\n if not date.isdigit():\n return\n if time_only:\n if len(date) != 4:\n return\n ihour = 0\n else:\n if len(date) == 4:\n date += \"00\"\n if len(date) != 6:\n return\n ihour = 2\n # Create initial guess\n now = datetime.now(tz=timezone.utc)\n day = now.day if time_only else int(date[0:2])\n # Handle situation where next month has less days than current month\n # Shifted value makes sure that a month shift doesn't happen twice\n shifted = False\n if day > monthrange(now.year, now.month)[1]:\n now += relativedelta(months=-1)\n shifted = True\n try:\n guess = now.replace(\n day=day,\n hour=int(date[ihour : ihour + 2]) % 24,\n minute=int(date[ihour + 2 : ihour + 4]) % 60,\n second=0,\n microsecond=0,\n )\n except ValueError:\n return\n # Handle changing months if not already shifted\n if not shifted:\n hourdiff = (guess - now) / timedelta(minutes=1) / 60\n if hourdiff > hour_threshold:\n guess += relativedelta(months=-1)\n elif hourdiff < -hour_threshold:\n guess += relativedelta(months=+1)\n return guess\n\n\ndef make_timestamp(timestamp: str, time_only: bool = False) -> Timestamp:\n \"\"\"\n Returns a Timestamp dataclass for a report timestamp in ddhhZ or ddhhmmZ format\n \"\"\"\n if timestamp:\n return Timestamp(timestamp, parse_date(timestamp, time_only=time_only))\n", "sub_path": "avwx/parsing/core.py", "file_name": "core.py", "file_ext": "py", "file_size_in_byte": 25405, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "avwx.static.core.FRACTIONS", "line_number": 105, "usage_type": "name"}, {"api_name": "avwx.static.core.FRACTIONS", "line_number": 106, "usage_type": "name"}, {"api_name": "avwx.static.core.NUMBER_REPL", "line_number": 109, "usage_type": "name"}, {"api_name": "avwx.static.core.SPECIAL_NUMBERS", "line_number": 123, "usage_type": "name"}, {"api_name": "avwx.structs.Number", "line_number": 124, "usage_type": "call"}, {"api_name": "avwx.static.core.SPECIAL_NUMBERS", "line_number": 124, "usage_type": "name"}, {"api_name": "avwx.static.core.CARDINALS", "line_number": 126, "usage_type": "name"}, {"api_name": "avwx.static.core.CARDINALS", "line_number": 129, "usage_type": "name"}, {"api_name": "avwx.structs.Fraction", "line_number": 146, "usage_type": "call"}, {"api_name": "avwx.structs.Number", "line_number": 158, "usage_type": "call"}, {"api_name": "avwx.structs.Number", "line_number": 114, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 247, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 280, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_TRANSLATIONS", "line_number": 314, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 315, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 317, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 331, "usage_type": "argument"}, {"api_name": "re.compile", "line_number": 333, "usage_type": "call"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 346, "usage_type": "name"}, {"api_name": "avwx.static.taf.TAF_NEWLINE", "line_number": 363, "usage_type": "name"}, {"api_name": "avwx.static.taf.TAF_NEWLINE_STARTSWITH", "line_number": 366, "usage_type": "name"}, {"api_name": "itertools.permutations", "line_number": 389, "usage_type": "call"}, {"api_name": "avwx.structs.Units", "line_number": 534, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 542, "usage_type": "call"}, {"api_name": "avwx.structs.Number", "line_number": 534, "usage_type": "name"}, {"api_name": "avwx.structs.Units", "line_number": 609, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 615, "usage_type": "call"}, {"api_name": "avwx.structs.Number", "line_number": 609, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 689, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 692, "usage_type": "name"}, {"api_name": "avwx.structs.Cloud", "line_number": 712, "usage_type": "call"}, {"api_name": "avwx.structs.Cloud", "line_number": 672, "usage_type": "name"}, {"api_name": "avwx.static.core.CLOUD_LIST", "line_number": 721, "usage_type": "name"}, {"api_name": "avwx.structs.Number", "line_number": 732, "usage_type": "name"}, {"api_name": "avwx.structs.Cloud", "line_number": 732, "usage_type": "name"}, {"api_name": "avwx.structs.Cloud", "line_number": 764, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 805, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 805, "usage_type": "name"}, {"api_name": "datetime.timezone.utc", "line_number": 805, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 805, "usage_type": "name"}, {"api_name": "calendar.monthrange", "line_number": 810, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 811, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 825, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 827, "usage_type": "call"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 829, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 782, "usage_type": "name"}, {"api_name": "avwx.structs.Timestamp", "line_number": 838, "usage_type": "call"}, {"api_name": "avwx.structs.Timestamp", "line_number": 833, "usage_type": "name"}]} +{"seq_id": "539465746", "text": "# coding: utf-8\n\"\"\"\n決算短信のB/S,P/L.CFをスクレイピングするプログラム\n2014年2月以前:xbrl\n2014年2月以降:htm\n\"\"\"\n\nfrom __future__ import division, unicode_literals\nimport re\nimport locale\nfrom datetime import datetime as dt\n\nlocale.setlocale(locale.LC_NUMERIC, '')\n\n\ndef get_company_cd(_filename, version):\n \"\"\"\n filenameから証券codeを取り出す\n :param _filename: filename\n :param version: new or old\n \"\"\"\n try:\n if version == \"new\":\n return int(_filename[28:32])\n else:\n return int(_filename[15:19])\n\n except Exception as e:\n print(e)\n return None\n\n\ndef get_date(_filename, version):\n \"\"\"filenameからend_dateを取りだす\"\"\"\n try:\n if version == \"new\":\n return str(_filename[34:44])\n else:\n return str(_filename[21:31])\n except Exception as e:\n print(e)\n return None\n\n\ndef get_term(_end_day):\n \"\"\"終了期日から第何期かを返す\"\"\"\n _end_month = dt.strptime(_end_day, '%Y-%m-%d')\n try:\n month = _end_month.month\n if month == 6:\n return 1\n elif month == 9:\n return 2\n elif month == 12:\n return 3\n else:\n return 4\n except AttributeError as e:\n print(e)\n return 0\n\n\ndef get_next_term(_soup, _filename):\n \"\"\"連結と非連結で場合分けして翌期を返す\"\"\"\n try:\n # 連結\n if _filename[5] == 'c':\n # 通期\n if _filename[4] == 'a':\n try:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextref': r'NextYearDuration_ConsolidatedMember_ForecastMember'})\n except:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextRef': r'NextYearDuration_ConsolidatedMember_ForecastMember'})\n # 四半期・中間期\n else:\n try:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextref': r'CurrentYearDuration_ConsolidatedMember_ForecastMember'})\n except:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextRef': r'CurrentYearDuration_ConsolidatedMember_ForecastMember'})\n # 非連結\n else:\n # 通期\n if _filename[4] == 'a':\n try:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextref': r'NextYearDuration_NonConsolidatedMember_ForecastMember'})\n except:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextRef': r'NextYearDuration_NonConsolidatedMember_ForecastMember'})\n # 四半期・中間期\n else:\n try:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextref': r'CurrentYearDuration_NonConsolidatedMember_ForecastMember'})\n except:\n _res = _soup.find(attrs={'name': r'tse-ed-t:TitleForForecasts',\n 'contextRef': r'CurrentYearDuration_NonConsolidatedMember_ForecastMember'})\n _res = _res.string\n _res = re.findall(r'平成.*?期', _res)[0]\n return _res\n except:\n return None\n\n\ndef get_type(_filename):\n \"\"\"連結か非連結かを調べて返す\"\"\"\n try:\n if _filename[5] == 'c':\n return '連結'\n else:\n return '非連結'\n except:\n return None\n\n\ndef get_gyo(_soup, _filename, gyo_dic, version):\n \"\"\"\n fileから決算情報を抽出\n :param _soup : soup\n :param _filename : filename\n :param gyo_dic : value of gyo_dics\n :param version :[old, new]\n \"\"\"\n try:\n # - 新規格\n if version == 'new':\n _res = _soup.find(attrs={\n 'name': re.compile(gyo_dic['new']['name'])\n , 'contextref': re.compile(gyo_dic['new']['contextref'][_filename[8:10]])})\n scale = int(_res.attrs['scale'])\n if 'sign' in _res.attrs:\n _res = -locale.atof(_res.string.replace(',', '')) * (10 ** scale)\n else:\n _res = locale.atof(_res.string.replace(',', '')) * (10 ** scale)\n # - 旧規格\n else:\n _res = _soup.find(\n re.compile(gyo_dic['old']['name'])\n , contextref=re.compile(gyo_dic['old']['contextref'][_filename[6:8]]))\n _res = locale.atof(_res.string.replace(',', ''))\n\n except:\n _res = None\n return _res\n", "sub_path": "edinet/xbrl_functions_tdnet.py", "file_name": "xbrl_functions_tdnet.py", "file_ext": "py", "file_size_in_byte": 4968, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "locale.setlocale", "line_number": 13, "usage_type": "call"}, {"api_name": "locale.LC_NUMERIC", "line_number": 13, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 103, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 132, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 133, "usage_type": "call"}, {"api_name": "locale.atof", "line_number": 136, "usage_type": "call"}, {"api_name": "locale.atof", "line_number": 138, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 142, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 143, "usage_type": "call"}, {"api_name": "locale.atof", "line_number": 144, "usage_type": "call"}]} +{"seq_id": "301581525", "text": "# Fast and convienent script for urand traffic benchmarks\r\n\r\n\"\"\" Import the necessary libraries \"\"\"\r\nimport sys\r\nimport os\r\nimport shutil\r\nimport subprocess\r\nimport xml.etree.ElementTree as ET\r\nimport csv\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom joblib import Parallel, delayed\r\nimport multiprocessing\r\nimport pickle\r\nimport configparser\r\n\r\n##################################################################################################\r\n\r\n\"\"\" Read the confgiuration file config.ini \"\"\"\r\nconfig = configparser.ConfigParser()\r\nconfig.read(\"config.ini\")\r\n\r\ntopologyFile = config['DEFAULT']['topologyFile']\r\nprint(topologyFile)\r\n\r\nlibdir = config['DEFAULT']['libdir']\r\nsimdir = config['DEFAULT']['simdir']\r\nbasedir = os.getcwd() \r\n\r\nsimulation_time = int(config['DEFAULT']['simulation_time'])\r\nrestarts = int(config['DEFAULT']['restarts'])\r\n\r\nbaseclock = int(config['DEFAULT']['baseclock'])\r\nflitsPerPacket = int(config['DEFAULT']['flitsPerPacket'])\r\n\r\nwarmup_start = int(config['DEFAULT']['warmup_start'])\r\nwarmup_duration = int(config['DEFAULT']['warmup_duration'])\r\nwarmup_rate = float(config['DEFAULT']['warmup_rate'])\r\n\r\nrun_rate_min = float(config['DEFAULT']['run_rate_min'])\r\nrun_rate_max = float(config['DEFAULT']['run_rate_max'])\r\nrun_rate_step = float(config['DEFAULT']['run_rate_step'])\r\nrun_start_after_warmup = int(config['DEFAULT']['run_start_after_warmup'])\r\nrun_start = warmup_start + warmup_duration + run_start_after_warmup\r\nrun_duration = int(config['DEFAULT']['run_duration'])\r\n\r\nnum_cores = int(config['DEFAULT']['num_cores'])\r\nif (num_cores == -1):\r\n num_cores = multiprocessing.cpu_count()\r\n\r\n##################################################################################################\r\n\r\ndef write_config_file(configFileSrc, configFileDst, injectionRate):\r\n \"\"\" Write the configuration file for the urand simulation \"\"\"\r\n try:\r\n configTree = ET.parse(configFileSrc)\r\n except Exception as e:\r\n raise\r\n \r\n configTree.find(\"noc/nocFile\").text = \"config/\" + topologyFile + \".xml\"\r\n \r\n configTree.find(\"general/simulationTime\").set(\"value\", str(simulation_time))\r\n configTree.find(\"general/outputToFile\").set(\"value\", \"true\")\r\n configTree.find(\"general/outputToFile\").text = \"report\"\r\n \r\n for elem in list(configTree.find(\"application/synthetic\").iter()):\r\n if elem.get(\"name\") == \"warmup\": \r\n elem.find(\"start\").set(\"min\",str(warmup_start))\r\n elem.find(\"start\").set(\"max\",str(warmup_start))\r\n elem.find(\"duration\").set(\"min\",str(warmup_start + warmup_duration))\r\n elem.find(\"duration\").set(\"max\",str(warmup_start + warmup_duration))\r\n sendPacketInterval = round(baseclock/warmup_rate, 2)\r\n elem.find(\"interval\").set(\"min\", str(sendPacketInterval)) #send every sendPacketInterval NS a packet with 10 flits\r\n elem.find(\"interval\").set(\"max\", str(sendPacketInterval)) \r\n if elem.get(\"name\") == \"run\": \r\n elem.find(\"start\").set(\"min\",str(run_start))\r\n elem.find(\"start\").set(\"max\",str(run_start))\r\n elem.find(\"duration\").set(\"min\",str(run_start + run_duration))\r\n elem.find(\"duration\").set(\"max\",str(run_start + run_duration)) \r\n sendPacketInterval = round(baseclock/injectionRate, 2)\r\n elem.find(\"interval\").set(\"min\", str(sendPacketInterval)) \r\n elem.find(\"interval\").set(\"max\", str(sendPacketInterval))\r\n repeatLength = round(run_duration/sendPacketInterval, 2)\r\n elem.find(\"repeat\").set(\"min\", str(repeatLength)) \r\n elem.find(\"repeat\").set(\"max\", str(repeatLength)) \r\n configTree.write(configFileDst)\r\n\r\n##################################################################################################\r\n\r\ndef write_sim_files(simdir):\r\n \"\"\" Write the files that are associated with each run of the simulation (the executable sim + the configuration file) \"\"\"\r\n confdir = simdir+\"/config\"\r\n shutil.rmtree(simdir, ignore_errors=True)\r\n try:\r\n os.makedirs(simdir)\r\n os.makedirs(confdir)\r\n except OSError as e:\r\n if e.errno != errno.EEXIST:\r\n raise\r\n \r\n #simulator\r\n shutil.copy(\"sim\", simdir)\r\n #topology file\r\n shutil.copy(libdir+\"/networks/\"+topologyFile+\".xml\", confdir)\r\n\r\n##################################################################################################\r\n \r\ndef run_simulation(simdir, basedir):\r\n \"\"\" Run a simulation \"\"\"\r\n os.chdir(simdir)\r\n args = (\"./sim\")\r\n outfile = open(\"log\",\"w\")\r\n popen = subprocess.Popen(args, stdout=outfile)#subprocess.PIPE)\r\n #print(popen.communicate())\r\n popen.wait()\r\n #output = popen.stdout.read()\r\n #print(output.decode('ascii'))\r\n os.chdir(basedir)\r\n\r\n##################################################################################################\r\n \r\ndef get_results(results_file):\r\n \"\"\" Read the resulting latencies from the csv file \"\"\"\r\n latencies = list()\r\n try:\r\n with open(results_file, newline='') as csvfile:\r\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\r\n for row in spamreader:\r\n latencies.append(row[1])\r\n except:\r\n \t#add dummy values to latencies, -1\r\n \tlatencies.append(-1)\r\n \tlatencies.append(-1)\r\n \tlatencies.append(-1)\r\n return(latencies)\r\n\r\n##################################################################################################\r\n\r\ndef processInput(restart, inj, injIter):\r\n \"\"\" Run a simulation with a specif injection rate \"\"\"\r\n print(\"Simulation with injection rate: \"+ str(inj[injIter])\\\r\n + \" restart \"+ str(restart))\r\n currentSimDir = simdir+str(restart)\r\n currentConfDir = currentSimDir+\"/config\" \r\n write_sim_files(currentSimDir) \r\n write_config_file(\"library/config.xml\", currentConfDir+\"/config.xml\", inj[injIter])\r\n run_simulation(currentSimDir, basedir)\r\n \r\n##################################################################################################\r\n \r\n \r\n\"\"\" Main point of execution \"\"\"\r\n\r\nprint(\"Generating urand simulation with injection rate from \" + \\\r\n str(run_rate_min)+ \" to \" + str(run_rate_max) + \" steps \" + \\\r\n str(run_rate_step))\r\n\r\n# Initialze the variables\r\ninjectionRates = np.arange(run_rate_min, run_rate_max, run_rate_step)\r\ninjectionRates = [round(elem, 4) for elem in injectionRates]\r\nlatenciesFlit = -np.ones((len(injectionRates), restarts))\r\nlatenciesPacket = -np.ones((len(injectionRates), restarts))\r\nlatenciesNetwork = -np.ones((len(injectionRates), restarts))\r\n\r\n# Run the full simulation (for all injection rates)\r\ninjIter = 0\r\nfor inj in injectionRates:\r\n print(\"Starting Sims with \"+ str(num_cores)+\" processes\")\r\n Parallel(n_jobs=num_cores)(delayed(processInput)\\\r\n (restart, injectionRates,injIter) for restart in range(restarts)) \r\n print(\"Executed all sims. Reading Results\")\r\n for restart in range(restarts): \r\n currentSimdir = 'sim'+str(restart)\r\n lat = get_results(currentSimdir+'/reportPerformance.csv')\r\n latenciesFlit[injIter, restart] = lat[0]\r\n latenciesPacket[injIter, restart] = lat[1]\r\n latenciesNetwork[injIter, restart] = lat[2]\r\n #input(\"press any key\")\r\n shutil.rmtree(currentSimdir)\r\n injIter += 1\r\n\r\n# After finishing the entire simulation, calculate the mean and standard deviation for each latency\r\nmeanLatenciesFlit = np.mean(latenciesFlit, axis=1)\r\nmeanLatenciesPacket = np.mean(latenciesPacket, axis=1)\r\nmeanLatenciesNetwork = np.mean(latenciesNetwork, axis=1) \r\nstdLatenciesFlit = np.std(latenciesFlit, axis=1)\r\nstdLatenciesPacket = np.std(latenciesPacket, axis=1)\r\nstdLatenciesNetwork = np.std(latenciesNetwork, axis=1)\r\n\r\n# Plot the graph of latencies\r\nfig = plt.figure()\r\nplt.ylabel('latencies in ns', fontsize = 11)\r\nplt.xlabel('injection rate', fontsize = 11)\r\nplt.xlim([0,1])\r\nlinestyle = {\"linestyle\":\"--\", \"linewidth\":1, \"markeredgewidth\":1, \"elinewidth\":1, \"capsize\":10}\r\nplt.errorbar(injectionRates, meanLatenciesFlit, yerr = stdLatenciesFlit, color=\"r\", **linestyle, marker = '*')\r\nplt.errorbar(injectionRates, meanLatenciesNetwork, yerr = stdLatenciesNetwork, color=\"b\", **linestyle, marker = 's')\r\nplt.errorbar(injectionRates, meanLatenciesPacket, yerr = stdLatenciesPacket, color=\"g\", **linestyle, marker = '^')\r\nplt.legend([\"Flit\",\"Network\", \"Packet\"])\r\nplt.show()\r\n\r\n# Save the configuration parameters and the results to a pickle file \r\nfile = \"rawResults\"\r\nwith open(file+\".pkl\", 'wb') as f: \r\n pickle.dump([latenciesFlit, latenciesNetwork, latenciesPacket, injectionRates, simulation_time, restarts, warmup_start, warmup_duration, warmup_rate, run_start_after_warmup, run_duration, topologyFile], f)\r\nf.close()\r\n", "sub_path": "scripts/urand/run_server.py", "file_name": "run_server.py", "file_ext": "py", "file_size_in_byte": 8845, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "configparser.ConfigParser", "line_number": 20, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 28, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 49, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 56, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 56, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 93, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 95, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 96, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 102, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 104, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 110, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 113, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 118, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 163, "usage_type": "call"}, {"api_name": "joblib.Parallel", "line_number": 169, "usage_type": "call"}, {"api_name": "joblib.delayed", "line_number": 169, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 197, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 197, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 198, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 205, "usage_type": "call"}]} +{"seq_id": "184265959", "text": "from django.shortcuts import render_to_response\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import RequestContext\nfrom django.shortcuts import HttpResponseRedirect\nfrom django.core.paginator import Paginator\n\nfrom django.core.urlresolvers import reverse_lazy\n\nfrom django.views.generic import (CreateView, DeleteView, DetailView, ListView)\nfrom .models import Article\nfrom .forms import ArticleForm\n\n\ndef article_list(request, pg=None):\n pg = 1 if pg is None else int(pg) + 1\n paginator = Paginator(Article.objects.all(), 10)\n if pg > paginator.num_pages:\n return HttpResponseRedirect('/')\n curpage = paginator.page(pg)\n return render_to_response(\n \"articles/article_list.html\",\n {\"page_obj\": curpage, 'object_list': curpage.object_list},\n context_instance=RequestContext(request)\n )\n\n\nclass ArticleCreateView(CreateView):\n model = Article\n fields = ['title', 'image', 'content']\n def get_form_class(self):\n return ArticleForm\n\n def form_valid(self, *args, **kwargs):\n resp = super(ArticleCreateView, self).form_valid(*args, **kwargs)\n return resp\n\n\nclass ArticleDetailView(DetailView):\n model = Article\n\n\ndef create_or_update_article(request):\n pk = request.REQUEST.get('id')\n instance = None if pk is None else get_object_or_404(Article, id=pk)\n if request.method == 'GET':\n form = ArticleForm(instance=instance)\n\n if request.method == 'POST':\n form = ArticleForm(request.POST, request.FILES, instance=instance)\n if form.is_valid():\n instance = form.save()\n return HttpResponseRedirect(instance.get_absolute_url())\n\n return render_to_response(\n \"articles/article_form.html\",\n {\"object\": instance, 'form': form},\n context_instance=RequestContext(request)\n )\n\n\nclass ArticleDeleteView(DeleteView):\n model = Article\n success_url = reverse_lazy('index')\n", "sub_path": "articles/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1947, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.core.paginator.Paginator", "line_number": 16, "usage_type": "call"}, {"api_name": "models.Article.objects.all", "line_number": 16, "usage_type": "call"}, {"api_name": "models.Article.objects", "line_number": 16, "usage_type": "attribute"}, {"api_name": "models.Article", "line_number": 16, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 18, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 20, "usage_type": "call"}, {"api_name": "django.shortcuts.RequestContext", "line_number": 23, "usage_type": "call"}, {"api_name": "django.views.generic.CreateView", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Article", "line_number": 28, "usage_type": "name"}, {"api_name": "forms.ArticleForm", "line_number": 31, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 38, "usage_type": "name"}, {"api_name": "models.Article", "line_number": 39, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 44, "usage_type": "argument"}, {"api_name": "forms.ArticleForm", "line_number": 46, "usage_type": "call"}, {"api_name": "forms.ArticleForm", "line_number": 49, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 52, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 54, "usage_type": "call"}, {"api_name": "django.shortcuts.RequestContext", "line_number": 57, "usage_type": "call"}, {"api_name": "django.views.generic.DeleteView", "line_number": 61, "usage_type": "name"}, {"api_name": "models.Article", "line_number": 62, "usage_type": "name"}, {"api_name": "django.core.urlresolvers.reverse_lazy", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "435255624", "text": "\"\"\"Dark magics about variable name in python\"\"\"\nimport ast\nimport dis\nimport sys\nimport inspect\nimport warnings\nfrom typing import Callable, List, Union, Tuple, Any, Optional\nfrom types import FrameType, CodeType, ModuleType\nfrom collections import namedtuple as standard_namedtuple\nfrom functools import wraps, lru_cache\n\nimport executing\n\n__version__ = \"0.5.6\"\n__all__ = [\n \"VarnameRetrievingError\", \"varname\", \"will\", \"inject_varname\",\n \"register\", \"inject\", \"nameof\", \"namedtuple\", \"Wrapper\", \"debug\"\n]\n\n# To show how the desired frame is selected and other frames are skipped\nDEBUG = False\n\nclass VarnameRetrievingError(Exception):\n \"\"\"When failed to retrieve the varname\"\"\"\n\ndef varname(\n caller: int = 1,\n ignore: Optional[\n List[Union[ModuleType, Tuple[ModuleType, str]]]\n ] = None,\n multi_vars: bool = False,\n raise_exc: bool = True\n) -> Optional[Union[str, Tuple[Union[str, tuple]]]]:\n \"\"\"Get the variable name that assigned by function/class calls\n\n To debug and specify the right caller and ignore arguments, you can set\n debug on and see how the frames are ignored or selected:\n\n >>> import varname\n >>> varname.DEBUG = True\n\n Args:\n caller: The call frame index, indicating where this function\n is called relative to where the variable is finally retrieved\n Frames are counted with the ignored ones being excluded.\n See `ignore` for frames to be ignored.\n ignore: A list of modules or tuples of module and qualname that\n you want to ignore for the intermediate calls.\n For example, `['module']` ignores all intermediate calls\n from `module` and its submodules, but `[(module, 'func')]`\n only ignores the calls (qual)named `func` from `module`.\n By default, all calls from `varname` and builtin modules\n (in `sys.builtin_module_names`) are ignored.\n Note that the qualname in the module should exist and be unique.\n multi_vars: Whether allow multiple variables on left-hand side (LHS).\n If `True`, this function returns a tuple of the variable names,\n even there is only one variable on LHS.\n If `False`, and multiple variables on LHS, a\n `VarnameRetrievingError` will be raised.\n raise_exc: Whether we should raise an exception if failed\n to retrieve the name.\n\n Returns:\n The variable name, or `None` when `raise_exc` is `False` and\n we failed to retrieve the variable name.\n A tuple or a hierarchy (tuple of tuples) of variable names\n when `multi_vars` is `True`.\n\n Raises:\n VarnameRetrievingError: When there is invalid variables or\n invalid number of variables used on the LHS; or\n when we are unable to retrieve the variable name and `raise_exc`\n is set to `True`.\n\n UserWarning: When there are multiple target\n in the assign node. (e.g: `a = b = func()`, in such a case,\n `b == 'a'`, may not be the case you want)\n \"\"\"\n ignore = ignore or []\n _check_qualname(ignore)\n # Skip one more frame, as it is supposed to be called\n # inside another function\n node = _get_node(caller + 1, ignore, raise_exc=raise_exc)\n if not node:\n if raise_exc:\n raise VarnameRetrievingError(\"Unable to retrieve the ast node.\")\n return None\n\n node = _lookfor_parent_assign(node)\n if not node:\n if raise_exc:\n raise VarnameRetrievingError(\n 'Failed to retrieve the variable name.'\n )\n return None\n\n if isinstance(node, ast.AnnAssign):\n target = node.target\n else:\n # Need to actually check that there's just one\n # give warnings if: a = b = func()\n if len(node.targets) > 1:\n warnings.warn(\"Multiple targets in assignment, variable name \"\n \"on the very left will be used.\",\n UserWarning)\n target = node.targets[0]\n\n names = _node_name(target)\n\n if not isinstance(names, tuple):\n names = (names, )\n\n if multi_vars:\n return names\n\n if len(names) > 1:\n raise VarnameRetrievingError(\n f\"Expecting a single variable on left-hand side, got {len(names)}.\"\n )\n\n return names[0]\n\ndef will(caller: int = 1, raise_exc: bool = True) -> Optional[str]:\n \"\"\"Detect the attribute name right immediately after a function call.\n\n Examples:\n >>> class AwesomeClass:\n >>> def __init__(self):\n >>> self.will = None\n\n >>> def permit(self):\n >>> self.will = will()\n >>> if self.will == 'do':\n >>> # let self handle do\n >>> return self\n >>> raise AttributeError(\n >>> 'Should do something with AwesomeClass object'\n >>> )\n\n >>> def do(self):\n >>> if self.will != 'do':\n >>> raise AttributeError(\"You don't have permission to do\")\n >>> return 'I am doing!'\n\n >>> awesome = AwesomeClass()\n >>> # AttributeError: You don't have permission to do\n >>> awesome.do()\n >>> # AttributeError: Should do something with AwesomeClass object\n >>> awesome.permit()\n >>> awesome.permit().do() == 'I am doing!'\n\n Args:\n caller: At which stack this function is called.\n raise_exc: Raise exception we failed to detect\n\n Returns:\n The attribute name right after the function call\n If there is no attribute attached and `raise_exc` is `False`\n\n Raises:\n VarnameRetrievingError: When `raise_exc` is `True` and we failed to\n detect the attribute name (including not having one)\n \"\"\"\n node = _get_node(caller + 1, raise_exc=raise_exc)\n if not node:\n if raise_exc:\n raise VarnameRetrievingError(\"Unable to retrieve the frame.\")\n return None\n\n # try to get node inst.attr from inst.attr()\n node = node.parent\n\n # see test_will_fail\n if not isinstance(node, ast.Attribute):\n if raise_exc:\n raise VarnameRetrievingError(\n \"Function `will` has to be called within \"\n \"a method/property of a class.\"\n )\n return None\n # ast.Attribute\n return node.attr\n\ndef register(\n cls: type = None, *,\n caller: int = 1,\n multi_vars: bool = False,\n raise_exc: bool = True\n) -> Union[type, Callable[[type], type]]:\n \"\"\"A decorator to inject __varname__ attribute to a class\n\n Args:\n caller: The call stack index, indicating where this class\n is instantiated relative to where the variable is finally retrieved\n multi_vars: Whether allow multiple variables on left-hand side (LHS).\n If `True`, this function returns a tuple of the variable names,\n even there is only one variable on LHS.\n If `False`, and multiple variables on LHS, a\n `VarnameRetrievingError` will be raised.\n raise_exc: Whether we should raise an exception if failed\n to retrieve the name.\n\n Examples:\n >>> @varname.register\n >>> class Foo: pass\n >>> foo = Foo()\n >>> # foo.__varname__ == 'foo'\n\n Returns:\n The wrapper function or the class itself if it is specified explictly.\n \"\"\"\n\n if cls is not None:\n # Used as @register directly\n return register(\n caller=caller,\n multi_vars=multi_vars,\n raise_exc=raise_exc\n )(cls)\n\n # Used as @register(multi_vars=..., raise_exc=...)\n def wrapper(cls):\n \"\"\"The wrapper function to wrap a class and inject `__varname__`\"\"\"\n orig_init = cls.__init__\n\n @wraps(cls.__init__)\n def wrapped_init(self, *args, **kwargs):\n \"\"\"Wrapped init function to replace the original one\"\"\"\n self.__varname__ = varname(\n caller=caller-1,\n multi_vars=multi_vars,\n raise_exc=raise_exc\n )\n orig_init(self, *args, **kwargs)\n\n cls.__init__ = wrapped_init\n return cls\n\n return wrapper\n\ndef inject_varname(\n cls: type = None, *,\n caller: int = 1,\n multi_vars: bool = False,\n raise_exc: bool = True\n) -> Union[type, Callable[[type], type]]:\n \"\"\"Alias of register. Will be deprecated\"\"\"\n warnings.warn(\"Decorator inject_varname will be removed in 0.6.0. \"\n \"Use varname.register to decorate your class.\",\n DeprecationWarning)\n return register(\n cls,\n caller=caller,\n multi_vars=multi_vars,\n raise_exc=raise_exc\n )\n\ndef inject(obj: object) -> object:\n \"\"\"Inject attribute `__varname__` to an object\n\n Examples:\n >>> class MyList(list):\n >>> pass\n\n >>> a = varname.inject(MyList())\n >>> b = varname.inject(MyList())\n\n >>> a.__varname__ == 'a'\n >>> b.__varname__ == 'b'\n\n >>> a == b\n\n >>> # other methods not affected\n >>> a.append(1)\n >>> b.append(1)\n >>> a == b\n\n Args:\n obj: An object that can be injected\n\n Raises:\n VarnameRetrievingError: When `__varname__` is unable to\n be set as an attribute\n\n Returns:\n The object with __varname__ injected\n \"\"\"\n warnings.warn(\"Function inject will be removed in 0.6.0. Use \"\n \"varname.register to decorate your class.\",\n DeprecationWarning)\n vname = varname(caller=0)\n try:\n setattr(obj, '__varname__', vname)\n except AttributeError:\n raise VarnameRetrievingError('Unable to inject __varname__.') from None\n return obj\n\n\ndef nameof(var, *more_vars, # pylint: disable=unused-argument\n caller: int = 1,\n full: Optional[bool] = None) -> Union[str, Tuple[str]]:\n \"\"\"Get the names of the variables passed in\n\n Examples:\n >>> a = 1\n >>> nameof(a) # 'a'\n\n >>> b = 2\n >>> nameof(a, b) # ('a', 'b')\n\n >>> x = lambda: None\n >>> x.y = 1\n >>> nameof(x.y, full=True) # 'x.y'\n\n Note:\n This function works with the environments where source code is\n available, in other words, the callee's node can be retrieved by\n `executing`. In some cases, for example, running code from python\n shell/REPL or from `exec`/`eval`, we try to fetch the variable name\n from the bytecode. This requires only a single variable name is passed\n to this function and no keyword arguments, meaning that getting full\n names of attribute calls are not supported in such cases.\n\n Args:\n var: The variable to retrieve the name of\n *more_vars: Other variables to retrieve the names of\n caller: The depth of the caller (this function) is called.\n This is useful if you want to wrap this function.\n Note that the calls from varname and builtin modules are ignored.\n full: Whether report the full path of the variable.\n For example: `nameof(a.b.c, full=True)` give you `a.b.c`\n instead of `c`\n\n Returns:\n The names of variables passed in. If a single varialble is passed,\n return the name of it. If multiple variables are passed, return\n a tuple of their names.\n\n Raises:\n VarnameRetrievingError: When the callee's node cannot be retrieved or\n trying to retrieve the full name of non attribute series calls.\n \"\"\"\n node = _get_node(caller, raise_exc=True)\n if not node:\n # We can't retrieve the node by executing.\n # It can be due to running code from python/shell, exec/eval or\n # other environments where sourcecode cannot be reached\n # make sure we keep it simple (only single variable passed and no\n # full passed) to use _bytecode_nameof\n if not more_vars and full is None:\n # don't need caller + 1\n # since this is happening inside varname\n # and will be ignored by default\n return _bytecode_nameof(caller)\n\n # We are anyway raising exceptions, no worries about additional burden\n # of frame retrieval again\n\n # may raise exception, just leave it as is\n frame = _get_frame(caller)\n source = frame.f_code.co_filename\n if source == '':\n raise VarnameRetrievingError(\n \"Are you trying to call nameof in REPL/python shell? \"\n \"In such a case, nameof can only be called with single \"\n \"argument and no keyword arguments.\"\n )\n if source == '':\n raise VarnameRetrievingError(\n \"Are you trying to call nameof from exec/eval? \"\n \"In such a case, nameof can only be called with single \"\n \"argument and no keyword arguments.\"\n )\n raise VarnameRetrievingError(\n \"Source code unavailable, nameof can only retrieve the name of \"\n \"a single variable, and argument `full` should not be specified.\"\n )\n\n ret = []\n for arg in node.args:\n if not full or isinstance(arg, ast.Name):\n ret.append(_node_name(arg))\n else:\n # traverse the node to get the full name: nameof(a.b.c)\n # arg:\n # Attribute(value=Attribute(value=Name(id='a', ctx=Load()),\n # attr='b',\n # ctx=Load()),\n # attr='c',\n # ctx=Load())\n full_name = []\n while not isinstance(arg, ast.Name):\n if not isinstance(arg, ast.Attribute):\n raise VarnameRetrievingError(\n 'Can only retrieve full names of '\n '(chained) attribute calls by nameof.'\n )\n full_name.append(arg.attr)\n arg = arg.value\n # now it is an ast.Name\n full_name.append(arg.id)\n ret.append('.'.join(reversed(full_name)))\n\n return ret[0] if not more_vars else tuple(ret)\n\ndef debug(var, *more_vars,\n prefix: str = 'DEBUG: ',\n merge: bool = False,\n repr: bool = True) -> None: # pylint: disable=redefined-builtin\n \"\"\"Print variable names and values.\n\n Examples:\n >>> a = 1\n >>> b = object\n >>> print(f'a={a}') # previously, we have to do\n >>> print(f'{a=}') # or with python3.8\n >>> # instead we can do:\n >>> debug(a) # DEBUG: a=1\n >>> debug(a, prefix='') # a=1\n >>> debug(a, b, merge=True) # a=1, b=\n\n Args:\n var: The variable to print\n *more_vars: Other variables to print\n prefix: A prefix to print for each line\n merge: Whether merge all variables in one line or not\n repr: Print the value as `repr(var)`? otherwise `str(var)`\n \"\"\"\n var_names = nameof(var, *more_vars, full=True)\n if not isinstance(var_names, tuple):\n var_names = (var_names, )\n variables = (var, *more_vars)\n name_and_values = [f\"{var_name}={variables[i]!r}\" if repr\n else f\"{var_name}={variables[i]}\"\n for i, var_name in enumerate(var_names)]\n if merge:\n print(f\"{prefix}{', '.join(name_and_values)}\")\n else:\n for name_and_value in name_and_values:\n print(f\"{prefix}{name_and_value}\")\n\ndef namedtuple(*args, **kwargs) -> type:\n \"\"\"A shortcut for namedtuple\n\n You don't need to specify the typename, which will be fetched from\n the variable name.\n\n So instead of:\n >>> from collections import namedtuple\n >>> Name = namedtuple('Name', ['first', 'last'])\n\n You can do:\n >>> from varname import namedtuple\n >>> Name = namedtuple(['first', 'last'])\n\n Args:\n *args: arguments for `collections.namedtuple` except `typename`\n **kwargs: keyword arguments for `collections.namedtuple`\n except `typename`\n\n Returns:\n The namedtuple you desired.\n \"\"\"\n warnings.warn(\"Shortcut for namedtuple is deprecated and \"\n \"will be removed in 0.6.0. Use the standard way instead.\",\n DeprecationWarning)\n typename = varname(raise_exc=True)\n return standard_namedtuple(typename, *args, **kwargs)\n\nclass Wrapper:\n \"\"\"A wrapper with ability to retrieve the variable name\n\n Examples:\n >>> foo = Wrapper(True)\n >>> # foo.name == 'foo'\n >>> # foo.value == True\n\n >>> val = {}\n >>> bar = Wrapper(val)\n >>> # bar.name == 'bar'\n >>> # bar.value is val\n\n Args:\n value: The value to be wrapped\n raise_exc: Whether to raise exception when varname is failed to retrieve\n\n Attributes:\n name: The variable name to which the instance is assigned\n value: The value this wrapper wraps\n \"\"\"\n\n def __init__(self, value: Any, raise_exc: bool = True):\n # This call is ignored, since it's inside varname\n self.name = varname(caller=0, raise_exc=raise_exc)\n self.value = value\n\n def __str__(self) -> str:\n return repr(self.value)\n\n def __repr__(self) -> str:\n return (f\"<{self.__class__.__name__} \"\n f\"(name={self.name!r}, value={self.value!r})>\")\n\ndef _check_qualname(\n ignore_list: List[Union[ModuleType, Tuple[ModuleType, str]]]\n) -> None:\n \"\"\"Check if a qualname refers to a unique object.\n\n If multiple or none, raise an error\n \"\"\"\n assert isinstance(ignore_list, list), (\n f\"A list expected for 'ignore', got {type(ignore_list)}\"\n )\n for ignore_elem in ignore_list:\n if not isinstance(ignore_elem, tuple):\n continue\n module, qualname = ignore_elem\n source = executing.Source.for_filename(module.__file__, module.__dict__)\n nobj = list(source._qualnames.values()).count(qualname)\n assert nobj == 1, (\n f\"Qualname {qualname!r} in {module.__name__!r} doesn't exist or \"\n \"refers to multiple objects.\"\n )\n\ndef _debug(msg: str, frame: Optional[FrameType] = None) -> None:\n \"\"\"Print the debug message\"\"\"\n if not DEBUG:\n return\n if frame is not None:\n frameinfo = inspect.getframeinfo(frame)\n msg = (f'{msg} [In {frameinfo.function!r} at '\n f'{frameinfo.filename}:{frameinfo.lineno}]')\n sys.stderr.write(f'[{__name__}] DEBUG: {msg}\\n')\n\ndef _get_frame(\n caller: int,\n ignore: Optional[\n List[Union[ModuleType, Tuple[ModuleType, str]]]\n ] = None\n) -> FrameType:\n \"\"\"This function makes sure that we get the desired frame,\n by caller and ignroe.\n\n The caller is the desired stack we want after excluding the frames we want\n to ignore. By default, this module (varname) and the builtin modules will\n be ignored.\n\n The frame_index defaults to 1 to exclude the calls from inside this module.\n \"\"\"\n # Use loop instead of recursion to avoid creating additional stacks\n try:\n # We are at least skipping 2 frames:\n # one is this function, the other is any varname API that uses this\n # Don't bother to test them, just simply skip.\n frame_index = 2\n\n while caller > 0:\n frame = sys._getframe(frame_index)\n # loot at next frame anyway at next iteration\n frame_index += 1\n module = inspect.getmodule(frame)\n # exect = executing.Source.executing(frame)\n\n if module is sys.modules[__name__]:\n _debug('Skipping frame from varname', frame)\n continue\n\n if module and module.__name__ in sys.builtin_module_names:\n # havn't find a way to compose a test for this, skip for now\n _debug('Skipping builtin module', frame) # pragma: no cover\n continue # pragma: no cover\n\n if ignore and (\n module in ignore or (\n module,\n executing.Source.for_frame(frame).\n code_qualname(frame.f_code)\n ) in ignore\n ):\n _debug('Ignored', frame)\n continue\n\n if ignore and module and '.' in module.__name__:\n # if asyncio specified, asyncio.runners, asyncio.events, etc\n # should be all ignored\n modnames = module.__name__.split('.')[:-1]\n if any(sys.modules['.'.join(modnames[:i+1])] in ignore\n for i, _ in enumerate(modnames)):\n\n _debug('Ignored', frame)\n continue\n\n caller -= 1\n\n if caller > 0:\n _debug(f'Skipping ({caller - 1} more to skip)', frame)\n else:\n _debug('Gotcha!', frame)\n return frame\n\n except Exception as exc:\n raise VarnameRetrievingError from exc\n\ndef _get_node(\n caller: int,\n ignore: Optional[\n List[Union[ModuleType, Tuple[ModuleType, str]]]\n ] = None,\n raise_exc: bool = True\n) -> Optional[ast.AST]:\n \"\"\"Try to get node from the executing object.\n\n This can fail when a frame is failed to retrieve.\n One case should be when python code is executed in\n R pacakge `reticulate`, where only first frame is kept.\n\n When the node can not be retrieved, try to return the first statement.\n \"\"\"\n try:\n frame = _get_frame(caller, ignore)\n except VarnameRetrievingError:\n return None\n\n exect = executing.Source.executing(frame)\n\n if exect.node:\n return exect.node\n\n if exect.source.text and exect.source.tree and raise_exc:\n raise VarnameRetrievingError(\n \"Couldn't retrieve the call node. \"\n \"This may happen if you're using some other AST magic at the \"\n \"same time, such as pytest, ipython, macropy, or birdseye.\"\n )\n\n return None\n\ndef _lookfor_parent_assign(node: ast.AST) -> Optional[ast.Assign]:\n \"\"\"Look for an ast.Assign node in the parents\"\"\"\n while hasattr(node, 'parent'):\n node = node.parent\n\n if isinstance(node, (ast.AnnAssign, ast.Assign)):\n return node\n return None\n\ndef _node_name(node: ast.AST) -> Optional[Union[str, Tuple[Union[str, tuple]]]]:\n \"\"\"Get the node node name.\n\n Raises VarnameRetrievingError when failed\n \"\"\"\n if isinstance(node, ast.Name):\n return node.id\n if isinstance(node, ast.Attribute):\n return node.attr\n if isinstance(node, (ast.List, ast.Tuple)):\n return tuple(_node_name(elem) for elem in node.elts)\n\n raise VarnameRetrievingError(\n f\"Can only get name of a variable or attribute, \"\n f\"not {ast.dump(node)}\"\n )\n\ndef _bytecode_nameof(caller: int = 1) -> str:\n \"\"\"Bytecode version of nameof as a fallback\"\"\"\n frame = _get_frame(caller)\n return _bytecode_nameof_cached(frame.f_code, frame.f_lasti)\n\n@lru_cache()\ndef _bytecode_nameof_cached(code: CodeType, offset: int) -> str:\n \"\"\"Cached Bytecode version of nameof\n\n We are trying this version only when the sourcecode is unavisible. In most\n cases, this will happen when user is trying to run a script in REPL/\n python shell, with `eval`, or other circumstances where the code is\n manipulated to run but sourcecode is not available.\n \"\"\"\n instructions = list(dis.get_instructions(code))\n (current_instruction_index, current_instruction), = (\n (index, instruction)\n for index, instruction in enumerate(instructions)\n if instruction.offset == offset\n )\n\n if current_instruction.opname not in (\"CALL_FUNCTION\", \"CALL_METHOD\"):\n raise VarnameRetrievingError(\"Did you call nameof in a weird way?\")\n\n name_instruction = instructions[\n current_instruction_index - 1\n ]\n\n if not name_instruction.opname.startswith(\"LOAD_\"):\n raise VarnameRetrievingError(\"Argument must be a variable or attribute\")\n\n name = name_instruction.argrepr\n if not name.isidentifier():\n raise VarnameRetrievingError(\n f\"Found the variable name {name!r} which is obviously wrong. \"\n \"This may happen if you're using some other AST magic at the \"\n \"same time, such as pytest, ipython, macropy, or birdseye.\"\n )\n\n return name\n", "sub_path": ".idea/VirtualEnvironment/lib/python3.8/site-packages/varname.py", "file_name": "varname.py", "file_ext": "py", "file_size_in_byte": 24662, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.Optional", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 29, "usage_type": "name"}, {"api_name": "types.ModuleType", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 29, "usage_type": "name"}, {"api_name": "ast.AnnAssign", "line_number": 97, "usage_type": "attribute"}, {"api_name": "warnings.warn", "line_number": 103, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 33, "usage_type": "name"}, {"api_name": "ast.Attribute", "line_number": 174, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 123, "usage_type": "name"}, {"api_name": "functools.wraps", "line_number": 226, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 189, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 189, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 248, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 246, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 246, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 288, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 301, "usage_type": "name"}, {"api_name": "ast.Name", "line_number": 381, "usage_type": "attribute"}, {"api_name": "ast.Name", "line_number": 392, "usage_type": "attribute"}, {"api_name": "ast.Attribute", "line_number": 393, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 301, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 301, "usage_type": "name"}, {"api_name": "warnings.warn", "line_number": 464, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 468, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 492, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 505, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 505, "usage_type": "name"}, {"api_name": "types.ModuleType", "line_number": 505, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 505, "usage_type": "name"}, {"api_name": "executing.Source.for_filename", "line_number": 518, "usage_type": "call"}, {"api_name": "executing.Source", "line_number": 518, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 525, "usage_type": "name"}, {"api_name": "types.FrameType", "line_number": 525, "usage_type": "name"}, {"api_name": "inspect.getframeinfo", "line_number": 530, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 533, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 533, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 537, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 538, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 538, "usage_type": "name"}, {"api_name": "types.ModuleType", "line_number": 538, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 538, "usage_type": "name"}, {"api_name": "sys._getframe", "line_number": 558, "usage_type": "call"}, {"api_name": "inspect.getmodule", "line_number": 561, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 564, "usage_type": "attribute"}, {"api_name": "sys.builtin_module_names", "line_number": 568, "usage_type": "attribute"}, {"api_name": "executing.Source.for_frame", "line_number": 576, "usage_type": "call"}, {"api_name": "executing.Source", "line_number": 576, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 587, "usage_type": "attribute"}, {"api_name": "types.FrameType", "line_number": 540, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 606, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 607, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 607, "usage_type": "name"}, {"api_name": "types.ModuleType", "line_number": 607, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 607, "usage_type": "name"}, {"api_name": "executing.Source.executing", "line_number": 624, "usage_type": "call"}, {"api_name": "executing.Source", "line_number": 624, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 610, "usage_type": "name"}, {"api_name": "ast.AST", "line_number": 610, "usage_type": "attribute"}, {"api_name": "ast.AST", "line_number": 638, "usage_type": "attribute"}, {"api_name": "ast.AnnAssign", "line_number": 643, "usage_type": "attribute"}, {"api_name": "ast.Assign", "line_number": 643, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 638, "usage_type": "name"}, {"api_name": "ast.Assign", "line_number": 638, "usage_type": "attribute"}, {"api_name": "ast.AST", "line_number": 647, "usage_type": "attribute"}, {"api_name": "ast.Name", "line_number": 652, "usage_type": "attribute"}, {"api_name": "ast.Attribute", "line_number": 654, "usage_type": "attribute"}, {"api_name": "ast.List", "line_number": 656, "usage_type": "attribute"}, {"api_name": "ast.Tuple", "line_number": 656, "usage_type": "attribute"}, {"api_name": "ast.dump", "line_number": 661, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 647, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 647, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 647, "usage_type": "name"}, {"api_name": "types.CodeType", "line_number": 670, "usage_type": "name"}, {"api_name": "dis.get_instructions", "line_number": 678, "usage_type": "call"}, {"api_name": "functools.lru_cache", "line_number": 669, "usage_type": "call"}]} +{"seq_id": "268597158", "text": "\"\"\"\nIn this file we will test the encoding and train a basic network using the built structure\n\n\"\"\"\nfrom __future__ import print_function\nimport time\nimport random\nimport sys\nimport subprocess\nimport unittest\nimport logging\nfrom PySearch.PySearch import PySearch\nfrom tensorflow.keras.datasets import cifar10\nfrom logging import config\n\n\ndef get_git_hash():\n return subprocess.check_output([\"git\", \"describe\", \"--always\"]).strip()\n\n\ndef set_seed(logger):\n seed = random.randrange(sys.maxsize)\n random.Random(seed)\n logger.info(\"Seed was: %f\", seed)\n\n\nclass CIFAR10Test(unittest.TestCase):\n\n def test_encoding(self):\n logging.config.fileConfig('PySearch/logs/logging.conf')\n logger = logging.getLogger('testFile')\n\n logger.info(\"Setting seed\")\n set_seed(logger)\n\n logger.info(\"starting test...\")\n\n logger.info(get_git_hash())\n\n (train_dataset, train_labels), (test_dataset,\n test_labels) = cifar10.load_data()\n\n start = time.time()\n best_cnn = PySearch({'train_dataset' : train_dataset, \n 'train_labels': train_labels,\n 'test_dataset': test_dataset,\n 'test_labels' : test_labels})\n fitness, accuracy, parameters = best_cnn(50, 0.00001)\n end = time.time()\n print(\"Time to best %f, fitness: %f, Accuracy: %f, Parameters: %d\",\n end - start, fitness, accuracy, parameters)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "CIFAR10.py", "file_name": "CIFAR10.py", "file_ext": "py", "file_size_in_byte": 1549, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "subprocess.check_output", "line_number": 18, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.maxsize", "line_number": 22, "usage_type": "attribute"}, {"api_name": "random.Random", "line_number": 23, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logging.config.fileConfig", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.config", "line_number": 30, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras.datasets.cifar10.load_data", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.keras.datasets.cifar10", "line_number": 41, "usage_type": "name"}, {"api_name": "time.time", "line_number": 43, "usage_type": "call"}, {"api_name": "PySearch.PySearch.PySearch", "line_number": 44, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 55, "usage_type": "call"}]} +{"seq_id": "161146698", "text": "import os\nimport sys\nfrom gtts import gTTS\nimport speech_recognition as sr\n\nif __name__ == \"__main__\":\n\t\n\ttry: \n\t\taudio2 = r.listen(source, timeout = 5)\n\n\t\tresponse2 = r.recognize_google(audio2)\n\t\tresponse3 = response2.lower()\n\t\tprint(response3)\n\n\t\t\n\t\tif(response3 == \"what time is it\"):\n\t\t\t# timeResp = gTTS(text=\"it is nine pee m\", lang = 'en',slow = False)\n\t\t\t# timeResp.save(\"time.mp3\")\n\t\t\tos.system(\"vlc -Idummy --play-and-exit none time.mp3\")\n\t\telif(response3 == \"f*** you\"):\n\t\t\t# timeResp = gTTS(text=\"Fuck you too\", lang = 'en',slow = False)\n\t\t\t# timeResp.save(\"fucku2.mp3\")\n\t\t\tos.system(\"vlc -Idummy --play-and-exit none fucku2.mp3\")\n\t\telif(response3 == \"what is today's date\"):\n\t\t\t# timeResp = gTTS(text=\"Today is September third\", lang = 'en',slow = False)\n\t\t\t# timeResp.save(\"date.mp3\")\n\t\t\tos.system(\"vlc -Idummy --play-and-exit none date.mp3\")\n\t\telse:\n\t\t\t# timeResp = gTTS(text=\"I do not know how to do that yet\", lang = 'en',slow = False)\n\t\t\t# timeResp.save(\"cannotdo.mp3\")\n\t\t\tos.system(\"vlc -Idummy --play-and-exit none cannotdo.mp3\")\n\n\texcept sr.WaitTimeoutError:\n\t\tprint(\"user took too long to respond\")\n\t\t# timeout = gTTS(text=\"how about you talk to me later\", lang ='en',slow = False)\n\t\t# timeout.save(\"outoftime.mp3\")\n\t\tos.system(\"vlc -Idummy --play-and-exit none outoftime.mp3\")", "sub_path": "The Old Stuff/arch_assistant.py", "file_name": "arch_assistant.py", "file_ext": "py", "file_size_in_byte": 1299, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.system", "line_number": 19, "usage_type": "call"}, {"api_name": "os.system", "line_number": 23, "usage_type": "call"}, {"api_name": "os.system", "line_number": 27, "usage_type": "call"}, {"api_name": "os.system", "line_number": 31, "usage_type": "call"}, {"api_name": "speech_recognition.WaitTimeoutError", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "318721517", "text": "#!/home/jhernandez/Documentos/RAM/venv/bin/python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\ndef dataframeuser_grafica(df,user,file):\n name_csv = file+\"_all.csv\"\n name_img = file+\"_\"+user+\".png\"\n df = df[df.Usuario == user]\n df = df.sort_values('RAM',ascending=False)\n df = df.head(5)\n xvalue = df['Fecha']\n yvalue = df['RAM']\n plt.plot(xvalue,yvalue, label=user)\n plt.legend(loc=\"center right\")\n plt.savefig(name_img)\n #plt.show()\n df.to_csv(name_csv,index=False,mode='a',header=False)\n\ndef main():\n #df = pd.read_csv('all.csv')\n file = sys.argv[1]\n file_name = file.split('.')\n df = pd.read_csv(file)\n df['RAM'] = (df.Memoria_Por * 125)/100\n df=df[df.RAM !=0]\n user = df.drop_duplicates(subset=['Usuario'])\n user = user['Usuario']\n #print(user)\n #df = df.groupby(['Fecha','Usuario','RAM'])['RAM'].sum().rename(columns={'Fecha':'Date','Usuario':'User'}).reset_index()\n df = df.groupby(['Fecha','Usuario'])['RAM'].sum().reset_index()\n for i in user:\n dataframeuser_grafica(df,i,file_name[0])\n\n \n #df2 = df.reset_index(drop=True)\n #df = df.groupby(['Fecha','Usuario','RAM']).agg({'RAM':'sum'})\n #dfimpala = df[df.Usuario == 'impala']\n #dfimpala = dfimpala.sort_values('RAM',ascending=False)\n #dfimpala = dfimpala.head(5)\n #xvalue = dfimpala['Fecha']\n #yvalue = dfimpala['RAM']\n \n #plt.plot(xvalue,yvalue)\n #plot = plt.plot(xvalue,yvalue)\n #plt.savefig('grafica.png')\n #plt.show()\n\n #plot = dfimpala.plot()\n #fig = plot.get_figure()\n #fig.savefig(\"output.png\")\n #df.plot()\n #df.to_csv('test.csv',index=False)\n #print(dfimpala)\nif __name__ == \"__main__\":\n main()", "sub_path": "files/fe-master02/analasis.py", "file_name": "analasis.py", "file_ext": "py", "file_size_in_byte": 1739, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "294728082", "text": "# -*- coding: utf-8 -*-\n# Copyright 2021 \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\"Tests for projectq.setups.decompositions.unitary2rzry.py\"\n\nimport pytest\n\nfrom projectq import MainEngine\nfrom projectq.backends import Simulator\nfrom projectq.cengines import (\n AutoReplacer,\n DecompositionRuleSet,\n DummyEngine,\n InstructionFilter,\n)\nfrom projectq.meta import Control\nfrom projectq.ops import Measure, U\n\nfrom . import unitary2rzry as u2rzry\n\n\ndef test_recognize_correct_gates():\n saving_backend = DummyEngine(save_commands=True)\n eng = MainEngine(backend=saving_backend)\n qubit = eng.allocate_qubit()\n ctrl_qubit = eng.allocate_qubit()\n eng.flush()\n U(1, 2, 3, 4) | qubit\n with Control(eng, ctrl_qubit):\n U(2, 3, 4, 5) | qubit\n eng.flush(deallocate_qubits=True)\n assert u2rzry._recognize_UNoCtrl(saving_backend.received_commands[3])\n assert not u2rzry._recognize_UNoCtrl(saving_backend.received_commands[4])\n\n\ndef rx_decomp_gates(eng, cmd):\n g = cmd.gate\n if isinstance(g, U):\n return False\n else:\n return True\n\n\n@pytest.mark.parametrize(\"alpha\", [0, 2.2])\n@pytest.mark.parametrize(\"beta\", [0, 2.3])\n@pytest.mark.parametrize(\"gamma\", [0, 2.4])\n@pytest.mark.parametrize(\"delta\", [0, 2.5])\ndef test_decomposition(alpha, beta, gamma, delta):\n for basis_state in ([1, 0], [0, 1]):\n correct_dummy_eng = DummyEngine(save_commands=True)\n correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])\n\n rule_set = DecompositionRuleSet(modules=[u2rzry])\n test_dummy_eng = DummyEngine(save_commands=True)\n test_eng = MainEngine(\n backend=Simulator(),\n engine_list=[AutoReplacer(rule_set), InstructionFilter(rx_decomp_gates), test_dummy_eng],\n )\n\n correct_qb = correct_eng.allocate_qubit()\n U(alpha, beta, gamma, delta) | correct_qb\n correct_eng.flush()\n\n test_qb = test_eng.allocate_qubit()\n U(alpha, beta, gamma, delta) | test_qb\n test_eng.flush()\n\n assert correct_dummy_eng.received_commands[1].gate == U(alpha, beta, gamma, delta)\n assert test_dummy_eng.received_commands[1].gate != U(alpha, beta, gamma, delta)\n\n for fstate in ['0', '1']:\n test = test_eng.backend.get_amplitude(fstate, test_qb)\n correct = correct_eng.backend.get_amplitude(fstate, correct_qb)\n assert correct == pytest.approx(test, rel=1e-12, abs=1e-12)\n\n Measure | test_qb\n Measure | correct_qb\n", "sub_path": "projectq/setups/decompositions/unitary2rzry_test.py", "file_name": "unitary2rzry_test.py", "file_ext": "py", "file_size_in_byte": 3082, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "projectq.cengines.DummyEngine", "line_number": 35, "usage_type": "call"}, {"api_name": "projectq.MainEngine", "line_number": 36, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 40, "usage_type": "call"}, {"api_name": "projectq.meta.Control", "line_number": 41, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 42, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 50, "usage_type": "argument"}, {"api_name": "projectq.cengines.DummyEngine", "line_number": 62, "usage_type": "call"}, {"api_name": "projectq.MainEngine", "line_number": 63, "usage_type": "call"}, {"api_name": "projectq.backends.Simulator", "line_number": 63, "usage_type": "call"}, {"api_name": "projectq.cengines.DecompositionRuleSet", "line_number": 65, "usage_type": "call"}, {"api_name": "projectq.cengines.DummyEngine", "line_number": 66, "usage_type": "call"}, {"api_name": "projectq.MainEngine", "line_number": 67, "usage_type": "call"}, {"api_name": "projectq.backends.Simulator", "line_number": 68, "usage_type": "call"}, {"api_name": "projectq.cengines.AutoReplacer", "line_number": 69, "usage_type": "call"}, {"api_name": "projectq.cengines.InstructionFilter", "line_number": 69, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 73, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 77, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 80, "usage_type": "call"}, {"api_name": "projectq.ops.U", "line_number": 81, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 86, "usage_type": "call"}, {"api_name": "projectq.ops.Measure", "line_number": 88, "usage_type": "name"}, {"api_name": "projectq.ops.Measure", "line_number": 89, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 56, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 57, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 58, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 58, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 59, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 59, "usage_type": "attribute"}]} +{"seq_id": "94416992", "text": "import pytest\nimport numpy as np\nimport scipy.ndimage as ndi\n\nfrom autolamella.align import (\n _calculate_beam_shift,\n _normalize_image,\n _simple_register_translation,\n)\nimport autolamella.data\nfrom autolamella.data.mocktypes import MockAdornedImage\n\n\n@pytest.mark.parametrize(\n \"pixel_shift, pixel_size, expected_beam_shift\",\n [\n (np.array([0, 20]), 1e-6, np.array([0.0, -20e-6])),\n (np.array([10, 0]), 1e-6, np.array([10e-6, -0.0])),\n (np.array([10, 20]), 1e-6, np.array([10e-6, -20e-6])),\n (np.array([10, -20]), 1e-6, np.array([10e-6, 20e-6])),\n (np.array([-10, 20]), 1e-6, np.array([-10e-6, -20e-6])),\n (np.array([-10, -20]), 1e-6, np.array([-10e-6, 20e-6])),\n ],\n)\ndef test__calculate_beam_shift(pixel_shift, pixel_size, expected_beam_shift):\n data = np.random.random([512, 512])\n shifted_data = ndi.shift(data, np.flip(pixel_shift))\n reference_image = MockAdornedImage(\n data, pixelsize_x=pixel_size, pixelsize_y=pixel_size\n )\n shifted_image = MockAdornedImage(\n shifted_data, pixelsize_x=pixel_size, pixelsize_y=pixel_size\n )\n result = _calculate_beam_shift(reference_image, shifted_image)\n assert np.allclose(result, expected_beam_shift)\n\n\n@pytest.mark.parametrize(\n \"shift\",\n [\n (np.array([0, 20])),\n (np.array([10, 0])),\n (np.array([10, 20])),\n (np.array([10, -20])),\n (np.array([-10, 20])),\n (np.array([-10, -20])),\n ],\n)\ndef test__simple_register_translation(shift):\n \"\"\"Input shift in x, y format.\"\"\"\n reference_image = np.random.random((512, 512))\n shifted_image = ndi.shift(reference_image, np.flip(shift))\n result = _simple_register_translation(reference_image, shifted_image)\n expected_shift = -1 * shift # negative should return to original position\n assert np.allclose(result[:2], expected_shift)\n\n\n@pytest.mark.parametrize(\n \"image\",\n [\n ((np.random.random((512, 512)) * 100) + 20),\n (autolamella.data.autoscript_image()),\n ],\n)\ndef test__normalize_image(image):\n output = _normalize_image(image)\n assert np.isclose(np.mean(output), 0)\n assert np.isclose(np.std(output), 1)\n", "sub_path": "tests/test_align.py", "file_name": "test_align.py", "file_ext": "py", "file_size_in_byte": 2194, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.random.random", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "scipy.ndimage.shift", "line_number": 27, "usage_type": "call"}, {"api_name": "scipy.ndimage", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.flip", "line_number": 27, "usage_type": "call"}, {"api_name": "autolamella.data.mocktypes.MockAdornedImage", "line_number": 28, "usage_type": "call"}, {"api_name": "autolamella.data.mocktypes.MockAdornedImage", "line_number": 31, "usage_type": "call"}, {"api_name": "autolamella.align._calculate_beam_shift", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 14, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "attribute"}, {"api_name": "scipy.ndimage.shift", "line_number": 52, "usage_type": "call"}, {"api_name": "scipy.ndimage", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.flip", "line_number": 52, "usage_type": "call"}, {"api_name": "autolamella.align._simple_register_translation", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 55, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "autolamella.align._normalize_image", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.isclose", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 68, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 58, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 61, "usage_type": "attribute"}, {"api_name": "autolamella.align.data.autoscript_image", "line_number": 62, "usage_type": "call"}, {"api_name": "autolamella.align.data", "line_number": 62, "usage_type": "attribute"}, {"api_name": "autolamella.align", "line_number": 62, "usage_type": "name"}]} +{"seq_id": "114297311", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nfrom flask import Flask, request, url_for, jsonify, json, g, make_response\nimport sqlite3\nimport sys\nfrom datetime import datetime\nfrom functools import wraps\nfrom passlib.hash import pbkdf2_sha256\nimport datetime\nfrom rfeed import *\n\n\napp = Flask(__name__)\n\n\nclass Slash(Extension):\n def get_namespace(self):\n return {\"xmlns:slash\" : \"http://purl.org/rss/1.0/modules/slash/\"}\n\nclass SlashItem(Serializable):\n def __init__(self, content):\n Serializable.__init__(self)\n self.comments = content\n\n def publish(self, handler):\n Serializable.publish(self, handler)\n self._write_element(\"slash:comments\", self.comments)\n\n@app.route(\"/comment_feed/\", methods = ['GET'])\ndef comment_feed(article_id):\n req = requests.get('http://localhost/articles/'+ article_id)\n article = req.json()\n items = []\n r = requests.get('http://localhost/comments/getncomments/'+ article_id, json = {\"n\" : \"10\"})\n arr = r.json()\n for i in range(0, len(r.json())):\n date_time_str = str(arr[i][1])\n date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')\n\n item1 = Item(\n title = arr[i][0],\n comments = arr[i][1],\n pubDate = date_time_obj)\n items.append(item1)\n\n feed = Feed(\n title = \"Top comments for article\",\n link = (\"http://127.0.0.1/\"+article_id),\n description = \"Top comments for article\",\n language = \"en-US\",\n lastBuildDate = datetime.datetime.now(),\n items = items)\n\n return (feed.rss())\n\n@app.route(\"/summary_feed\", methods = ['GET'])\ndef summary_feed():\n r = requests.get('http://localhost/articles', json = {\"n\" : \"10\"})\n arr = r.json()\n items = []\n for i in range(0, len(arr)):\n date_time_str = str(arr[i][3])\n date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')\n item1 = Item(\n title = arr[i][1],\n link = arr[i][5],\n author = arr[i][6],\n pubDate = date_time_obj)\n items.append(item1)\n\n feed = Feed(\n title = \"Articles RSS Feed\",\n link = \"http://www.articles.com/rss\",\n description = \"Generate RSS Feeds for Articles\",\n language = \"en-US\",\n lastBuildDate = datetime.datetime.now(),\n items = items)\n\n return (feed.rss())\n\n@app.route(\"/full_feed/\", methods = ['GET'])\ndef full_feed(article_id):\n req_article = requests.get('http://localhost/articles/'+ article_id)\n article = req_article.json()\n req_tags = requests.get('http://localhost/get_tags/'+ article_id)\n tags = req_tags.json();\n req_comment_count = requests.get('http://localhost/comments/getcommentcount/'+ article_id)\n comment_count = req_comment_count.json()\n items = []\n tags_arr = []\n for i in range (0, len(tags)):\n tags_arr.append(''.join(tags[i]))\n date_time_str = str(article[3])\n date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')\n item1 = Item(\n title = article[1],\n description = article[2],\n link = article[5],\n author = article[6],\n categories = tags_arr,\n pubDate = date_time_obj,\n extensions = [SlashItem(comment_count)])\n items.append(item1)\n feed = Feed(\n title = \"Artciles RSS Feed\",\n link = \"http://www.articles.com/rss\",\n description = \"Generate RSS Feeds for Articles\",\n language = \"en-US\",\n lastBuildDate = datetime.datetime.now(),\n extensions = [Slash()],\n items = items)\n\n return (feed.rss())\n", "sub_path": "RSSFeed.py", "file_name": "RSSFeed.py", "file_ext": "py", "file_size_in_byte": 3685, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 33, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 78, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 78, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 85, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 87, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 89, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 96, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 96, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 111, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 111, "usage_type": "attribute"}]} +{"seq_id": "463621842", "text": "import os\nfrom flask import Flask, render_template, request, url_for, redirect, send_from_directory\nfrom werkzeug import secure_filename\nfrom label_image import getScores\nfrom rot_segmentation import getRotRatio\n\nscore = 0\nimg = 'moc.jpg'\n\napp = Flask(__name__)\n\napp.config['UPLOAD_FOLDER'] = 'static/'\n\n\n@app.route('/')\ndef login():\n return render_template('homepage.html')\n\n\n@app.route('/', methods=['POST'])\ndef login_process():\n # this is the user input\n # *************************************\n # modifies the global username variable for later use\n print(\"in\")\n url = request.form['url']\n #\tfile = request.files['file']\n #\tfilename = secure_filename(file.filename)\n #\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n #\treturn redirect(url_for('uploaded_file',\n # filename=filename))\n # *************************************\n print(url)\n # checks the user name and password. if they match this part of the code will redirect them to\n # the logged_in. If the username does not match the password it the code will redirect them to\n # a screen where they are told that they have entered the wrong input\n if (request.form['submit'] == \"login\"):\n os.system(\"wget \" + url)\n i = 0\n index = 0\n for word in url:\n if (word == '/'):\n index = i\n i = i + 1\n global img\n img = url[index + 1:]\n global score\n score = getScores(img)\n # os.system(\"python label_image.py \" + img)\n os.system(\"mv \" + img + \" static/\")\n img = \"static/\" + img\n return redirect(url_for('results'))\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n # Get the name of the uploaded file\n file = request.files['file']\n # Check if the file is one of the allowed types/extensions\n # if file and allowed_file(file.filename):\n # Make the filename safe, remove unsupported chars\n filename = secure_filename(file.filename)\n # Move the file form the temporal folder to\n # the upload folder we setup\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n global score\n score = getScores(\"static/\" + filename)\n global img\n img = \"static/\" + filename\n # os.system(\"python label_image.py static/\"+filename)\n # Redirect the user to the uploaded_file route, which\n # will basicaly show on the browser the uploaded file\n return redirect(url_for('results'))\n\n\n@app.route('/results')\ndef results():\n print(score)\n print(\"in results\")\n if (score['notaleaf'] > .5):\n return render_template(\"results.html\", rot='NA', health='NA', other='NA')\n else:\n print(img)\n os.system(\"rm static/rot.jpg\")\n percentace_of_rot = getRotRatio(img)\n print(\"got it\")\n return render_template(\"final.html\", rot=(score['blackrot'] * 100), health=(score['notaleaf'] * 100),\n other=(score['leaves'] * 100), percent=percentace_of_rot)\n\n\n@app.route('/static/')\ndef uploaded_file(img):\n return send_from_directory(app.config['UPLOAD_FOLDER'],\n img)\n\n\nif __name__ == '__main__':\n app.run(\n debug=True,\n port=int(os.getenv('PORT', 8080)),\n host=os.getenv('IP', '0.0.0.0')\n )\n", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 3323, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 37, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "os.system", "line_number": 38, "usage_type": "call"}, {"api_name": "label_image.getScores", "line_number": 48, "usage_type": "call"}, {"api_name": "os.system", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 58, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 58, "usage_type": "name"}, {"api_name": "werkzeug.secure_filename", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "label_image.getScores", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "os.system", "line_number": 84, "usage_type": "call"}, {"api_name": "rot_segmentation.getRotRatio", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 87, "usage_type": "call"}, {"api_name": "flask.send_from_directory", "line_number": 93, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 100, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 101, "usage_type": "call"}]} +{"seq_id": "376992004", "text": "#!/usr/bin/env python\n''' '''\n\nfrom flask import Flask\nimport dns.reversename\nimport dns.resolver\nimport os\nimport re\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef return_ips():\n ip_list = os.popen('arp-scan --localnet --interface=br0 | awk \\'{ print $1 }\\' | grep -e \\'[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\' | sort -V').read()\n return ip_list\n\n\n@app.route('/full')\ndef return_ips_full():\n ip_list_full = os.popen('arp-scan --localnet --interface=br0 | sort -V').read()\n result = []\n for line in ip_list_full.split('\\n'):\n try:\n found = re.search(r'^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s*((?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2}))([\\s\\t]*\\((?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\\))?\\s*(.*)', line)\n if found.group(3):\n mac = '{}{}'.format(found.group(2), found.group(3))\n else:\n mac = found.group(2)\n \n ip = found.group(1)\n vendor = found.group(4)\n try:\n x = dns.reversename.from_address(ip)\n name = str(dns.resolver.query(x,\"PTR\")[0])\n result.append('{:14} {:41} {:37} {:50}'.format(ip, name, mac, vendor))\n except dns.resolver.NXDOMAIN:\n result.append('{:56} {:37} {:50}'.format(ip, mac, vendor))\n \n except AttributeError:\n pass\n\n return '{}'.format('\\n'.join(result))\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=9999)\n", "sub_path": "get_network_ips_arp_scan.py", "file_name": "get_network_ips_arp_scan.py", "file_ext": "py", "file_size_in_byte": 1509, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 11, "usage_type": "call"}, {"api_name": "os.popen", "line_number": 16, "usage_type": "call"}, {"api_name": "os.popen", "line_number": 22, "usage_type": "call"}, {"api_name": "re.search", "line_number": 26, "usage_type": "call"}, {"api_name": "dns.reversename.reversename.from_address", "line_number": 35, "usage_type": "call"}, {"api_name": "dns.reversename.reversename", "line_number": 35, "usage_type": "attribute"}, {"api_name": "dns.reversename", "line_number": 35, "usage_type": "name"}, {"api_name": "dns.reversename.resolver.query", "line_number": 36, "usage_type": "call"}, {"api_name": "dns.reversename.resolver", "line_number": 36, "usage_type": "attribute"}, {"api_name": "dns.reversename", "line_number": 36, "usage_type": "name"}, {"api_name": "dns.reversename.resolver", "line_number": 38, "usage_type": "attribute"}, {"api_name": "dns.reversename", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "314992681", "text": "#-------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#--------------------------------------------------------------------------\n\nimport numpy as np\nfrom ....proto import onnx_proto\nfrom ...common import NodeBuilder\nfrom ...common import utils\nfrom ...common import model_util\nfrom ...common import registration\n\n\nclass EmbeddingLayerConverter:\n\n @staticmethod\n def validate(cm_node):\n try:\n utils._check_has_attr(cm_node, 'embedding')\n utils._check_has_attr(cm_node, 'input')\n utils._check_has_attr(cm_node, 'output')\n except AttributeError as e:\n raise RuntimeError(\n 'Missing attribute in neural network layer: {0}'.format(cm_node.name))\n\n @staticmethod\n def convert(context, cm_node, inputs, outputs):\n # Type changes of embedding operator's input. They should be integer tensors rather\n # than float tensors by default.\n for top_level_input in context.top_level_inputs:\n onnx_name = context.get_onnx_name(top_level_input.name)\n if onnx_name == inputs[0]:\n top_level_input.type.tensor_type.elem_type = onnx_proto.TensorProto.INT64\n\n params = cm_node.embedding\n\n # Reshape the indexes we want to embed to 1-D tensor. Otherwise, Gather's output may get a wrong shape.\n reshaped_input_name = context.get_unique_name(inputs[0]+'_reshaped')\n nb1 = NodeBuilder(context, 'Reshape')\n nb1.add_input(inputs[0])\n nb1.add_output(reshaped_input_name)\n nb1.add_attribute('shape', [-1])\n\n # Use Gather to extract representations for each index\n nb2 = NodeBuilder(context, 'Gather')\n # Load the embedding matrix. Its shape is outputChannels-by-inputDim.\n weights = np.array(params.weights.floatValue).reshape(params.outputChannels, params.inputDim)\n # Transpose the embedding matrix for applying Gather operator\n tensor_w = model_util.make_tensor('W', onnx_proto.TensorProto.FLOAT, [params.inputDim, params.outputChannels],\n weights.transpose().flatten().tolist())\n nb2.add_initializer(tensor_w)\n nb2.add_input(reshaped_input_name)\n\n # To support the bias term in an embedding (if exists), we need to create one extra node\n if params.hasBias:\n # Put the embedded result onto a temporal tensor\n nb2.add_output(nb2.name)\n # Create an addition operator to add bias (shape: [C]) into the temporal tensor (shape: [N, C])\n nb3 = NodeBuilder(context, 'Add')\n nb3.extend_inputs(nb2.output_names)\n tensor_b = model_util.make_tensor('b', onnx_proto.TensorProto.FLOAT, [\n params.outputChannels], params.bias.floatValue)\n nb3.add_initializer(tensor_b)\n nb3.add_attribute('axis', 1)\n nb3.add_attribute('broadcast', 1)\n # Output the result produced by the addition node\n nb3.extend_outputs(outputs)\n\n return [nb1.make_node(), nb2.make_node(), nb3.make_node()]\n else:\n # This case has no bias, so we just output the result produced by the embedding node.\n nb2.extend_outputs(outputs)\n\n return [nb1.make_node(), nb2.make_node()]\n\n\nregistration.register_nn_converter('embedding', EmbeddingLayerConverter)\n", "sub_path": "onnxmltools/convert/coreml/NeuralNetwork/embedding.py", "file_name": "embedding.py", "file_ext": "py", "file_size_in_byte": 3575, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "common.utils._check_has_attr", "line_number": 20, "usage_type": "call"}, {"api_name": "common.utils", "line_number": 20, "usage_type": "name"}, {"api_name": "common.utils._check_has_attr", "line_number": 21, "usage_type": "call"}, {"api_name": "common.utils", "line_number": 21, "usage_type": "name"}, {"api_name": "common.utils._check_has_attr", "line_number": 22, "usage_type": "call"}, {"api_name": "common.utils", "line_number": 22, "usage_type": "name"}, {"api_name": "proto.onnx_proto.TensorProto", "line_number": 34, "usage_type": "attribute"}, {"api_name": "proto.onnx_proto", "line_number": 34, "usage_type": "name"}, {"api_name": "common.NodeBuilder", "line_number": 40, "usage_type": "call"}, {"api_name": "common.NodeBuilder", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "common.model_util.make_tensor", "line_number": 50, "usage_type": "call"}, {"api_name": "common.model_util", "line_number": 50, "usage_type": "name"}, {"api_name": "proto.onnx_proto.TensorProto", "line_number": 50, "usage_type": "attribute"}, {"api_name": "proto.onnx_proto", "line_number": 50, "usage_type": "name"}, {"api_name": "common.NodeBuilder", "line_number": 60, "usage_type": "call"}, {"api_name": "common.model_util.make_tensor", "line_number": 62, "usage_type": "call"}, {"api_name": "common.model_util", "line_number": 62, "usage_type": "name"}, {"api_name": "proto.onnx_proto.TensorProto", "line_number": 62, "usage_type": "attribute"}, {"api_name": "proto.onnx_proto", "line_number": 62, "usage_type": "name"}, {"api_name": "common.registration.register_nn_converter", "line_number": 78, "usage_type": "call"}, {"api_name": "common.registration", "line_number": 78, "usage_type": "name"}]} +{"seq_id": "508077186", "text": "# Import Krita\r\nfrom krita import *\r\nfrom PyQt5 import QtWidgets, QtCore, QtGui, uic\r\nimport os.path\r\nimport time\r\nimport datetime\r\nimport xml\r\n\r\n# Set Window Title Name\r\nDOCKER_NAME = 'Timer Watch'\r\n# Alarm QMessageBox\r\nmessage = \"Time is Over\"\r\n\r\n# Docker Class\r\nclass TimerWatchDocker(DockWidget):\r\n \"\"\"Control amount of work time spent or see the current time\"\"\"\r\n\r\n def __init__(self):\r\n super(TimerWatchDocker, self).__init__()\r\n\r\n # Window Title\r\n self.setWindowTitle(DOCKER_NAME)\r\n # Widget\r\n self.window = QTabWidget()\r\n self.layout = uic.loadUi(os.path.dirname(os.path.realpath(__file__)) + '/timer_watch.ui', self.window)\r\n self.setWidget(self.window)\r\n\r\n # Timer\r\n self.timer_hm = QtCore.QTimer(self)\r\n self.timer_hm.timeout.connect(self.HM_Display)\r\n self.timer_hm.timeout.connect(self.Info_Display)\r\n self.timer_hm.start(1000)\r\n\r\n self.timer_sw = QtCore.QTimer(self)\r\n self.timer_sw.timeout.connect(self.SW_Display)\r\n self.timer_sw.start(1000)\r\n\r\n # Inictialize Variables\r\n self.counter = 0\r\n self.switch = 0 # 0=Pause, 1=Play\r\n self.isreset = True\r\n\r\n # Start up Connection\r\n self.Connect()\r\n\r\n # Connect Funtions to Buttons\r\n def Connect(self):\r\n # Clean First Start\r\n self.SW_Reset()\r\n\r\n # Stopwatch buttons\r\n self.layout.pushButton_startpause.clicked.connect(self.SW_StartPause)\r\n self.layout.pushButton_reset.clicked.connect(self.SW_Reset)\r\n # self.layout.pushButton_alarm.toggled.connect(self.SW_Alarm)\r\n\r\n # Default Start UP Tab Display\r\n self.layout.setCurrentIndex(0)\r\n\r\n # Functions\r\n def HM_Display(self):\r\n self.currentTime = QtCore.QTime.currentTime()\r\n self.layout.lcdNumber_1.setDigitCount(5) # 5=hh:mm 8=hh:mm:ss\r\n self.strCurrentTime = self.currentTime.toString('hh:mm') # 'hh:mm' 'hh:mm:ss'\r\n self.layout.lcdNumber_1.display(self.strCurrentTime)\r\n\r\n def SW_Display(self):\r\n self.counter += 1\r\n self.SW_Tick(self.counter)\r\n\r\n def SW_Tick(self, counter):\r\n self.layout.lcdNumber_2.setDigitCount(8)\r\n self.strProgressTime = time.strftime('%H:%M:%S', time.gmtime(self.counter))\r\n if not self.isreset:\r\n self.layout.lcdNumber_2.display(self.strProgressTime)\r\n self.layout.progressBar_1.setValue(self.counter)\r\n self.layout.progressBar_2.setValue(self.counter)\r\n if (self.layout.pushButton_alarm.isChecked() == True and self.counter >= self.maximum):\r\n self.SW_Alarm()\r\n else:\r\n self.layout.lcdNumber_2.display('00:00:00')\r\n\r\n def SW_Time(self):\r\n # Convert Input Time\r\n hh = self.layout.timeEdit.time().hour()\r\n mm = self.layout.timeEdit.time().minute()\r\n ss = self.layout.timeEdit.time().second()\r\n conv = datetime.timedelta(hours=hh, minutes=mm)\r\n tsec = conv.total_seconds() + ss\r\n return tsec\r\n\r\n def SW_StartPause(self):\r\n # Select Operation\r\n if self.switch == 0:\r\n self.SW_Start() # 0=Pause change to Start\r\n elif self.switch == 1:\r\n self.SW_Pause() # 1=Start change to Pause\r\n else:\r\n self.SW_Reset()\r\n\r\n def SW_Start(self):\r\n # Start Ready\r\n self.maximum = self.SW_Time()\r\n self.layout.progressBar_1.setMaximum(self.maximum)\r\n self.layout.progressBar_2.setMaximum(self.maximum)\r\n # Commands\r\n self.timer_sw.start()\r\n # UI\r\n self.switch = 1\r\n self.isreset = False\r\n if self.maximum == 0: # if User time == Zero\r\n self.layout.pushButton_startpause.setText(\"Pause:Zero\")\r\n self.layout.timeEdit.setEnabled(False)\r\n self.layout.progressBar_1.setEnabled(False)\r\n self.layout.progressBar_2.setEnabled(False)\r\n else: # if User time is NOT Zero\r\n self.layout.pushButton_startpause.setText(\"Pause\")\r\n self.layout.timeEdit.setEnabled(False)\r\n self.layout.progressBar_1.setEnabled(True)\r\n self.layout.progressBar_2.setEnabled(True)\r\n\r\n def SW_Pause(self):\r\n # Commands\r\n self.timer_sw.stop()\r\n # UI\r\n self.switch = 0\r\n self.isreset = False\r\n self.layout.pushButton_startpause.setText(\"Start\")\r\n self.layout.timeEdit.setEnabled(False)\r\n self.layout.progressBar_1.setEnabled(True)\r\n self.layout.progressBar_2.setEnabled(True)\r\n\r\n def SW_Reset(self):\r\n # Variables\r\n self.counter = 0\r\n # Commands\r\n self.timer_sw.stop()\r\n self.SW_Tick(self.counter)\r\n # UI\r\n self.switch = 0\r\n self.isreset = True\r\n self.layout.pushButton_startpause.setText(\"Start\")\r\n self.layout.timeEdit.setEnabled(True)\r\n self.layout.progressBar_1.setEnabled(True)\r\n self.layout.progressBar_2.setEnabled(True)\r\n self.layout.progressBar_1.setValue(0)\r\n self.layout.progressBar_2.setValue(0)\r\n\r\n def SW_Alarm(self):\r\n QMessageBox.information(QWidget(), i18n(\"Warnning\"), i18n(message))\r\n self.SW_Pause()\r\n self.SW_Reset()\r\n\r\n def Info_Display(self):\r\n # Active Document\r\n ki = Krita.instance()\r\n ad = ki.activeDocument()\r\n if ad is None: # No Document is Active\r\n self.layout.label_00_title.setText(\"Title\")\r\n self.layout.label_05_initial_creator.setText(\"Initial Creator\")\r\n self.layout.label_11_12_first_last_name.setText(\"Creator Name\")\r\n self.layout.label_10_full_name.setText(\"Full Name\")\r\n self.layout.label_17_contact_type.setText(\"Contact Type\")\r\n self.layout.label_09_creation_date.setText(\"Creation Date\")\r\n self.layout.label_date_delta.setText(\"Date Delta\")\r\n self.layout.label_07_editing_time.setText(\"Editing Time\")\r\n self.layout.label_active_time.setText(\"Active Time\")\r\n self.layout.label_06_editing_cycles.setText(\"Editing Cycles\")\r\n else: # Requesto to active Document\r\n self.Info_Document()\r\n\r\n def Info_Document(self):\r\n # Active Document\r\n ki = Krita.instance()\r\n ad = ki.activeDocument()\r\n text = ad.documentInfo()\r\n ET = xml.etree.ElementTree\r\n root = ET.fromstring(text)\r\n\r\n # Call XML items with Error Check\r\n try: title = root[0][0].text # title\r\n except: title = \"Title\"\r\n # try: description = root[0][1].text # description\r\n # except: description = \"Description\"\r\n # try: subject = root[0][2].text # subject\r\n # except: subject = \"Subject\"\r\n # try: abstract = root[0][3].text # abstract\r\n # except: abstract = \"Abstract\"\r\n # try: keyword = root[0][4].text # keyword\r\n # except: keyword = \"Keyword\"\r\n try: initial_creator = root[0][5].text # initial-creator\r\n except: initial_creator = \"Initial Creator\"\r\n try: editing_cycles = root[0][6].text # editing-cycles\r\n except: editing_cycles = \"Editing Cycles\"\r\n try: editing_time = root[0][7].text # editing-time\r\n except: editing_time = \"Editing Time\"\r\n try: date = root[0][8].text # date\r\n except: date = \"Date\"\r\n try: creation_date = root[0][9].text # creation-date\r\n except: creation_date = \"Creation Date\"\r\n # try: language = root[0][10].text # language\r\n # except: language = \"Language\"\r\n # try: license = root[0][11].text # license\r\n # except: license = \"License\"\r\n try: full_name = root[1][0].text # full-name\r\n except: full_name = \"Full Name\"\r\n try: creator_first_name = root[1][1].text # creator-first-name\r\n except: creator_first_name = \"Fname\"\r\n try: creator_last_name = root[1][2].text # creator-last-name\r\n except: creator_last_name = \"Lname\"\r\n # try: initial = root[1][3].text # initial\r\n # except: initial = \"Initial\"\r\n # try: author_title = root[1][4].text # author-title\r\n # except: author_title = \"Author Title\"\r\n # try: position = root[1][5].text # position\r\n # except: position = \"Position\"\r\n # try: company = root[1][6].text # company\r\n # except: company = \"Company\"\r\n try: contact_type = root[1][7].text # contact type\r\n except: contact_type = \"Contact Type\"\r\n\r\n # Date Edits\r\n creator_first_last_name = str(creator_first_name)+\" \"+str(creator_last_name)\r\n\r\n cd2 = list(creation_date)\r\n cd2[10] = ' '\r\n cd3 = \"\".join(cd2)\r\n\r\n date1 = list(creation_date)\r\n year1 = int(\"\".join(date1[0:4]))\r\n month1 = int(\"\".join(date1[5:7]))\r\n day1 = int(\"\".join(date1[8:10]))\r\n hour1 = int(\"\".join(date1[11:13]))\r\n minute1 = int(\"\".join(date1[14:16]))\r\n second1 = int(\"\".join(date1[17:19]))\r\n\r\n date2 = list(date)\r\n year2 = int(\"\".join(date2[0:4]))\r\n month2 = int(\"\".join(date2[5:7]))\r\n day2 = int(\"\".join(date2[8:10]))\r\n hour2 = int(\"\".join(date2[11:13]))\r\n minute2 = int(\"\".join(date2[14:16]))\r\n second2 = int(\"\".join(date2[17:19]))\r\n\r\n date_start = datetime.datetime(year1, month1, day1, hour1, minute1, second1)\r\n date_now = datetime.datetime(year2, month2, day2, hour2, minute2, second2)\r\n delta = (date_now - date_start).days\r\n\r\n yearHH = int(delta) // 365\r\n yearTT = int(delta) - (yearHH * 365)\r\n monthHH = yearTT // 30\r\n monthTT = yearTT - (monthHH * 30)\r\n dayHH = monthTT\r\n\r\n date_delta = str(yearHH)+\"y \"+str(monthHH)+\"m \"+str(dayHH)+\"d ago\"\r\n\r\n if editing_time == \"Editing Time\" or editing_time is None:\r\n editing_time = \"Unaware\"\r\n active_time = \"Unaware\"\r\n else:\r\n yearNN = int(editing_time) // 31557600 #year\r\n yearRR = int(editing_time) - (yearNN * 31557600)\r\n monthNN = yearRR // 2629800 # month\r\n monthRR = yearRR - (monthNN * 2629800)\r\n dayNN = monthRR // 86400 # day\r\n dayRR = monthRR - (dayNN * 86400)\r\n hourNN = dayRR // 3600\r\n hourRR = dayRR - (hourNN * 3600)\r\n minuteNN = hourRR // 60\r\n minuteRR = hourRR - (minuteNN * 60)\r\n secondNN = minuteRR\r\n active_time = str(yearNN)+\"y \"+str(monthNN)+\"m \"+str(dayNN)+\"d . \"+str(hourNN)+\"h \"+str(minuteNN)+\"m \"+str(secondNN)+\"s work\"\r\n\r\n # Deplay XML items on the tab\r\n self.layout.label_00_title.setText(title)\r\n self.layout.label_05_initial_creator.setText(initial_creator)\r\n self.layout.label_11_12_first_last_name.setText(creator_first_last_name)\r\n self.layout.label_10_full_name.setText(full_name)\r\n self.layout.label_17_contact_type.setText(contact_type)\r\n self.layout.label_09_creation_date.setText(cd3)\r\n self.layout.label_date_delta.setText(date_delta)\r\n self.layout.label_07_editing_time.setText(editing_time)\r\n self.layout.label_active_time.setText(active_time)\r\n self.layout.label_06_editing_cycles.setText(editing_cycles)\r\n\r\n # Change the Canvas\r\n def canvasChanged(self, canvas):\r\n pass\r\n", "sub_path": "timer_watch/timer_watch.py", "file_name": "timer_watch.py", "file_ext": "py", "file_size_in_byte": 11727, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "PyQt5.uic.loadUi", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.uic", "line_number": 25, "usage_type": "name"}, {"api_name": "os.path.path.dirname", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 25, "usage_type": "name"}, {"api_name": "os.path.path.realpath", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QTimer", "line_number": 29, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 29, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QTimer", "line_number": 34, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 34, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QTime.currentTime", "line_number": 61, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QTime", "line_number": 61, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 61, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 72, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 87, "usage_type": "call"}, {"api_name": "xml.etree", "line_number": 176, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 244, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 245, "usage_type": "call"}]} +{"seq_id": "507208595", "text": "import pytest\n\nfrom tinydb import TinyDB, where\nfrom tinydb.migrate import migrate\n\nv1_0 = \"\"\"\n{\n \"_default\": [{\"key\": \"value\", \"_id\": 1}],\n \"table\": [{\"key\": \"value\", \"_id\": 2}]\n}\n\"\"\"\n\n\ndef test_open_old(tmpdir):\n # Make sure that opening an old database results in an exception and not\n # in data loss\n db_file = tmpdir.join('db.json')\n db_file.write(v1_0)\n\n with pytest.raises(Exception):\n TinyDB(str(db_file))\n\n\ndef test_upgrade(tmpdir):\n db_file = tmpdir.join('db.json')\n db_file.write(v1_0)\n\n # Run upgrade\n assert migrate(str(db_file)) is True\n db = TinyDB(str(db_file))\n\n assert db.count(where('key') == 'value') == 1\n\n\ndef test_no_upgrade_needed(tmpdir):\n db_file = tmpdir.join('db.json')\n with TinyDB(str(db_file)) as db:\n db.insert({'val': 1})\n\n assert migrate(str(db_file)) is False\n", "sub_path": "tests/test_migrate.py", "file_name": "test_migrate.py", "file_ext": "py", "file_size_in_byte": 857, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pytest.raises", "line_number": 20, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 21, "usage_type": "call"}, {"api_name": "tinydb.migrate.migrate", "line_number": 29, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 30, "usage_type": "call"}, {"api_name": "tinydb.where", "line_number": 32, "usage_type": "call"}, {"api_name": "tinydb.TinyDB", "line_number": 37, "usage_type": "call"}, {"api_name": "tinydb.migrate.migrate", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "153082623", "text": "import time\nimport unittest\n\nfrom selenium import webdriver\n\n\nfrom Register.pages.home import Home\n\nfrom colour import Color\n\n\n\n\nclass RegisterPage(unittest.TestCase):\n driver = None\n\n def setUp(self):\n self.driver.get(\"http://taqc-opencart.epizy.com/\")\n time.sleep(1)\n self.home = Home(self.driver)\n\n def tearDown(self):\n time.sleep(2)\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n cls.driver.maximize_window()\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n def test_color_required_fields(self):\n register_page = self.home.get_header()\\\n .account_dropdown\\\n .click()\\\n .clickRegister() \\\n .click_continue()\n\n self.assertEqual(register_page.get_colour_firstname, '#F00')\n", "sub_path": "HW/rrasi/HW6/tests/test_colour_requiredfields.py", "file_name": "test_colour_requiredfields.py", "file_ext": "py", "file_size_in_byte": 841, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "unittest.TestCase", "line_number": 14, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 19, "usage_type": "call"}, {"api_name": "Register.pages.home.Home", "line_number": 20, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 23, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 27, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "446503366", "text": "import json\nimport random\nimport difflib\nimport discord\n\nfrom discord.ext import commands\n\nimport utils\n\n\nthing = '''\n@parent_command.command(name='all')\nasync def {0}_all(ctx):\n \"\"\"Gives you a list off all {0}s.\"\"\"\n data = ctx.command.parent.instance.data[\"{0}\"]\n results = [v['Name'] for k, v in data.items()]\n try:\n p = utils.EmbedPaginator(ctx, entries=results, per_page=15)\n p.embed.colour = 0x738bd7\n await p.paginate()\n except Exception as e:\n await ctx.send(e)\n\n@parent_command.command(name='search')\nasync def {0}_search(ctx, *, query: str):\n \"\"\"Searches for {1} {0}.\"\"\"\n query = query.lower()\n data = ctx.command.parent.instance.data[\"{0}\"]\n results = [v['Name'] for k, v in data.items() if query in k]\n results.sort()\n if results:\n try:\n p = utils.EmbedPaginator(ctx, entries=results, per_page=15)\n p.embed.colour = 0x738bd7\n await p.paginate()\n except Exception as e:\n await ctx.send(e)\n else:\n await ctx.send('No {0} found.')\n\n@{0}_search.error\nasync def {0}_search_error(ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Missing query.')\n'''\n\n\nclass XenobladeX:\n classes = [\n 'Drifter', 'Deulist', 'Bastion Warrior', 'Full Metal Jaguar',\n 'Astral Crusader', 'Mastermind', 'Galactic Knight'\n ]\n\n melee_weapons = [\n 'Longsword', 'Shield', 'Dual Swords',\n 'Javelin', 'Knife', 'Photon Saber'\n ]\n\n ranged_weapons = [\n 'Assault Rifle', 'Gatling Gun', 'Dual Guns', 'Sniper Rifle',\n 'Raygun', 'Psycho Launchers', 'Multigun'\n ]\n\n party_members = [\n 'Elma', 'Lin', 'Gwin', 'Irina', 'Lao', 'Doug', 'L',\n 'Murderess', 'Hope', 'Mia', 'Nagi', 'Phog', 'Frye',\n 'Celica', 'Boze', 'Alexa', 'Yelv', 'H.B.'\n ]\n\n def __init__(self):\n self.data = {}\n self.colors = {\n 'Common': 0x646864,\n 'Rare': 0x0074A7,\n 'Unique': 0x10AB6C,\n 'Intergalactic': 0xAB6C02,\n }\n\n for filename in ['skills', 'arts', 'augments']:\n with open(f'xenox/json/{filename}.json') as f:\n setattr(self, filename, json.load(f))\n self.data[filename[:-1]] = getattr(self, filename)\n\n for key in self.data.keys():\n parent_command = getattr(self, key)\n env = {'parent_command': parent_command}\n env.update(globals())\n exec(thing.format(key, 'an' if key[0] == 'a' else 'a'), env)\n\n with open('xenox/json/materials.json') as f:\n self.materials = json.load(f)\n\n def get_entry(self, entry_type, name):\n data = self.data[entry_type.lower()]\n try:\n return data[name]\n except KeyError:\n possible_matches = difflib.get_close_matches(name, data, 1000)\n if not possible_matches:\n raise RuntimeError(f'{entry_type} not found.')\n\n items = data.items()\n entry_list = [v['Name'] for k, v in items if k in possible_matches]\n possible_entries = '\\n'.join(entry_list)\n raise RuntimeError(f'{entry_type} not found. Did you mean...\\n{possible_entries}')\n\n @utils.group(invoke_without_command=True)\n async def skill(self, ctx, *, skill: str):\n \"\"\"Gives you information about a skill.\"\"\"\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)\n\n @skill.error\n async def skill_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Missing skill name.')\n\n @utils.group(invoke_without_command=True)\n async def art(self, ctx, *, art: str):\n \"\"\"Gives you information about an art.\"\"\"\n try:\n art = self.get_entry('Art', art.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = art['Name']\n description = art['Description']\n weapon = art['Weapon']\n learned = art['Class/Rank']\n effect_range = art['Effect Range']\n attribute = art['Attribute']\n hits = art['Hits']\n scaling = art['Hit Scaling']\n cooldown = art['Cooldown']\n cooldown_bonus = art['Secondary/Tertiary']\n special_effects = art['Special Effects']\n aura_effects = art['Aura Effects']\n extra_effects = art['Extra Effects']\n additional_effects = art['Additional Effects']\n effects = art['Effects']\n aura = art['Aura']\n duration = art['Effect Duration']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://art.png')\n embed.add_field(name='Weapon', value=weapon)\n embed.add_field(name='Learned', value=learned)\n embed.add_field(name='Effect Range', value=effect_range)\n if attribute:\n embed.add_field(name='Attribute', value=attribute)\n if hits:\n embed.add_field(name='Hits', value=hits)\n if scaling:\n embed.add_field(name='Hit Scaling', value=scaling)\n embed.add_field(name='Cooldown', value=cooldown)\n embed.add_field(name='Cooldown Bonus', value=cooldown_bonus)\n if special_effects:\n embed.add_field(name='Special Effects', value=special_effects,\n inline=False)\n if aura_effects:\n embed.add_field(name='Aura Effects', value=aura_effects,\n inline=False)\n if extra_effects:\n embed.add_field(name='Extra Effects', value=extra_effects,\n inline=False)\n if additional_effects:\n embed.add_field(name='Additional Effects',\n value=additional_effects)\n if effects:\n embed.add_field(name='Effects', value=effects)\n if aura:\n embed.add_field(name='Aura', value=aura)\n if duration:\n embed.add_field(name='Duration', value=duration)\n embed.add_field(name='Description', value=description, inline=False)\n await ctx.send(file=discord.File(f'xenox/arts/{name}.png', 'art.png'),\n embed=embed)\n\n @art.error\n async def art_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Missing art name.')\n\n @utils.group(invoke_without_command=True, aliases=['aug'])\n async def augment(self, ctx, *, augment: str):\n \"\"\"Gives you information about an augment.\"\"\"\n try:\n augment = self.get_entry('Augment', augment.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n type = augment['Type']\n price = augment['Sell Price']\n miranium = augment.get('Required Miranium')\n mat_1 = augment.get('Material 1')\n mat_2 = augment.get('Material 2')\n mat_3 = augment.get('Material 3')\n drop = augment.get('Drop')\n resource = augment.get('Precious Resource')\n\n total_tickets = 0\n\n embed = discord.Embed(title=augment['Name'], color=self.colors[augment[\"Rarity\"]])\n embed.add_field(name='Effect', value=augment['Effect'], inline=False)\n\n if type != 'Augment': # Remove when augment json fully updated\n embed.add_field(name='Type', value=type)\n\n if price != 0: # Remove when augment json fully updated\n embed.add_field(name='Sell Price', value=price)\n\n if miranium:\n embed.add_field(name='Required Miranium', value=miranium)\n\n if mat_1:\n name = mat_1[\"Name\"]\n amount = mat_1[\"Amount\"]\n\n tickets = self.materials[name.lower()]['price'] * amount\n total_tickets += tickets\n\n embed.add_field(name='Material 1', value=f'{amount} {name}\\n({tickets} Tickets)')\n\n if mat_2:\n name = mat_2[\"Name\"]\n amount = mat_2[\"Amount\"]\n\n tickets = self.materials[name.lower()]['price'] * amount\n total_tickets += tickets\n\n embed.add_field(name='Material 2', value=f'{amount} {name}\\n({tickets} Tickets)')\n\n if mat_3:\n name = mat_3[\"Name\"]\n amount = mat_3[\"Amount\"]\n\n tickets = self.materials[name.lower()]['price'] * amount\n total_tickets += tickets\n\n embed.add_field(name='Material 3', value=f'{amount} {name}\\n({tickets} Tickets)')\n\n if drop:\n embed.add_field(name='Drop', value=drop)\n if resource:\n embed.add_field(name='Precious Resource', value=f'{resource[\"Amount\"]} {resource[\"Name\"]}', inline=False)\n\n if total_tickets != 0:\n embed.add_field(name='Total Tickets', value=total_tickets)\n\n await ctx.send(embed=embed)\n\n @augment.error\n async def augment_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Missing augment name.')\n\n @commands.command()\n async def loadout(self, ctx):\n fmt = f'Class: {random.choice(self.classes)}\\n' \\\n f'Melee Weapon: {random.choice(self.melee_weapons)}\\n' \\\n f'Ranged Weapon: {random.choice(self.ranged_weapons)}\\n' \\\n f'Party Members: {\", \".join(random.sample(self.party_members, 3))}'\n\n await ctx.send(fmt)\n\n\ndef setup(bot):\n bot.add_cog(XenobladeX())\n", "sub_path": "cogs/xenobladex.py", "file_name": "xenobladex.py", "file_ext": "py", "file_size_in_byte": 9839, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 81, "usage_type": "call"}, {"api_name": "json.load", "line_number": 91, "usage_type": "call"}, {"api_name": "difflib.get_close_matches", "line_number": 98, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 118, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 123, "usage_type": "call"}, {"api_name": "utils.group", "line_number": 107, "usage_type": "call"}, {"api_name": "discord.ext.commands.MissingRequiredArgument", "line_number": 127, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 127, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 156, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 188, "usage_type": "call"}, {"api_name": "utils.group", "line_number": 130, "usage_type": "call"}, {"api_name": "discord.ext.commands.MissingRequiredArgument", "line_number": 193, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 193, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 215, "usage_type": "call"}, {"api_name": "utils.group", "line_number": 196, "usage_type": "call"}, {"api_name": "discord.ext.commands.MissingRequiredArgument", "line_number": 266, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 266, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 271, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 272, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 273, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 274, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 269, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 269, "usage_type": "name"}]} +{"seq_id": "238970696", "text": "import grpc\nimport time\nimport cv2\nimport logging\nimport sys\nimport numpy as np\nfrom argparse import ArgumentParser\n\nfrom rotational_invariance_pb2 import Null\nfrom rotational_invariance_pb2_grpc import ImageServiceStub\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass ImageClient(object):\n def __init__(self, host):\n self.host = host\n self.mode = 'camera'\n if isinstance(self.host, str):\n logger.info('starting client, connecting to %s' % (host))\n self.channel = grpc.insecure_channel('%s' % (host))\n self.stub = ImageServiceStub(self.channel)\n self.mode = 'grpc'\n elif isinstance(self.host, int):\n logger.info('starting local camera %d...' % (self.host))\n self.camera = cv2.VideoCapture(self.host)\n if not self.camera.isOpened():\n logger.info('unable to open local camera %d' % (self.host))\n sys.exit(-1)\n\n def get_image(self):\n \"\"\"\n retrieve image from different source\n both outputs a BGR image\n grpc: from image server\n camera: from local camera\n \"\"\"\n if self.mode == 'grpc':\n image = self.stub.GetImage(Null())\n img = np.fromstring(image.data,\n dtype=np.uint8).reshape([image.height, image.width, image.channel])\n return img\n elif self.mode == 'camera':\n _, image = self.camera.read()\n return image\n return None\n\n def run(self):\n try:\n while True:\n img = self.get_image()\n cv2.imshow('Server Image', img)\n key = cv2.waitKey(20)\n if key in [ord('q'), ord('Q')]:\n break\n except KeyboardInterrupt:\n logger.info('close client')\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('--ip', dest='ip', default='localhost',\n type=str, help='server ip')\n parser.add_argument('--port', dest='port', default=50051,\n type=int, help='server port')\n parser.add_argument('--camera-id', dest='camera_id', default=0,\n type=int, help='local camera id')\n parser.add_argument('--mode', dest='mode', default='camera',\n type=str, help='mode to open (eg. camera/grpc)')\n args = parser.parse_args()\n\n if args.mode == 'camera':\n host = args.camera_id\n else:\n host = '%s:%d' % (args.ip, args.port)\n if host is not None:\n client = ImageClient(host)\n client.run()\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "rotational-invariance/image_client.py", "file_name": "image_client.py", "file_ext": "py", "file_size_in_byte": 2353, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.basicConfig", "line_number": 13, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 15, "usage_type": "attribute"}, {"api_name": "grpc.insecure_channel", "line_number": 24, "usage_type": "call"}, {"api_name": "rotational_invariance_pb2_grpc.ImageServiceStub", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 32, "usage_type": "call"}, {"api_name": "rotational_invariance_pb2.Null", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.fromstring", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 44, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 56, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 64, "usage_type": "call"}]} +{"seq_id": "434359377", "text": "import datetime\nfrom pprint import pprint \n\nfrom ..utils.muted_objects import MutedList\nfrom ..utils.orm.connector import session_scope\nfrom ..utils.orm.orm import Session, Display, Action, Subsession\nfrom pyreact_core.query.displays import get_display\nfrom pyreact_core.query.actions import get_actions\nimport ujson\n\n\ndef create_query_subsession(display_id, window_size=2, verbose=True):\n \"\"\"\n Create a query subsession,with a tail of size \n\n :param display_id: The last display ID\n :param window_size: the size of the tail\n :param verbose: If True, details will be printed.\n :return: A subsession object.\n \"\"\"\n\n qss = Subsession()\n session_dict = {}\n last_display = get_display(display_id, verbose=False)\n session_id = last_display.session_id\n session_length = get_actions(session_id=session_id).count() + 1 \n if not last_display:\n return None\n if last_display.get_parent_action():\n action_type = last_display.get_parent_action().action_type\n else:\n action_type = None\n actions_list = []\n displays_list = [last_display.display_id]\n\n i = 0\n\n while i < window_size and last_display.get_parent_action():\n last_action = last_display.get_parent_action()\n #last_display = get_display(last_action.parent_display_id)\n #last_display = last_action.parent_display\n last_display = get_display(last_action.parent_display_id, verbose=False)\n actions_list.append(last_action.action_id)\n displays_list.append(last_display.display_id)\n i += 1\n\n session_dict[\"actions\"] = actions_list\n session_dict[\"displays\"] = displays_list\n session_dict[\"similarities\"] = {}\n\n #if i == window_size:\n if not action_type:\n qss.last_action_type = 'begin'\n else:\n qss.last_action_type = action_type\n #qss.last_action_type = action_type\n qss.session_id = session_id\n qss.session_length = session_length\n qss.data = session_dict\n if verbose:\n pprint(qss.to_dict())\n return qss\n \"\"\"\n else:\n if verbose:\n print(\"Tail size \", i, \" is too short. Window size is:\", window_size)\n return None\n \"\"\"\n\n\n\n\ndef create_subsession(action_id, window_size=2, verbose=True):\n \"\"\"\n Create a session window, containing the current action, a tail of size \n\n :param action_id: The current display ID\n :param window_size: the size of the tail\n :param verbose: If True, details will be printed.\n :return: A dictionary containing IDs of the sessions tree nodes/edges.\n \"\"\"\n\n last_action = get_actions(action_id=action_id, verbose=False)[0]\n session_id = last_action.session_id\n session_length = get_actions(session_id=session_id).count()\n session_dict = {}\n session_dict[\"next_action\"] = last_action.action_id\n last_display = get_display(last_action.parent_display_id, verbose=False)\n #p_action = last_display.get_parent_action()\n if last_display and last_display.get_parent_action():\n action_type = last_display.get_parent_action().action_type\n else:\n action_type = None\n actions_list = []\n displays_list = [last_display.display_id]\n\n i = 0\n\n while i < window_size and last_display.get_parent_action():\n last_action = last_display.get_parent_action()\n #last_display = get_display(last_action.parent_display_id)\n #last_display = last_action.parent_display\n last_display = get_display(last_action.parent_display_id, verbose=False)\n actions_list.append(last_action.action_id)\n displays_list.append(last_display.display_id)\n i += 1\n\n session_dict[\"actions\"] = actions_list\n session_dict[\"displays\"] = displays_list\n session_dict[\"similarities\"] = {}\n #print(ujson.dumps(session_dict))\n #if i == window_size:\n with session_scope() as session:\n ss = Subsession()\n if not action_type:\n ss.last_action_type = 'begin'\n else:\n ss.last_action_type = action_type\n ss.session_id = session_id\n ss.session_length = session_length\n ss.data = session_dict\n session.add(ss)\n session.commit()\n \n if verbose:\n print(\"New sub-session:\\n\")\n pprint(ss.to_dict())\n return ss\n #print(\"NOT IN DB:,i=\", i, session_dict)\n\n\ndef get_subsessions(subsession_id=None, session_id=None, last_action_type=None, verbose=False):\n \"\"\"\n Fetch the available sessions for user in project \n\n :param user_id: The user ID\n :param project_id: The Project ID \n :param verbose: If True, session details will be printed.\n :return: A list of available sessions.\n \"\"\"\n # Validate parameters.\n\n with session_scope() as session:\n subsessions = session.query(Subsession)\n if last_action_type:\n subsessions = subsessions.filter(Subsession.last_action_type == last_action_type)\n if subsession_id:\n subsessions = subsessions.filter(Subsession.subsession_id == subsession_id)\n if session_id:\n subsessions = subsessions.filter(Subession.session_id == session_id)\n if verbose and subsessions:\n for s in subsessions:\n pprint(s.to_dict())\n #if len(subsessions.all()) == 1:\n # return subsessions[0]\n #else:\n #return subsessions\n return subsessions\n\n\n\n\n \n\n\ndef get_sessions(user_id=None, project_id=None,session_id=None, verbose=False):\n \"\"\"\n Fetch the available sessions for user in project \n\n :param user_id: The user ID\n :param project_id: The Project ID \n :param verbose: If True, session details will be printed.\n :return: A list of available sessions.\n \"\"\"\n # Validate parameters.\n\n with session_scope() as session:\n sessions = session.query(Session)\n if user_id:\n sessions = sessions.filter(Session.user_id == user_id)\n if project_id:\n sessions = sessions.filter(Session.project_id == project_id)\n if session_id:\n sessions = sessions.filter(Session.session_id == session_id)\n if verbose and sessions:\n for s in sessions:\n pprint(s.to_dict())\n return sessions\n\n\ndef create_session(user_id, project_id, verbose=True):\n \"\"\"\n Create a new session for user in project \n\n :param user_id: The user ID\n :param project_id: The Project ID\n :param verbose: If True, session details will be printed.\n :return: The new session\n \"\"\"\n\n with session_scope() as session:\n s = Session()\n s.user_id = user_id\n s.project_id = project_id\n session.add(s)\n session.commit()\n\n s = session.query(Session).filter(Session.session_id == s.session_id).one()\n if verbose:\n print(\"New session:\")\n pprint(s.to_dict())\n return s\n\n__all__ = ['get_sessions', 'create_session', 'create_subsession','create_query_subsession']\n", "sub_path": "pyreact_core/query/sessions.py", "file_name": "sessions.py", "file_ext": "py", "file_size_in_byte": 7052, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "utils.orm.orm.Subsession", "line_number": 22, "usage_type": "call"}, {"api_name": "pyreact_core.query.displays.get_display", "line_number": 24, "usage_type": "call"}, {"api_name": "pyreact_core.query.actions.get_actions", "line_number": 26, "usage_type": "call"}, {"api_name": "pyreact_core.query.displays.get_display", "line_number": 42, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 61, "usage_type": "call"}, {"api_name": "pyreact_core.query.actions.get_actions", "line_number": 83, "usage_type": "call"}, {"api_name": "pyreact_core.query.actions.get_actions", "line_number": 85, "usage_type": "call"}, {"api_name": "pyreact_core.query.displays.get_display", "line_number": 88, "usage_type": "call"}, {"api_name": "pyreact_core.query.displays.get_display", "line_number": 103, "usage_type": "call"}, {"api_name": "utils.orm.connector.session_scope", "line_number": 113, "usage_type": "call"}, {"api_name": "utils.orm.orm.Subsession", "line_number": 114, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 127, "usage_type": "call"}, {"api_name": "utils.orm.connector.session_scope", "line_number": 143, "usage_type": "call"}, {"api_name": "utils.orm.orm.Subsession", "line_number": 144, "usage_type": "argument"}, {"api_name": "utils.orm.orm.Subsession.last_action_type", "line_number": 146, "usage_type": "attribute"}, {"api_name": "utils.orm.orm.Subsession", "line_number": 146, "usage_type": "name"}, {"api_name": "utils.orm.orm.Subsession.subsession_id", "line_number": 148, "usage_type": "attribute"}, {"api_name": "utils.orm.orm.Subsession", "line_number": 148, "usage_type": "name"}, {"api_name": "pprint.pprint", "line_number": 153, "usage_type": "call"}, {"api_name": "utils.orm.connector.session_scope", "line_number": 177, "usage_type": "call"}, {"api_name": "utils.orm.orm.Session", "line_number": 178, "usage_type": "argument"}, {"api_name": "utils.orm.orm.Session.user_id", "line_number": 180, "usage_type": "attribute"}, {"api_name": "utils.orm.orm.Session", "line_number": 180, "usage_type": "name"}, {"api_name": "utils.orm.orm.Session.project_id", "line_number": 182, "usage_type": "attribute"}, {"api_name": "utils.orm.orm.Session", "line_number": 182, "usage_type": "name"}, {"api_name": "utils.orm.orm.Session.session_id", "line_number": 184, "usage_type": "attribute"}, {"api_name": "utils.orm.orm.Session", "line_number": 184, "usage_type": "name"}, {"api_name": "pprint.pprint", "line_number": 187, "usage_type": "call"}, {"api_name": "utils.orm.connector.session_scope", "line_number": 201, "usage_type": "call"}, {"api_name": "utils.orm.orm.Session", "line_number": 202, "usage_type": "call"}, {"api_name": "utils.orm.orm.Session", "line_number": 208, "usage_type": "argument"}, {"api_name": "utils.orm.orm.Session.session_id", "line_number": 208, "usage_type": "attribute"}, {"api_name": "pprint.pprint", "line_number": 211, "usage_type": "call"}]} +{"seq_id": "186297603", "text": "import pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\n\n# 파라미터 \npage = '1' # 페이지수 \nrow = '10' # 페이지당 목록 수 \nsDate = '20200310' # 조회 시작일 : YYYYMMDD\neDate = '20200422' # 조회 종료일 : YYYYMMDD\n# 파라미터 조합 \nparams = '&' + 'pageNo=' + page + '&' + 'numOfRows=' + row + '&' + 'startCreateDt=' + sDate + '&' + 'endCreateDt=' + eDate\n# API 인증키 \nkey = 'pheKFj8Pv7Uv7EnJIYCWrt2jBSOo6WalN3YPI08%' + '2FjDXHKtpOthPuS4atzK7C8W2xQv071%' + '2FNJej2ceRkz9T6QYg%3D%3D'\n\n# Open API URL \nurl = 'http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=' + key + params\n\nreq = requests.get(url) \nprint(type(req))\nhtml = req.text \nprint(type(html)) #이제 string객체로 바꼈다.\nprint(html) #이렇게 내용물을 확인할 수 있다.\n\nsoup = BeautifulSoup(html, 'html.parser')\nfinded_values = soup.find_all('item')\n[x.text for x in finded_values]\n\n", "sub_path": "nn_Python/projs/0421_Project copy.py", "file_name": "0421_Project copy.py", "file_ext": "py", "file_size_in_byte": 988, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "388142947", "text": "try:\n from pygame import *\n import pygame\n import sys\n from SpriteSheet import *\n import Utilities\n from ImageCanvas import ImageCanvas\n import ControlFrame\nexcept ImportError as err:\n print(\"Could not load module. %s\" % err)\n sys.exit()\n\nWIDTH, HEIGHT = 1400, 600\nCANVAS_WIDTH = 900\n\n\"\"\"\nMain program\n\"\"\"\n\n\nclass SpriteSheetEditor:\n\n # Set up game objects\n def __init__(self, screen, sprite_sheet_image, sprite_sheet_data):\n self.screen = screen\n pygame.display.set_caption(\"Sprite Sheet Editor - %s\" %\n sprite_sheet_data.name)\n\n self.game_objects = {\"image_canvas\": ImageCanvas.ImageCanvas(sprite_sheet_image),\n \"control_frame\": ControlFrame.ControlFrame(sprite_sheet_data)}\n self.main_loop()\n\n # Typical game cycle\n def main_loop(self):\n while True:\n self.handle_events()\n self.update()\n self.render()\n\n # Give each game object the events\n def handle_events(self):\n events = pygame.event.get()\n pressed = pygame.key.get_pressed()\n for event in events:\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n return\n\n for obj in self.game_objects.values():\n obj.handle_input(events, pressed)\n return\n\n # Update each game object\n def update(self):\n for obj in self.game_objects.values():\n obj.update()\n\n # Render the program is correct order\n def render(self):\n pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(0, 0, WIDTH, HEIGHT))\n self.game_objects[\"image_canvas\"].render(self.screen)\n self.game_objects[\"control_frame\"].render(self.screen)\n pygame.display.flip()\n\n\n\"\"\"\nProgram can be called with or without existing sprite-sheet data file.\nFirst argument is the sprite-sheet image to work with and second is\noption existing sprite-sheet data. Once the file(s) is/are loaded\nthen start program with the data as the arguments.\n\"\"\"\nif __name__ == \"__main__\":\n pygame.init()\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n if len(sys.argv) == 3:\n sprite_sheet_image = Utilities.load_image(sys.argv[1])\n sprite_sheet_data = Utilities.load_sprite_sheet(sys.argv[2])\n\n sse = SpriteSheetEditor(screen, sprite_sheet_image, sprite_sheet_data)\n elif len(sys.argv) == 2:\n sprite_sheet_image = Utilities.load_image(sys.argv[1])\n sprite_sheet_data = Utilities.load_sprite_sheet(sys.argv[1])\n\n sse = SpriteSheetEditor(screen, sprite_sheet_image, sprite_sheet_data)\n else:\n print(\"Invalid program arguments\")\n pygame.quit()\n sys.exit()\n\n", "sub_path": "SpriteSheetEditor.py", "file_name": "SpriteSheetEditor.py", "file_ext": "py", "file_size_in_byte": 2745, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.exit", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.display.set_caption", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 26, "usage_type": "attribute"}, {"api_name": "ImageCanvas.ImageCanvas.ImageCanvas", "line_number": 29, "usage_type": "call"}, {"api_name": "ImageCanvas.ImageCanvas", "line_number": 29, "usage_type": "name"}, {"api_name": "ControlFrame.ControlFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 46, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 47, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 74, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 75, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 75, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 76, "usage_type": "attribute"}, {"api_name": "Utilities.load_image", "line_number": 77, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 77, "usage_type": "attribute"}, {"api_name": "Utilities.load_sprite_sheet", "line_number": 78, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 78, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 81, "usage_type": "attribute"}, {"api_name": "Utilities.load_image", "line_number": 82, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 82, "usage_type": "attribute"}, {"api_name": "Utilities.load_sprite_sheet", "line_number": 83, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 83, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 88, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "616077472", "text": "#!/home/xlin/miniconda3/bin/python\n# -*- coding: utf-8 -*-\n \nimport logging\nimport os.path\nimport sys\nimport multiprocessing\nimport time\n\nimport pickle\nimport numpy as np\nfrom gensim.corpora import WikiCorpus\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\nfrom gensim.models.keyedvectors import KeyedVectors\nfrom scipy import spatial\n\nfrom numpy import dot\nfrom numpy.linalg import norm\nimport random\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\n\nimport scipy\nfrom scipy.sparse import lil_matrix\nfrom scipy.sparse import coo_matrix\nfrom scipy.sparse.linalg import spsolve\nfrom distutils.log import info\n\nif __name__ == '__main__':\n \n # check and process input arguments\n if len(sys.argv) < 3:\n print(globals()['__doc__'] % locals())\n sys.exit(1)\n \n pklFile = open(sys.argv[1], 'rb')\n wv = pickle.load(pklFile)\n pklFile.close()\n wv2 = KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin\", binary=True)\n \n if (len(sys.argv) == 3):\n testWord = sys.argv[2]\n v1 = wv[testWord]\n maxCosSim = -1.0e100\n maxSimWord = testWord\n counter = 0\n for aWord in wv.keys():\n if (aWord not in wv2.vocab.keys()):\n continue\n if (testWord == aWord):\n continue\n v2 = wv[aWord]\n cosSim = abs(dot(v1, v2)/norm(v2))\n if (maxCosSim < cosSim) :\n maxCosSim = cosSim\n maxSimWord = aWord\n counter += 1\n if (counter % 100000 == 0):\n print(\"%s\" % maxSimWord)\n \n print(\"Word most similar to %s: %s %.6f\" % (testWord, maxSimWord, maxCosSim/norm(v1)))\n elif (len(sys.argv) == 5):\n w1 = sys.argv[2]\n w2 = sys.argv[3]\n w3 = sys.argv[4]\n isCommonWord = (w1 in wv2.vocab.keys()) and (w2 in wv2.vocab.keys()) and (w3 in wv2.vocab.keys())\n v1 = wv[w1]\n v2 = wv[w2]\n v3 = wv[w3]\n v0 = v1 + v2 -v3\n maxCosSim = -1.0e100\n maxSimWord = w3\n counter = 0\n for aWord in wv.keys():\n if isCommonWord and (aWord not in wv2.vocab.keys()):\n continue\n badWord = False\n for c in aWord:\n if ( ( (c < 'a') or (c > 'z') ) and ( (c < 'A') or (c > 'Z') ) ):\n #if ( (c < 'a') or (c > 'z') ):\n badWord = True\n break\n if (badWord) :\n continue \n if (w1 == aWord):\n continue\n if (w2 == aWord):\n continue\n if (w3 == aWord):\n continue\n v2 = wv[aWord]\n cosSim = abs(dot(v0, v2)/norm(v2))\n if (maxCosSim < cosSim) :\n maxCosSim = cosSim\n maxSimWord = aWord\n counter += 1\n if (counter % 100000 == 0):\n print(\"%s\" % maxSimWord)\n \n print(\"%s:%s => %s:%s, %.6f\" % (w1, w3, w2, maxSimWord, maxCosSim/norm(v0)))\n \n \n \n \n \n", "sub_path": "word2vec/getMostSimilar.py", "file_name": "getMostSimilar.py", "file_ext": "py", "file_size_in_byte": 3127, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 33, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 35, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 38, "usage_type": "call"}, {"api_name": "gensim.models.keyedvectors.KeyedVectors.load_word2vec_format", "line_number": 40, "usage_type": "call"}, {"api_name": "gensim.models.keyedvectors.KeyedVectors", "line_number": 40, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 43, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 63, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 64, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 65, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 101, "usage_type": "call"}]} +{"seq_id": "151255794", "text": "import os\nimport sys\nimport gym\nfrom gym import wrappers\nimport random\nimport numpy as np\nimport math\n\nimport torch\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom ACNet import save_checkpoint, load_checkpoint\n\n\nclass ReplayMemory(object):\n def __init__(self, capacity):\n self.capacity = capacity\n self.load = 0\n self.batchsize = 0\n self.memory = []\n\n def push(self, events):\n # Events = list(zip(*events))\n # self.memory.append(map(lambda x: torch.cat([torch.repeat_interleave(torch.zeros_like(x[0]),(1000-len(x)),dim = 0),\n # torch.cat(x, 0)],0), events))\n self.memory.append(map(lambda x: torch.cat(x, 0), events))\n self.load += len(events[1])\n self.batchsize += 1\n # if len(self.memory)>self.capacity:\n # del self.memory[0]\n\n def clear(self):\n self.memory = []\n self.load = 0\n self.batchsize = 0\n\n def pull(self):\n Memory = list(zip(*self.memory))\n data = map(lambda x: torch.cat(x, 1), Memory)\n return data\n\n\ndef train(env, model, optimizer, shared_obs_stats, device, params):\n memory = ReplayMemory(params.num_steps)\n state = env.reset()\n done = True\n episode = params.initial_model\n n = params.robot_number\n # model.train()\n\n # horizon loop\n for t in range(params.time_horizon):\n model.eval()\n episode_length = 0\n while (memory.load < params.num_steps * params.batch_size * n):\n states = []\n actions = []\n rewards = []\n values = []\n logprobs = []\n av_reward = 0\n cum_reward = 0\n cum_done = 0\n xdis = []\n for i in range(n):\n xdis.append(0)\n hx = torch.zeros((n, params.gruhiddensize)).unsqueeze(0).to(device)\n\n # n steps loops\n for step in range(params.num_steps):\n state = Variable(torch.Tensor(state))\n episode_length += 1\n state = state.reshape(n, 60)\n shared_obs_stats.observes(state)\n state = shared_obs_stats.normalize(state).unsqueeze(0).to(device)\n states.append(state)\n # print(hx.shape)\n # print(state.shape)\n model = model.to(device)\n with torch.no_grad():\n mu, sigma, v, hx = model.single_forward(state, hx)\n # h.append(hx)\n # c.append(cx)\n # print(v.shape)\n action = (mu + torch.exp(sigma) * Variable(torch.randn(mu.size()).to(device)))\n actions.append(action)\n log_prob = -0.5 * ((action - mu) / torch.exp(sigma)).pow(2) - (0.5 * math.log(2 * math.pi)) - sigma\n log_prob = log_prob.sum(-1, keepdim=True)\n logprobs.append(log_prob)\n values.append(v)\n action = action.reshape(1, n * 16)\n env_action = torch.tanh(action).data.squeeze().cpu().numpy()\n state, reward, done, _ = env.step(env_action)\n # if step % 128 == 0:\n # for i in range(n):\n # xdis[i] = state[60 * i + 48] - xdis[i]\n # reward[i] += xdis[i] * 80\n cum_reward += reward\n # reward = max(min(reward, 1), -1)\n rewards.append(reward)\n\n if done:\n episode += 1\n cum_done += n\n av_reward += cum_reward\n cum_reward = 0\n episode_length = 0\n with torch.no_grad():\n state = Variable(torch.Tensor(state))\n state = state.reshape(n, 60)\n shared_obs_stats.observes(state)\n state = shared_obs_stats.normalize(state).unsqueeze(0).to(device)\n _, _, v, _ = model.single_forward(state, hx)\n values.append(v)\n state = env.reset()\n break\n\n # compute returns and GAE(lambda) advantages:\n for j in range(n):\n returns = []\n advantages = []\n st = []\n ac = []\n lo = []\n R = torch.zeros(1, 1)\n A = Variable(torch.zeros(1, 1)).to(device)\n for i in reversed(range(len(rewards))):\n td = rewards[i][j] + params.gamma * values[i + 1].data[0, j] - values[i].data[0, j]\n A = float(td) + params.gamma * params.gae_param * A\n advantages.insert(0, A)\n R = A + values[i][0][j]\n returns.insert(0, R)\n st.insert(0, states[i][0][j].unsqueeze(0).unsqueeze(0))\n ac.insert(0, actions[i][0][j].unsqueeze(0).unsqueeze(0))\n lo.insert(0, logprobs[i][0][j].unsqueeze(0).unsqueeze(0))\n # print(advantages[0].shape) torch.Size([1, 1])\n memory.push([st, ac, returns, advantages, lo])\n\n model.train()\n # print(memory.load)\n # epochs\n batch_states, batch_actions, batch_returns, batch_advantages, batch_logprobs = memory.pull()\n batch_advantages = batch_advantages.unsqueeze(-1)\n batch_returns = batch_returns.unsqueeze(-1)\n # print(batch_states.shape)torch.Size([1024, 4, 60])\n for k in range(params.num_epoch):\n # new probas\n hx = torch.zeros((memory.batchsize, params.gruhiddensize)).unsqueeze(0).to(device)\n\n Mu, Sigma, V_pred = model(batch_states, hx) # size: length * batch * sigma_size\n # Sigma = Sigma.expand_as(Mu)\n\n log_probs = -0.5 * ((batch_actions - Mu) / torch.exp(Sigma)).pow(2) - 0.5 * math.log(2 * math.pi) - Sigma\n log_probs = log_probs.sum(-1, keepdim=True)\n dist_entropy = 0.5 + 0.5 * math.log(2 * math.pi) + Sigma\n dist_entropy = dist_entropy.mean().sum(-1, keepdim=True)\n\n # ratio\n ratio = torch.exp(log_probs - batch_logprobs)\n\n # clip loss\n # print(ratio.shape)\n # print(batch_advantages.shape)\n\n surr1 = ratio * batch_advantages.expand_as(ratio) # surrogate from conservative policy iteration\n surr2 = ratio.clamp(1 - params.clip, 1 + params.clip) * batch_advantages.expand_as(ratio)\n loss_clip = - torch.mean(torch.min(surr1, surr2))\n\n # value loss\n loss_value = (V_pred - batch_returns).pow(2).mean()\n\n # entropy\n loss_ent = - params.ent_coeff * dist_entropy\n\n # gradient descent step\n total_loss = (loss_clip + loss_value + loss_ent)\n\n # loss = torch.square(log_probs - torch.full_like(batch_logprobs, 0)).mean() + torch.square(\n # V_pred - torch.full_like(batch_returns, 1.0)).mean()\n\n # print(loss)\n optimizer.zero_grad()\n total_loss.backward(retain_graph=params.iso_sig)\n # loss.backward()\n # nn.utils.clip_grad_norm(model.parameters(), params.max_grad_norm)\n optimizer.step()\n\n # finish, print:\n av_reward = sum(av_reward)\n print('episode', episode, 'av_reward', av_reward / float(cum_done), 'total loss', total_loss)\n if episode % params.save_interval == 0:\n save_checkpoint(params.save_path, episode, model, optimizer, shared_obs_stats)\n f = open(params.save_path + \".txt\", \"a\")\n f.write(\"%f %f\\n\" % (av_reward / float(cum_done), total_loss))\n f.close()\n memory.clear()\n\n\ndef mkdir(base, name):\n path = os.path.join(base, name)\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n\n\ndef readtxt(name):\n mat = np.loadtxt(name, dtype='f', delimiter=' ')\n return mat\n", "sub_path": "script/Training.py", "file_name": "Training.py", "file_ext": "py", "file_size_in_byte": 8078, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.cat", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 91, "usage_type": "call"}, {"api_name": "math.log", "line_number": 91, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.tanh", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 157, "usage_type": "call"}, {"api_name": "math.log", "line_number": 157, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 157, "usage_type": "attribute"}, {"api_name": "math.log", "line_number": 159, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 159, "usage_type": "attribute"}, {"api_name": "torch.exp", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.min", "line_number": 171, "usage_type": "call"}, {"api_name": "ACNet.save_checkpoint", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 204, "usage_type": "call"}, {"api_name": "os.path", "line_number": 204, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path", "line_number": 205, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 211, "usage_type": "call"}]} +{"seq_id": "333741794", "text": "from django.conf.urls import patterns, url, include\nfrom django.contrib import admin\nfrom views import archive, year, month, post\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^/(?P[\\d]{4})/(?P[\\d]{2})/(?P[-\\w]+)\\.html$', post, name='blog_post'),\n url(r'^/(?P[\\d]{4})/(?P[\\d]{2})\\.html$', month, name='blog_month'),\n url(r'^/(?P[\\d]{4})\\.html$', year, name='blog_year'),\n url(r'^\\.html$', archive, name='blog'),\n)", "sub_path": "blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 473, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 4, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 4, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "views.post", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "views.month", "line_number": 8, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "views.year", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "views.archive", "line_number": 10, "usage_type": "argument"}]} +{"seq_id": "653910675", "text": "from flask import render_template\nfrom app import app\n@app.route('/')\n@app.route('/home')\ndef home():\n\treturn render_template('home.html')\n@app.route('/the_house')\ndef our_house():\n\tusers = [\n\t\t{\n\t\t'name': 'Brendan',\n\t\t'task': 'dishes'\n\t\t},\n\t\t{\n\t\t'name':'Brent',\n\t\t'task': 'garbage'\n\t\t},\n\t\t{\n\t\t'name': 'Nick',\n\t\t'task':'mopping'\n\t\t}\n\n\t]\n\treturn render_template('our_house.html',\n\t\tusers = users)", "sub_path": "app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 395, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.render_template", "line_number": 6, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 3, "usage_type": "call"}, {"api_name": "app.app", "line_number": 3, "usage_type": "name"}, {"api_name": "app.app.route", "line_number": 4, "usage_type": "call"}, {"api_name": "app.app", "line_number": 4, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 24, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 7, "usage_type": "call"}, {"api_name": "app.app", "line_number": 7, "usage_type": "name"}]} +{"seq_id": "187859752", "text": "from typing import List\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n dp = [False for i in range(len(s)+1)]\n dp[0] = True\n for i in range(len(s)):\n if dp[i]:\n for j in wordDict:\n if s[i:i+len(j)] == j:\n dp[i+len(j)] = True\n return dp[len(s)]\n\n\nx = Solution()\na = x.wordBreak(\"applepenapple\",[\"apple\", \"pen\"])\nprint(a)", "sub_path": "leetcode139.py", "file_name": "leetcode139.py", "file_ext": "py", "file_size_in_byte": 446, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.List", "line_number": 3, "usage_type": "name"}]} +{"seq_id": "439551605", "text": "import matplotlib.pyplot as plt\nimport math\n\n# show multi-images in a window\ndef showImgN(imgs, titles = None):\n\t# grids definition\n\tN = int(len(imgs))\n\th = int(math.sqrt(N) + 0.5)\n\tw = h + (1 if h * h < N else 0)\n\tfor i in range(N):\n\t\timg = imgs[i]\n\t\ttitle = titles[i] if titles != None else 'img ' + str(i + 1)\n\t\t# show images\n\t\tplt.subplot(h, w, i + 1)\n\t\tplt.imshow(img)\n\t\tplt.title(title)\n\t\tplt.xticks([])\n\t\tplt.yticks([])\n\tplt.show()\n\n# Is n equal to 2^(integer)\ndef exp2int(n):\n\treturn (n & (n - 1)) == 0\n# get 2^(integer) that is >= n\ndef geExp2(n):\n\ti = math.log2(n)\n\ti = math.ceil(i)\n\treturn int(pow(2, i))", "sub_path": "code/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 615, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "math.sqrt", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "math.log2", "line_number": 26, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "537949907", "text": "from add.UserForm import UserForm\r\nfrom django.shortcuts import render\r\nfrom django.contrib import messages\r\nfrom django.core.validators import validate_email\r\n\r\nfrom list.models import Users\r\n\r\n\r\ndef is_email_valid(email):\r\n try:\r\n validate_email(email)\r\n return True\r\n finally:\r\n return False\r\n\r\n\r\ndef index(request):\r\n\r\n if request.method == \"POST\":\r\n\r\n user_form = UserForm(request.POST)\r\n\r\n if user_form.is_valid():\r\n name = user_form.cleaned_data['name']\r\n email = user_form.cleaned_data['email']\r\n\r\n if len(name) > 2:\r\n if is_email_valid(email):\r\n user = Users(\r\n name=name,\r\n email=email\r\n )\r\n user.save()\r\n messages.info(request, 'User added successfully!')\r\n\r\n return render(request, 'menu/index.html')\r\n\r\n else:\r\n messages.info(request, 'Please insert a valid email')\r\n else:\r\n messages.info(request, 'Name needs at least 3 characters')\r\n else:\r\n messages.info(request, 'Please fill all the text fields!')\r\n\r\n return render(request, 'add/index.html')\r\n", "sub_path": "DjangoApp/add/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1277, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.core.validators.validate_email", "line_number": 11, "usage_type": "call"}, {"api_name": "add.UserForm.UserForm", "line_number": 21, "usage_type": "call"}, {"api_name": "list.models.Users", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 34, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 34, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 36, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 39, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 39, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 41, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 41, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 43, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 43, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "215329466", "text": "\"\"\"\r\nEditor tool.\r\n\r\nA simple python code editor and integrated debugger with just enough features.\r\n\"\"\"\r\n#---logging---------------------------------------------------------------------\r\nimport logging\r\nlog = logging.getLogger(__name__)\r\n#log.setLevel(logging.DEBUG)\r\n\r\n#---Imports---------------------------------------------------------------------\r\nimport wx\r\nimport wx.aui as aui\r\n\r\nfrom ptk_lib.message_bus.mb_node import MBLocalNode\r\nfrom ptk_lib.message_bus import mb_protocol\r\nfrom ptk_lib.tool_manager import Tool\r\nfrom ptk_lib.engine import eng_messages, eng_misc\r\n\r\n#other tool imports\r\nfrom ptk_lib.core_tools.fileio import Importer, DoFileDialog\r\nfrom ptk_lib.core_tools.console import console_messages\r\n\r\n#editor imports\r\nfrom editor_frame import EditorFrame\r\nimport editor_messages\r\nimport editor_icons\r\n\r\n#debugger imports\r\nfrom dbg_controls import DebugConsoleTools, BreakPointListPanel\r\n\r\n#---the tools class-------------------------------------------------------------\r\nclass Editor(Tool):\r\n name = 'Editor'\r\n descrip = 'Core tool providing a simple python code editor and integrated debugger with just enough features'\r\n author = 'T.Charrett'\r\n requires = ['TaskIcon','Console','FileIO'] \r\n core = True \r\n icon = editor_icons.editor32\r\n\r\n def __init__(self):\r\n Tool.__init__(self)\r\n log.info('Initialising tool')\r\n\r\n #create a message bus node for this tool\r\n self.msg_node = MBLocalNode('Editor')\r\n self.msg_node.connect(self.msg_bus)\r\n\r\n #-----------------------------------------------------------------------\r\n #subscribe to application messages\r\n # - this is done first to ensure the debugger interace is always\r\n # updated before other subscribers are processed (the toolbars in\r\n # this tool then any other tools loaded after the editor).\r\n #-----------------------------------------------------------------------\r\n self.msg_node.subscribe('App.Init',self.msg_app_init)\r\n self.msg_node.subscribe('App.ExitCheck',self.msg_app_exitcheck)\r\n self.msg_node.subscribe('App.Exit',self.msg_app_exit)\r\n\r\n #Add the edit command and debugger breakpoints when a new engine starts.\r\n self.msg_node.subscribe(mb_protocol.SYS_NODE_CONNECT+'.Engine',\r\n self.msg_engine_connect) \r\n\r\n self.msg_node.subscribe( console_messages.CONSOLE_SWITCHED,\r\n self.msg_console_switched)\r\n \r\n #on debug messages - update the editor breakpoint and paused markers\r\n self.msg_node.subscribe( eng_messages.ENGINE_STATE_DONE, \r\n self.msg_eng_done)\r\n \r\n self.msg_node.subscribe( eng_messages.ENGINE_DEBUG_TOGGLED,\r\n self.msg_debug_toggled)\r\n\r\n self.msg_node.subscribe( eng_messages.ENGINE_DEBUG_PAUSED, \r\n self.msg_debug_paused)\r\n \r\n self.msg_node.subscribe( eng_messages.ENGINE_DEBUG_RESUMED, \r\n self.msg_debug_resumed)\r\n\r\n\r\n #-----------------------------------------------------------------------\r\n #Register message handlers\r\n #-----------------------------------------------------------------------\r\n self.msg_node.set_handler(editor_messages.EDITOR_NEW, \r\n self.msg_new) #open the a new file\r\n self.msg_node.set_handler(editor_messages.EDITOR_OPEN, \r\n self.msg_open) #open the file(s)\r\n self.msg_node.set_handler(editor_messages.EDITOR_SHOW, \r\n self.msg_show) #show the editor\r\n self.msg_node.set_handler(editor_messages.EDITOR_HIDE, \r\n self.msg_hide) #hide the editor\r\n\r\n #-----------------------------------------------------------------------\r\n # Internals\r\n #-----------------------------------------------------------------------\r\n #break points (set in all engines)\r\n self.bpoints = eng_misc.DictList()\r\n self.bp_counter = 0\r\n\r\n #-----------------------------------------------------------------------\r\n # GUI components\r\n #-----------------------------------------------------------------------\r\n #create the editor frame\r\n self.frame = EditorFrame(self)\r\n self.notebook = self.frame.notebook\r\n\r\n #Add taskbar menu item\r\n taskicon = self.toolmgr.get_tool('TaskIcon')\r\n bmp = editor_icons.editor16.GetBitmap()\r\n taskicon.add_menu_item(wx.NewId(), 'Open the Editor',\r\n 'Open the Editor window', self.on_show, bmp)\r\n\r\n #Add menu item to console window\r\n console = self.toolmgr.get_tool('Console')\r\n bmp = editor_icons.editor16.GetBitmap()\r\n console.add_menu_item('tools', wx.NewId(), 'Editor',\r\n 'Open the Editor window', self.on_show, bmp)\r\n\r\n #Add the debugger breakpoints pane to the console\r\n ctrl = BreakPointListPanel(console.frame, self)\r\n pane = aui.AuiPaneInfo()\r\n name='Debugger Breakpoints'\r\n pane.Name(name) #id name\r\n pane.Caption('Debugger Breakpoints')\r\n pane.CloseButton(True) #close button\r\n pane.MaximizeButton(True)\r\n pane.DestroyOnClose(False)\r\n pane.Floatable(True)\r\n pane.Resizable(True)\r\n pane.MinSize( (100,200))\r\n pane.MaxSize( (-1,-1))\r\n pane.Right()\r\n pane.Dock()\r\n pane.Hide()\r\n\r\n console.frame.auimgr.AddPane(ctrl, pane) #add the pane\r\n self.console_pane=console.frame.auimgr.GetPane(name) #store a reference\r\n\r\n #Add a menu item to show/hide the debugger pane\r\n \r\n\r\n\r\n #Add a debugger toolbar to the console frame\r\n self.debugtools = DebugConsoleTools(console.frame, self)\r\n pane = (aui.AuiPaneInfo().Name('Debuger toolbar')\r\n .Caption('Debuger toolbar').ToolbarPane().CloseButton(True)\r\n .CaptionVisible(False)\r\n .DestroyOnClose(False).Top().Row(1).Position(1)\r\n .LeftDockable(False).RightDockable(False))\r\n console.frame.AddToolbar(self.debugtools,'Debuger toolbar',pane,\r\n helpstring = 'Show/hide the Debugger toolbar') \r\n\r\n #-----------------------------------------------------------------------\r\n #register file importer\r\n #-----------------------------------------------------------------------\r\n fileio = self.toolmgr.get_tool('FileIO')\r\n self.importer = EditorImporter(self.frame)\r\n fileio.register_importer( self.importer )\r\n\r\n log.info('Done Initialising tool')\r\n\r\n #---Frame Interfaces--------------------------------------------------------\r\n def show_editor(self):\r\n \"\"\"\r\n Show the Editor frame\r\n \"\"\"\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n def hide_editor(self):\r\n \"\"\"\r\n Hide the Editor frame\r\n \"\"\"\r\n self.frame.Hide()\r\n\r\n def add_menu_item(self, menu, id, string, helpstring, evthndlr, bitmap=None,\r\n pos=None):\r\n \"\"\"\r\n Add a menu item to the menu.\r\n menu - string description of menu ('Tools', 'File'. 'Edit' etc)\r\n string - string to display\r\n helpstring - help string for item\r\n evthndlr - wx event handler callable\r\n bitmap - bitmap to use / None for no bitmap\r\n pos - Position in menu, inserted here if specified.\r\n \"\"\"\r\n menu = self.frame.GetMenu(menu)\r\n item = wx.MenuItem(menu, id, string,helpstring)\r\n self.frame.Bind(wx.EVT_MENU, evthndlr, id=id)\r\n if bitmap is not None:\r\n item.SetBitmap(bitmap)\r\n if pos is None:\r\n pos = menu.GetMenuItemCount()\r\n menu.InsertItem(pos,item)\r\n \r\n def edit_file(self, file, lineno=0):\r\n \"\"\"\r\n Open the file in the editor and scroll to the line given\r\n \"\"\"\r\n self.frame.notebook.OpenFile(file)\r\n #TODO: scroll to line\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n #---debugger interfaces-----------------------------------------------------\r\n def set_breakpoint(self, filename,lineno,\r\n condition=None,ignore_count=None,trigger_count=None):\r\n \"\"\"\r\n Set a breakpoint for all engines.\r\n Returns the new breakpoint id (used to edit/clear breakpoints).\r\n \"\"\"\r\n #create new id.\r\n id = self.bp_counter\r\n self.bp_counter+=1 \r\n\r\n #store in DictList\r\n bpdata = { 'id':id,'filename':filename, 'lineno':lineno,\r\n 'condition':condition, 'ignore_count':ignore_count,\r\n 'trigger_count':trigger_count }\r\n self.bpoints.append(bpdata)\r\n \r\n #set the breakpoint in each engine.\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines(active=True)\r\n for eng in engines:\r\n eng.debugger.set_breakpoint(bpdata)\r\n\r\n #add a breakpoint marker to the editor page\r\n page = self.frame.notebook.GetPageFromPath(filename)\r\n if page is not None:\r\n page.AddBreakpointMarker( id, lineno )\r\n\r\n #publish a breakpoint set message\r\n self.msg_node.publish_msg( editor_messages.EDITOR_BREAKPOINT_SET,\r\n (bpdata,) ) \r\n return id \r\n\r\n def clear_breakpoint(self, id):\r\n \"\"\"\r\n Clear the debugger breakpoint with the id given for all engines.\r\n \"\"\"\r\n bps = self.bpoints.filter( ('id',),(id,) )\r\n if len(bps)==0:\r\n raise Exception('No breakpoint with id '+str(id))\r\n bpdict = bps[0]\r\n\r\n #clear the breakpoint in each engine\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines(active=True)\r\n for eng in engines:\r\n eng.debugger.clear_breakpoint(id)\r\n \r\n #remove from internal breakpoint list\r\n self.bpoints.remove(bpdict)\r\n\r\n #clear any markers from the editor pages\r\n page = self.frame.notebook.GetPageFromPath( bpdict['filename'] )\r\n if page is not None:\r\n page.DeleteBreakpointMarker( id )\r\n\r\n #publish a breakpoint cleared message\r\n self.msg_node.publish_msg( editor_messages.EDITOR_BREAKPOINT_CLEARED,\r\n (id,) ) \r\n\r\n def clear_breakpoints(self, filename, lineno=None):\r\n \"\"\"\r\n Clear the debugger breakpoints in the filename given. If the optional \r\n lineno is given clear breakpoints at this line in the file given.\r\n \"\"\" \r\n #get breakpoints\r\n bps = self.get_breakpoints(filename, lineno)\r\n\r\n #no breakpoints found?\r\n if bps==[]:\r\n return\r\n \r\n bpids = []\r\n for bp in bps:\r\n bpids.append(bp['id'])\r\n \r\n #clear the breakpoint in each engine\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines(active=True)\r\n for eng in engines:\r\n eng.debugger.clear_breakpoints(bpids)\r\n \r\n #remove from the internal breakpoint list and clear any markers in the\r\n #editor pages\r\n page = self.frame.notebook.GetPageFromPath( filename )\r\n for bp in bps:\r\n self.bpoints.remove(bp)\r\n if page is not None:\r\n page.DeleteBreakpointMarker( bp['id'] )\r\n\r\n #published a breakpoint cleared message\r\n self.msg_node.publish_msg( editor_messages.EDITOR_BREAKPOINT_CLEARED,\r\n bpids ) \r\n\r\n def clear_all_breakpoints(self):\r\n \"\"\"\r\n Clear all set breakpoints\r\n \"\"\"\r\n #clear all the breakpoints in each engine\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines()\r\n\r\n for eng in engines:\r\n res = self.msg_node.send_msg( eng.engine, \r\n eng_messages.ENG_DEBUG_CLEARBP,\r\n (None,), True )\r\n\r\n #clear the internal brealpoint list\r\n self.bpoints.clear()\r\n\r\n #clear any markers from the editor pages\r\n pages = self.frame.notebook.GetAllPages()\r\n for page in pages:\r\n page.DeleteAllBreakpointMarkers()\r\n\r\n #published a breakpoint cleared message\r\n self.msg_node.publish_msg( editor_messages.EDITOR_BREAKPOINT_CLEARED,\r\n (None,) ) \r\n\r\n def modify_breakpoint(self, id, **kwargs):\r\n \"\"\"\r\n Modify a breakpoint.\r\n\r\n Note: Only modify the keywords 'condition', 'trigger_count' or \r\n 'ignore_count'. 'filename' and 'lineno' can also be used if the \r\n file is not open in the editor (or by the editor page itself to move a \r\n breakpoint).\r\n\r\n e.g. modify_breakpoint( id=1, filename='test.py', lineno=23) will modify\r\n the breakpoint filename and lineno. To pass a dictionary of changes use \r\n **dict.\r\n \"\"\"\r\n bps = self.bpoints.filter( ('id',),(id,) )\r\n if len(bps)==0:\r\n raise Exception('No breakpoint with id '+str(id))\r\n bpdict = bps[0]\r\n\r\n #modify the breakpoint in each engine\r\n console = self.app.toolmgr.get_tool('Console')\r\n engines = console.get_all_engines()\r\n\r\n for eng in engines:\r\n res = self.msg_node.send_msg( eng.engine, \r\n eng_messages.ENG_DEBUG_EDITBP,\r\n (id, kwargs), True )\r\n\r\n #modify the breakpoint data dictionary.\r\n bpdict.update( kwargs )\r\n\r\n #modify any markers if the file is open in the editor\r\n page = self.frame.notebook.GetPageFromPath( bpdict['filename'] )\r\n if page is not None:\r\n page.DeleteBreakpointMarker( id )\r\n page.AddBreakpointMarker( id, bpdict['lineno'] )\r\n \r\n #published a breakpoint changed message\r\n self.msg_node.publish_msg( editor_messages.EDITOR_BREAKPOINT_CHANGED,\r\n (id,kwargs) ) \r\n\r\n def get_breakpoint(self, id):\r\n \"\"\"\r\n Get the breakpoint by id\r\n \"\"\"\r\n res = self.bpoints.filter( keys=('id',), values=( id,) )\r\n if res==[]:\r\n return None\r\n return res[0]\r\n\r\n def get_breakpoints(self, filename=None, lineno=None):\r\n \"\"\"\r\n Get the breakpoints currently set in the filename given if None return\r\n all breakpoints. If lineno is given return only breakpoints at this line\r\n in the file given.\r\n \"\"\"\r\n if filename is None:\r\n return self.bpoints.items()\r\n if lineno is None:\r\n return self.bpoints.filter( keys=('filename',),\r\n values=(filename,) )\r\n else:\r\n return self.bpoints.filter( keys=('filename','lineno'), \r\n values=(filename, lineno) )\r\n\r\n def get_breakpoint_files(self):\r\n \"\"\"\r\n Get a list of all files where breakpoints are set\r\n \"\"\"\r\n return self.bpoints.values(key='filename')\r\n\r\n #---Message handlers-------------------------------------------------------\r\n def msg_show(self,msg):\r\n \"\"\"\r\n Message handler for Editor.Show and wx.Event from menu\r\n \"\"\"\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n def msg_hide(self,msg):\r\n \"\"\"\r\n Message handler for Editor.Hide\r\n \"\"\"\r\n self.frame.Hide()\r\n\r\n def msg_new(self,msg):\r\n \"\"\"\r\n Message handler for Editor.New\r\n \"\"\"\r\n self.frame.notebook.New()\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n def msg_open(self,msg):\r\n \"\"\"\r\n Message handler for Editor.Open\r\n data=list of files to open in editor\r\n \"\"\"\r\n filepaths = msg.get_data()\r\n if filepaths is ():\r\n #Create the file open dialog.\r\n filepaths,index = DoFileDialog(self.frame, wildcard = \"Python source (*.py,*.pyw)|*.py;*.pyw|All files (*,*.*)|*.*;*\")\r\n if filepaths==None:\r\n return\r\n\r\n if (filepaths is not None) and (filepaths!=[]):\r\n #open the file requested\r\n for path in filepaths:\r\n self.frame.notebook.OpenFile(path)\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n def msg_app_init(self,msg):\r\n \"\"\"\r\n Listener for App.Init message\r\n Sent when application starts\r\n \"\"\"\r\n #load the main window layouts (in aui mixin class)\r\n self.frame.LoadLayouts()\r\n\r\n def msg_app_exitcheck(self,msg):\r\n \"\"\"\r\n Check its ok for the application to exit\r\n \"\"\"\r\n #check for unsaved files\r\n res= self.frame.notebook.CheckClose()\r\n if res is False:\r\n self.app.VetoExit()\r\n\r\n def msg_app_exit(self,msg):\r\n \"\"\"\r\n Listener for App.Exit message\r\n Save settings on application exit\r\n \"\"\"\r\n #save the main window layouts (in aui mixin class)\r\n self.frame.SaveLayouts()\r\n #save the recent files list\r\n cfg = self.app.GetConfig()\r\n cfg.SetPath(\"Editor//\")\r\n self.frame.filehistory.Save(cfg)\r\n cfg.Flush()\r\n\r\n def msg_engine_connect(self,msg):\r\n \"\"\"\r\n Engine manager - Engine.Started message handler\r\n \"\"\"\r\n log.debug('Adding edit() command to new engine')\r\n engname = msg.get_data()[0]\r\n\r\n #get the new engine interface\r\n app = wx.GetApp()\r\n console = app.toolmgr.get_tool('Console')\r\n eng = console.get_engine_console(engname)\r\n\r\n #When an engine is started add the edit() command\r\n eng.add_builtin(edit, 'edit')\r\n\r\n #add any set breakpoints to this engine's debugger\r\n for bpdata in self.bpoints:\r\n eng.debugger.set_breakpoint(bpdata)\r\n\r\n def msg_debug_toggled(self, msg):\r\n \"\"\"\r\n Debugger enabled/disabled message\r\n \"\"\"\r\n #update the bp markers in the editor pages\r\n pages = self.frame.notebook.GetAllPages()\r\n for page in pages:\r\n page.UpdateBreakpointSymbols()\r\n\r\n def msg_eng_done(self,msg):\r\n engname = msg.get_from()\r\n debug, profile = msg.data\r\n console = self.app.toolmgr.get_tool('Console')\r\n if console.is_engine_current(engname):\r\n #update any displayed paused markers\r\n self.frame.notebook.UpdatePauseMarkers()\r\n \r\n def msg_debug_paused(self,msg):\r\n engname = msg.get_from()\r\n paused_at, scope_list, active_scope, flags = msg.data\r\n console = self.app.toolmgr.get_tool('Console')\r\n if console.is_engine_current(engname):\r\n #update any displayed paused markers\r\n self.frame.notebook.UpdatePauseMarkers()\r\n\r\n def msg_debug_resumed(self,msg):\r\n engname = msg.get_from()\r\n console = self.app.toolmgr.get_tool('Console')\r\n if console.is_engine_current(engname):\r\n #update any displayed paused markers\r\n self.frame.notebook.UpdatePauseMarkers()\r\n\r\n def msg_console_switched(self, msg):\r\n \"\"\"\r\n The current active console switched.\r\n \"\"\"\r\n #update the paused/line number markers\r\n self.frame.notebook.UpdatePauseMarkers()\r\n\r\n #update the bp markers in the editor pages\r\n pages = self.frame.notebook.GetAllPages()\r\n for page in pages:\r\n page.UpdateBreakpointSymbols()\r\n\r\n #---other-------------------------------------------------------------------\r\n def on_show(self, event):\r\n \"\"\"wx event handler for the taskbar and console menu items\"\"\"\r\n self.frame.Show()\r\n self.frame.Raise()\r\n\r\n#-------------------------------------------------------------------------------\r\n# Engine magic command - this is added to engines __builtin__ module.\r\n#-------------------------------------------------------------------------------\r\ndef edit(filename):\r\n \"\"\"\r\n Edit a file in the ptk editor\r\n \"\"\"\r\n import os\r\n import __main__\r\n\r\n #check file exists\r\n filepath = os.path.abspath(filename)\r\n cwd = os.getcwd()\r\n #a full path given\r\n if os.path.exists(filepath) is False:\r\n raise Exception('File does not exist: '+filename)\r\n #send the editor message\r\n __main__._engine.send_msg('Editor','Open',(filepath,))\r\n\r\n#-------------------------------------------------------------------------------\r\n#FileIO importer\r\n#-------------------------------------------------------------------------------\r\nclass EditorImporter(Importer):\r\n def __init__(self,frame):\r\n Importer.__init__( self,'Open in the Editor', ['','.py','.pyw','.txt'],\r\n data=False,\r\n wildcards=[\"Python source (*.py,*.pyw)|*.py;*.pyw;\",\r\n \"Text file (*.txt)|*.txt\"],\r\n descrip = 'Open the file in the Editor' )\r\n self.frame = frame\r\n\r\n def __call__(self,filename):\r\n self.frame.OpenFile(filename)\r\n\r\n\r\n", "sub_path": "PythonToolkit-14.04.04/ptk_lib/core_tools/editor/editor_tool.py", "file_name": "editor_tool.py", "file_ext": "py", "file_size_in_byte": 21646, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "ptk_lib.tool_manager.Tool", "line_number": 33, "usage_type": "name"}, {"api_name": "editor_icons.editor32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "ptk_lib.tool_manager.Tool.__init__", "line_number": 42, "usage_type": "call"}, {"api_name": "ptk_lib.tool_manager.Tool", "line_number": 42, "usage_type": "name"}, {"api_name": "ptk_lib.message_bus.mb_node.MBLocalNode", "line_number": 46, "usage_type": "call"}, {"api_name": "ptk_lib.message_bus.mb_protocol.SYS_NODE_CONNECT", "line_number": 60, "usage_type": "attribute"}, {"api_name": "ptk_lib.message_bus.mb_protocol", "line_number": 60, "usage_type": "name"}, {"api_name": "ptk_lib.core_tools.console.console_messages.CONSOLE_SWITCHED", "line_number": 63, "usage_type": "attribute"}, {"api_name": "ptk_lib.core_tools.console.console_messages", "line_number": 63, "usage_type": "name"}, {"api_name": "ptk_lib.engine.eng_messages.ENGINE_STATE_DONE", "line_number": 67, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 67, "usage_type": "name"}, {"api_name": "ptk_lib.engine.eng_messages.ENGINE_DEBUG_TOGGLED", "line_number": 70, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 70, "usage_type": "name"}, {"api_name": "ptk_lib.engine.eng_messages.ENGINE_DEBUG_PAUSED", "line_number": 73, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 73, "usage_type": "name"}, {"api_name": "ptk_lib.engine.eng_messages.ENGINE_DEBUG_RESUMED", "line_number": 76, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 76, "usage_type": "name"}, {"api_name": "editor_messages.EDITOR_NEW", "line_number": 83, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_OPEN", "line_number": 85, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_SHOW", "line_number": 87, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_HIDE", "line_number": 89, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_misc.DictList", "line_number": 96, "usage_type": "call"}, {"api_name": "ptk_lib.engine.eng_misc", "line_number": 96, "usage_type": "name"}, {"api_name": "editor_frame.EditorFrame", "line_number": 103, "usage_type": "call"}, {"api_name": "editor_icons.editor16.GetBitmap", "line_number": 108, "usage_type": "call"}, {"api_name": "editor_icons.editor16", "line_number": 108, "usage_type": "attribute"}, {"api_name": "wx.NewId", "line_number": 109, "usage_type": "call"}, {"api_name": "editor_icons.editor16.GetBitmap", "line_number": 114, "usage_type": "call"}, {"api_name": "editor_icons.editor16", "line_number": 114, "usage_type": "attribute"}, {"api_name": "wx.NewId", "line_number": 115, "usage_type": "call"}, {"api_name": "dbg_controls.BreakPointListPanel", "line_number": 119, "usage_type": "call"}, {"api_name": "wx.aui.AuiPaneInfo", "line_number": 120, "usage_type": "call"}, {"api_name": "wx.aui", "line_number": 120, "usage_type": "name"}, {"api_name": "dbg_controls.DebugConsoleTools", "line_number": 143, "usage_type": "call"}, {"api_name": "wx.aui.AuiPaneInfo", "line_number": 144, "usage_type": "call"}, {"api_name": "wx.aui", "line_number": 144, "usage_type": "name"}, {"api_name": "wx.MenuItem", "line_number": 187, "usage_type": "call"}, {"api_name": "wx.EVT_MENU", "line_number": 188, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_BREAKPOINT_SET", "line_number": 233, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_BREAKPOINT_CLEARED", "line_number": 261, "usage_type": "attribute"}, {"api_name": "editor_messages.EDITOR_BREAKPOINT_CLEARED", "line_number": 295, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages.ENG_DEBUG_CLEARBP", "line_number": 308, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 308, "usage_type": "name"}, {"api_name": "editor_messages.EDITOR_BREAKPOINT_CLEARED", "line_number": 320, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages.ENG_DEBUG_EDITBP", "line_number": 347, "usage_type": "attribute"}, {"api_name": "ptk_lib.engine.eng_messages", "line_number": 347, "usage_type": "name"}, {"api_name": "editor_messages.EDITOR_BREAKPOINT_CHANGED", "line_number": 360, "usage_type": "attribute"}, {"api_name": "ptk_lib.core_tools.fileio.DoFileDialog", "line_number": 423, "usage_type": "call"}, {"api_name": "wx.GetApp", "line_number": 472, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 544, "usage_type": "call"}, {"api_name": "os.path", "line_number": 544, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 545, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 547, "usage_type": "call"}, {"api_name": "os.path", "line_number": 547, "usage_type": "attribute"}, {"api_name": "__main__._engine.send_msg", "line_number": 550, "usage_type": "call"}, {"api_name": "__main__._engine", "line_number": 550, "usage_type": "attribute"}, {"api_name": "ptk_lib.core_tools.fileio.Importer", "line_number": 555, "usage_type": "name"}, {"api_name": "ptk_lib.core_tools.fileio.Importer.__init__", "line_number": 557, "usage_type": "call"}, {"api_name": "ptk_lib.core_tools.fileio.Importer", "line_number": 557, "usage_type": "name"}]} +{"seq_id": "234752284", "text": "import numpy as np\nimport scipy.special\n\nimport matplotlib\nmatplotlib.use\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-talk')\n\nimport pandas as pd\n\nimport friction_functions as data\n\nexcel_file = pd.ExcelFile('data/friction_data.xlsx')\ndf = excel_file.parse('mean_std_noncontinuous')\n\ndf_soda = df[df['substrate'] == 'soda lime']\ndf_soda_srubber = df_soda[df_soda['sample_material'] == 'rubber_sheet']\ndf_soda_srubber_PAC = df_soda_srubber[df_soda_srubber['parylene_type']!= 'PAHT']\n\ndf_soda_srubber_PAHT = df_soda_srubber[df_soda_srubber['parylene_type'] == 'PAHT']\n\ndf_c = df[df['substrate'] == 'COP']\ndf_c_r = df_c[df_c['sample_material'] == 'rubber_sheet']\ndf_c_sr = df_c_r[df_c_r['sample_size'] == 'small']\ndf_c_sr_PAC = df_c_sr[df_c_sr['parylene_type']!= 'PAHT']\n\ndf_c_sr_PAHT = df_c_sr[df_c_sr['parylene_type'] == 'PAHT']\n\ndf_PAC_soda = df[df['substrate'] == 'soda lime 3.6 um PAC']\ndf_PAC_soda_srubber = df_PAC_soda[df_PAC_soda['sample_material'] == 'rubber_sheet']\ndf_PAC_soda_srubber_PAC = df_PAC_soda_srubber[df_PAC_soda_srubber['parylene_type'] != 'PAHT']\n\ndf_PAC_soda_srubber_PAHT = df_PAC_soda_srubber[df_PAC_soda_srubber['parylene_type'] == 'PAHT']\n\ndf_teflon = df[df['substrate'] == 'teflon']\ndf_teflon_srubber = df_teflon[df_teflon['sample_material'] == 'rubber_sheet']\ndf_teflon_srubber_PAC = df_teflon_srubber[df_teflon_srubber['parylene_type']!= 'PAHT']\n\ndf_teflon = df[df['substrate'] == 'teflon']\ndf_teflon_teflon = df_teflon[df_teflon['sample_material'] == 'teflon']\n\nplt.errorbar(df_soda_srubber_PAC['parylene_thickness'], df_soda_srubber_PAC['mean'], yerr = df_soda_srubber_PAC['std'], fmt='o', label = 'PA-C on gray rubber vs soda lime wafer', color = '#1f77b4ff')\nplt.errorbar(df_soda_srubber_PAHT['parylene_thickness'], df_soda_srubber_PAHT['mean'], yerr = df_soda_srubber_PAHT['std'], fmt='s', label = 'PA-HT on gray rubber vs soda lime wafer', color = '#1f77b4ff')\n\nplt.errorbar(df_PAC_soda_srubber_PAC['parylene_thickness'], df_PAC_soda_srubber_PAC['mean'], yerr = df_PAC_soda_srubber_PAC['std'], fmt='o', label = 'PA-C on gray rubber vs PA-C on soda lime wafer', color = '#ff7f0eff')\nplt.errorbar(df_PAC_soda_srubber_PAHT['parylene_thickness'], df_PAC_soda_srubber_PAHT['mean'], yerr = df_PAC_soda_srubber_PAHT['std'], fmt='s', label = 'PA-HT on gray rubber vs PA-C on soda lime wafer', color = '#ff7f0eff')\n\n#plt.errorbar(df_c_sr_PAC['parylene_thickness'], df_c_sr_PAC['mean'], yerr = df_c_sr_PAC['std'], fmt='o', label = 'PA-C on gray rubber vs COP', color ='#2ca02cff' )\n#plt.errorbar(df_c_sr_PAHT['parylene_thickness'], df_c_sr_PAHT['mean'], yerr = df_c_sr_PAHT['std'], fmt='s', label = 'PA-HT on gray rubber vs COP', color ='#2ca02cff' )\n\nplt.errorbar(df_teflon_srubber_PAC['parylene_thickness'], df_teflon_srubber_PAC['mean'], yerr = df_teflon_srubber_PAC['std'], fmt='o', label = 'PA-C on gray rubber vs teflon', color ='#d62728ff' )\n\n#plt.errorbar(df_teflon_teflon['parylene_thickness'], df_teflon_teflon['mean'], yerr = df_teflon_teflon['std'], fmt='s', label = 'teflont vs teflon', color ='#e2e200' )\n\n# df_g = df[df['substrate'] == 'glass']\n# df_g_r = df_g[df_g['sample_material'] == 'rubber_sheet']\n# df_g_r = df_g_r[df_g_r['sample_size'] == 'big']\n# df_g_r_PAC = df_g_r[df_g_r['parylene_type']!= 'PAHT']\n#\n# df_c = df[df['substrate'] == 'COP']\n# df_c_r = df_c[df_c['sample_material'] == 'rubber_sheet']\n# df_c_r = df_c_r[df_c_r['sample_size'] == 'big']\n# df_c_r_PAC = df_c_r[df_c_r['parylene_type']!= 'PAHT']\n\n\n# plt.errorbar(df_g_r_PAC['parylene_thickness'], df_g_r_PAC['mean'], yerr = df_g_r_PAC['std'], fmt='o', label = 'PA-C on rubber sheet vs glass', color = '#2ca02cff')\n# plt.errorbar(df_c_r_PAC['parylene_thickness'], df_c_r_PAC['mean'], yerr = df_c_r_PAC['std'], fmt='o', label = 'PA-C on rubber sheet vs COP', color = '#d62728ff')\n#\n\n\n\n\nplt.xlabel(r'Parylene Thickness ($\\mu$m)', fontsize=20)\nplt.ylabel('Kinetic Friction Coefficient', fontsize=20)\nplt.margins(0.2)\nplt.ylim(0, 2)\n#plt.ylim(0, 2.5)\nplt.xlim(-0.5, 20)\nplt.legend(loc = 'upper right' ,prop={'size':14})\nplt.tick_params(axis='both', which='major', labelsize=16)#\n#plt.title('friction coefficient vs thickness', fontsize=24)#\n\nplt.show()\n", "sub_path": "friction_vs_thickness_plot_srubber.py", "file_name": "friction_vs_thickness_plot_srubber.py", "file_ext": "py", "file_size_in_byte": 4166, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.use", "line_number": 5, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 7, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 7, "usage_type": "name"}, {"api_name": "pandas.ExcelFile", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.margins", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}]} +{"seq_id": "237151497", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nimport pymysql\nimport jieba.posseg as posseg\nimport jieba\nimport gensim\nimport logging\nfrom collections import defaultdict\nimport numpy as np\n\ndb2 = pymysql.connect(host = \"localhost\",\n user = \"zzh\",\n password = \"123456\",\n db = \"runoob\")\n\ncursor2 = db2.cursor()\n\ndef get_question(table_name, text):\n \"\"\"\n 加载模型获取答案\n :param table_name:\n :param text:\n :return:\n \"\"\"\n\n print(table_name)\n tfidf = gensim.models.TfidfModel.load(\"/home/zzh/PycharmProjects/django_test/HelloWorld/HelloWorld/MODELS/%s_tfidf\"%table_name)\n index = gensim.similarities.MatrixSimilarity.load(\"/home/zzh/PycharmProjects/django_test/HelloWorld/HelloWorld/MODELS/%s_index\"%table_name)\n dictionary = gensim.corpora.Dictionary.load(\"/home/zzh/PycharmProjects/django_test/HelloWorld/HelloWorld/MODELS/%s_dic\"%table_name)\n\n text = dictionary.doc2bow(jieba.lcut(text))\n\n text_tfidf = tfidf[text]\n sims = index[text_tfidf]\n\n postion = np.where(sims == max(sims))\n # print(postion)\n\n\n cursor2.execute(\"select * from %s where id = %s\"%(table_name, postion[0][0]+1))\n\n result = cursor2.fetchall()\n # print(result)\n return result\n\n\ndef search_form(request):\n return render_to_response('search_form.html')\n\ndef search(resquest):\n resquest.encodind = 'utf-8'\n if('q' in resquest.GET):\n print(resquest.GET['class_'], resquest.GET['q'])\n result = get_question(resquest.GET['class_'], resquest.GET['q'])\n message = result[0][2]\n # message = resquest.GET['class_']+ resquest.GET['q']\n else:\n message = \"你提交了空表单\"\n return HttpResponse(message)\n\nif __name__ == '__main__':\n result = get_question(\"ASP_NET\", \"MVC编程模式是什么样的\")\n print(result[0][2])", "sub_path": "HelloWorld/search.py", "file_name": "search.py", "file_ext": "py", "file_size_in_byte": 1911, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymysql.connect", "line_number": 11, "usage_type": "call"}, {"api_name": "gensim.models.TfidfModel.load", "line_number": 27, "usage_type": "call"}, {"api_name": "gensim.models", "line_number": 27, "usage_type": "attribute"}, {"api_name": "gensim.similarities.MatrixSimilarity.load", "line_number": 28, "usage_type": "call"}, {"api_name": "gensim.similarities", "line_number": 28, "usage_type": "attribute"}, {"api_name": "gensim.corpora.Dictionary.load", "line_number": 29, "usage_type": "call"}, {"api_name": "gensim.corpora", "line_number": 29, "usage_type": "attribute"}, {"api_name": "jieba.lcut", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 36, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 48, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 59, "usage_type": "call"}]} +{"seq_id": "245900470", "text": "import sys, os\r\nimport time, json, re\r\nfrom datetime import datetime\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options \r\nfrom bs4 import BeautifulSoup as bs\r\nfrom urllib.request import urlopen\r\n\r\n# Print iterations progress\r\ndef printProgressBar(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):\r\n \"\"\"\r\n Call in a loop to create terminal progress bar\r\n @params:\r\n iteration - Required : current iteration (Int)\r\n total - Required : total iterations (Int)\r\n prefix - Optional : prefix string (Str)\r\n suffix - Optional : suffix string (Str)\r\n decimals - Optional : positive number of decimals in percent complete (Int)\r\n bar_length - Optional : character length of bar (Int)\r\n \"\"\"\r\n str_format = \"{0:.\" + str(decimals) + \"f}\"\r\n percents = str_format.format(100 * (iteration / float(total)))\r\n filled_length = int(round(bar_length * iteration / float(total)))\r\n bar = '#' * filled_length + '-' * (bar_length - filled_length)\r\n\r\n sys.stdout.write('\\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)),\r\n\r\n if iteration >= total:\r\n sys.stdout.write('\\n')\r\n sys.stdout.flush()\r\n\r\nlocation = 'data/'\r\nusername = input('Username: ')\r\npost_count = input(\"Post count (write 'all' to scrape all posts): \")\r\nscroll_delay = int(input(\"Scroll delay (default 5 sec.): \"))\r\nsilent_mode = int(input('Silent mode? (1=EN, 0=DIS): '))\r\n\r\n# Locate chromedriver\r\nchrome_options = Options()\r\nif silent_mode == 1: \r\n\tchrome_options.add_argument('--headless')\r\n\t#prefs = {\"profile.managed_default_content_settings.images\": 2}\r\n\t#chrome_options.add_experimental_option(\"prefs\", prefs)\r\nbrowser = webdriver.Chrome('PATH_TO_CHROMEDRIVER/chromedriver.exe', options = chrome_options)\r\nbrowser.get('https://www.instagram.com/'+username+'/?hl=en')\r\n\r\nraw = False\r\nraw_data = []\r\nlinks = []\r\nposts = {}\r\nformat_json = {}\r\n\r\ntemporary_likes = 0\r\ntemporary_comments = 0\r\ntemporary_video_duration = 0\r\ntemporary_video_views = 0\r\n\r\n# Scrape basic data\r\npost_amount = browser.find_element_by_class_name(\"g47SY\").text\r\nfollowers = browser.find_element_by_css_selector(\"a[href*='followers'] span\").get_attribute('title')\r\nfollowing = browser.find_element_by_css_selector(\"a[href*='following'] span\").text\r\n\r\nif post_count == 'all':\r\n\tpost_count = int(post_amount.replace(',',''))\r\nelse:\r\n\tpost_count = int(post_count)\r\n\r\n# Calculate how many times it needs to scroll to get to bottom\r\nscroll_amount = round(post_count/(12))\r\nif scroll_amount < 1:\r\n\tscroll_amount = 1\r\n\r\nprint()\r\nprint('It will take about ' + str(round(((scroll_amount*scroll_delay) + (post_count*0.85))/60)) + ' minutes to run this program (' + str(post_count) + ' posts)')\r\nstart = time.time()\r\n\r\n# Add progress bar\r\nprint()\r\nprint('Collecting links')\r\nprintProgressBar(0, scroll_amount, prefix = 'Progress:', suffix = '', bar_length = 25)\r\nbarcount = 0\r\n# Get all links\r\nfailed_collect = 0\r\nfor i in range(scroll_amount):\r\n\tbarcount += 1\r\n\tprintProgressBar(barcount, scroll_amount, prefix = 'Progress:', suffix = '', bar_length = 25)\r\n\ttry:\r\n\t\tPagelength = browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n\t\ttime.sleep(scroll_delay)\r\n\t\tsource = browser.page_source\r\n\t\tdata=bs(source, 'html.parser')\r\n\t\tbody = data.find('body')\r\n\t\tscript = body.find('span')\r\n\t\tfor link in script.findAll('a'):\r\n\t\t\tif re.match(\"/p\", link.get('href')):\r\n\t\t\t\tlinks.append('https://www.instagram.com'+link.get('href'))\r\n\texcept:\r\n\t\tfailed_collect += 0\r\n\r\n# Remove duplicates\r\nlinks = list(set(links))\r\n\r\nprint()\r\nprint('Got ' + str(len(links)) + ' links')\r\n\r\n# Add progress bar\r\nprint()\r\nprint('Extracting data')\r\nprintProgressBar(0, len(links), prefix = 'Progress:', suffix = '', bar_length = 25)\r\nbarcount = 0\r\n# Extract info from links\r\nfailed_extract = 0\r\nfor i in range(len(links)):\r\n\tbarcount += 1\r\n\tprintProgressBar(barcount, len(links), prefix = 'Progress:', suffix = '', bar_length = 25)\r\n\ttry:\r\n\t\tpage = urlopen(links[i]).read()\r\n\t\tdata=bs(page, 'html.parser')\r\n\t\tbody = data.find('body')\r\n\t\tscript = body.find('script')\r\n\t\traw = script.text.strip().replace('window._sharedData =', '').replace(';', '')\r\n\t\tjson_data=json.loads(raw)\r\n\t\tposts =json_data['entry_data']['PostPage'][0]['graphql']\r\n\t\tposts= json.dumps(posts)\r\n\t\tposts = json.loads(posts)\r\n\r\n\t\tif raw == True:\r\n\t\t\traw_data.append(posts)\r\n\r\n\t\t# Check if any of the parameters can be found, if not, set them as None (null)\r\n\t\t# Timestamp\r\n\t\tif 'taken_at_timestamp' in str(posts):\r\n\t\t\ttimestamp = datetime.utcfromtimestamp(posts['shortcode_media']['taken_at_timestamp']).strftime('%Y-%m-%d')\r\n\t\t# Likes\r\n\t\tif 'edge_media_preview_like' in str(posts):\r\n\t\t\tlike_count = posts['shortcode_media']['edge_media_preview_like']['count']\r\n\t\t\t# This checks if there is arleady an entry for today, if there is, combine all of todays posts\r\n\t\t\tif str(timestamp) in str(format_json):\r\n\t\t\t\ttemporary_likes += like_count\r\n\t\t\t\tlike_count = temporary_likes\r\n\t\t\telse:\r\n\t\t\t\ttemporary_likes = 0\r\n\t\telse:\r\n\t\t\tlike_count = None\r\n\t\t# Comments\r\n\t\tif 'edge_media_preview_comment' in str(posts):\r\n\t\t\tcomment_count = int(posts['shortcode_media']['edge_media_preview_comment']['count'])\r\n\t\t\tif str(timestamp) in str(format_json):\r\n\t\t\t\ttemporary_comments += comment_count\r\n\t\t\t\tcomment_count = temporary_comments\r\n\t\t\telse:\r\n\t\t\t\ttemporary_comments = 0\r\n\t\telif 'edge_media_to_parent_comment' in str(posts):\r\n\t\t\tcomment_count = int(posts['shortcode_media']['edge_media_to_parent_comment']['count'])\r\n\t\t\tif str(timestamp) in str(format_json):\r\n\t\t\t\ttemporary_comments += comment_count\r\n\t\t\t\tcomment_count = temporary_comments\r\n\t\t\telse:\r\n\t\t\t\ttemporary_comments = 0\r\n\t\telif 'edge_media_to_comment' in str(posts):\r\n\t\t\tcomment_count = int(posts['shortcode_media']['edge_media_to_comment']['count'])\r\n\t\t\tif str(timestamp) in str(format_json):\r\n\t\t\t\ttemporary_comments += comment_count\r\n\t\t\t\tcomment_count = temporary_comments\r\n\t\t\telse:\r\n\t\t\t\ttemporary_comments = 0\r\n\t\telse:\r\n\t\t\tcomment_count = None\r\n\t\t# Video\r\n\t\tif 'video_duration' in str(posts):\r\n\t\t\tvideo_view_count = int(posts['shortcode_media']['video_view_count'])\r\n\t\t\tvideo_duration = int(posts['shortcode_media']['video_duration'])\r\n\t\t\tif str(timestamp) in str(format_json):\r\n\t\t\t\t# Views\r\n\t\t\t\ttemporary_video_views += video_view_count\r\n\t\t\t\tvideo_view_count = temporary_video_views\r\n\t\t\t\t# Duration\r\n\t\t\t\ttemporary_video_duration += video_duration\r\n\t\t\t\tvideo_duration = temporary_video_duration\r\n\t\t\telse:\r\n\t\t\t\ttemporary_video_views = 0\r\n\t\t\t\ttemporary_video_duration = 0\r\n\t\telse:\r\n\t\t\tvideo_view_count = None\r\n\t\t\tvideo_duration = None\r\n\r\n\r\n\t\t# Format JSON\r\n\t\tformat_json[str(timestamp)] = {\r\n\t\t\t'likes' : like_count,\r\n\t\t\t'comments' : comment_count,\r\n\t\t\t'video_view_count' : video_view_count,\r\n\t\t\t'video_duration' : video_duration\r\n\t\t}\r\n\r\n\texcept:\r\n\t\tfailed_extract += 1\r\n\t\tpass\r\n\r\nprint()\r\nprint(str(failed_collect) + ' links failed during collection')\r\nprint(str(failed_extract) + ' links failed during extraction')\r\nprint('Saving to ' + location + username + '_scrape.json')\r\n\r\n#Save to .json\r\ntry:\r\n # Create target Directory\r\n os.mkdir(location.replace('/',''))\r\n print(\"Directory \" , location.replace('/','') , \" created \") \r\nexcept FileExistsError:\r\n print(\"Directory \" , location.replace('/','') , \" already exists\")\r\ntry:\r\n\twith open(location + username + '_scrape.json', 'r') as read_data:\r\n\t\tread_data.close()\r\n\twith open(location + username + '_scrape.json', 'w+') as data_file:\t\r\n\t\tjson.dump(format_json, data_file, indent=3, separators=(',', ': '), sort_keys=True)\r\n\t\tdata_file.close()\r\n\tif raw == True:\r\n\t\twith open(location + username + '_raw.json', 'r') as read_data:\r\n\t\t\tread_data.close()\r\n\t\twith open(location + username + '_raw.json', 'w+') as data_file:\t\r\n\t\t\tjson.dump(raw_data, data_file, indent=3, separators=(',', ': '), sort_keys=True)\r\n\t\t\tdata_file.close()\r\nexcept:\r\n\twith open(location + username + '_scrape.json', 'w+') as data_file:\t\r\n\t\tjson.dump(format_json, data_file, indent=3, separators=(',', ': '), sort_keys=True)\r\n\t\tdata_file.close()\r\n\tif raw == True:\r\n\t\twith open(location + username + '_raw.json', 'w+') as data_file:\t\r\n\t\t\tjson.dump(raw_data, data_file, indent=3, separators=(',', ': '), sort_keys=True)\r\n\t\t\tdata_file.close()\r\n\r\nend = time.time()\r\n\r\nprint('Scrape duration: ' + str(datetime.utcfromtimestamp(end-start).strftime('%Hh %Mm')))\r\n", "sub_path": "scrape.py", "file_name": "scrape.py", "file_ext": "py", "file_size_in_byte": 8376, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.stdout.write", "line_number": 26, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 26, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 29, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 30, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 30, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 39, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 44, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 44, "usage_type": "name"}, {"api_name": "time.time", "line_number": 75, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 91, "usage_type": "call"}, {"api_name": "re.match", "line_number": 95, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 117, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 118, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 122, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 124, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 125, "usage_type": "call"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 133, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 133, "usage_type": "name"}, {"api_name": "os.mkdir", "line_number": 208, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 216, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 222, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 226, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 230, "usage_type": "call"}, {"api_name": "time.time", "line_number": 233, "usage_type": "call"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 235, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 235, "usage_type": "name"}]} +{"seq_id": "624437901", "text": "import serial\nimport time\nimport datetime\nimport csv\nimport http.client, urllib\nfrom Adafruit_BME280 import *\nimport subprocess\n\nport = serial.Serial('/dev/ttyS0', baudrate=9600, timeout=2.0)\n\ndef read_pm_line(_port):\n rv = b''\n while True:\n ch1 = _port.read()\n if ch1 == b'\\x42':\n ch2 = _port.read() \n if ch2 == b'\\x4d':\n rv += ch1 + ch2\n rv += _port.read(28)\n return rv\n\n# THINGSPEAK set up\n\ndef update_thingspeak(data1, data2, data3, data4, data5, data6, data7):\n params = urllib.parse.urlencode({\"field1\": data1, \"field2\": data2, \"field3\": data3, \n \"field4\": data4, \"field5\": data5, \"field6\": data6, \"field7\": data7,\n 'key':'JDHQKRAO83EPRZ5K'}) # Put your write key here.\n headers = {\"Content-typZZe\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\"}\n conn = http.client.HTTPConnection(\"api.thingspeak.com:80\")\n try:\n conn.request(\"POST\", \"/update\", params, headers)\n response = conn.getresponse()\n# print(response.status, response.reason)\n data = response.read()\n conn.close()\n except:\n pass\n # error handler if needed\n\n# End of THINGSPEAK\n\n# Needed to open the correct outputfile for the 1st time.\n\nold_date = \"-1\"\n\n# Sleep 30 second for the PM sensor to heat up.\n\ntime.sleep(30)\n\n# We collect data every 1 second, but THINGSPEAK can only take 15s data without\n# fancy round-robin writing to several channels. So, we only write the 15th \n# iteration to THINGSPAK. All data are written to the output file.\n\niter = 0\n\nwhile True:\n iter += 1\n try:\n\n# Read the PMS7003.\n rcv = read_pm_line(port)\n\n# Read the BMP280.\n sensor = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8)\n\n degrees = sensor.read_temperature()\n pascals = sensor.read_pressure()\n hectopascals = pascals / 100\n humidity = sensor.read_humidity()\n\n# Set up output files\n time_now = str.split(time.ctime())\n if (time_now[2] != old_date):\n try:\n myfile.close()\n except:\n pass\n outfile = \"/home/pi/UCD_AQ_UAV/UCD_1-\" + time_now[1]+time_now[2]+time_now[4]+\".txt\"\n myfile = open(outfile, \"a\")\n wr = csv.writer(myfile)\n old_date = time_now[2]\n\n# Pretty date/time string\n dtstr = time_now[4] + \" \" + time_now[0] + \" \" + time_now[1] +\\\n \" \" + time_now[2] + \" \" + time_now[3]\n# print(dtstr)\n\n# List of values to be written to the csv file\n res = {'timestamp': datetime.datetime.now(),\n 'apm10': rcv[4] * 256 + rcv[5],\n 'apm25': rcv[6] * 256 + rcv[7],\n 'apm100': rcv[8] * 256 + rcv[9],\n 'pm10': rcv[10] * 256 + rcv[11],\n 'pm25': rcv[12] * 256 + rcv[13],\n 'pm100': rcv[14] * 256 + rcv[15],\n 'gt03um': rcv[16] * 256 + rcv[17],\n 'gt05um': rcv[18] * 256 + rcv[19],\n 'gt10um': rcv[20] * 256 + rcv[21],\n 'gt25um': rcv[22] * 256 + rcv[23],\n 'gt50um': rcv[24] * 256 + rcv[25],\n 'gt100um': rcv[26] * 256 + rcv[27]\n }\n\n# Measure core temperature of the RPi3B+\n\n proc = subprocess.Popen(\"/opt/vc/bin/vcgencmd measure_temp\", stdout=subprocess.PIPE, shell=True)\n (out, err) = proc.communicate()\n core_T = str(str(out).split(\"=\")[1]).split(\"'\")[0]\n\n mylist = [dtstr,\n res['apm10'], res['apm25'], res['apm100'],\n res['pm10'], res['apm25'], res['pm100'],\n res['gt03um'], res['gt05um'], res['gt10um'],\n res['gt25um'], res['gt50um'], res['gt100um'],\n degrees, hectopascals, humidity, core_T]\n wr.writerow(mylist)\n\n# Update THINGSPEAK\n\n if (iter == 15):\n update_thingspeak(res['pm10'], res['apm25'], res['pm100'],\n degrees, hectopascals, humidity, core_T) \n iter = 0\n\n#Sleep 0.5 seconds so that time stamps are not identical for two consecutive records. \n\n time.sleep(0.5)\n\n except KeyboardInterrupt:\n break\n", "sub_path": "pms7003bme280pi.py3", "file_name": "pms7003bme280pi.py3", "file_ext": "py3", "file_size_in_byte": 4307, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "serial.Serial", "line_number": 9, "usage_type": "call"}, {"api_name": "urllib.parse.urlencode", "line_number": 25, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 25, "usage_type": "attribute"}, {"api_name": "http.client.client.HTTPConnection", "line_number": 29, "usage_type": "call"}, {"api_name": "http.client.client", "line_number": 29, "usage_type": "attribute"}, {"api_name": "http.client", "line_number": 29, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 48, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 72, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 89, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 89, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 106, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 106, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 127, "usage_type": "call"}]} +{"seq_id": "208664830", "text": "import argparse\nfrom Crypto.Cipher import AES\nimport binascii\nimport difflib\n\ndef getFlags():\n #parse command line args\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-k\", dest = 'keyFile', help=\"Enter key file\", required = True)\n parser.add_argument(\"-m\", dest = 'msgFile', help=\"Enter message file\", required = True)\n parser.add_argument(\"-t\", dest = 'tagFile', help= \"Enter tag file\", required=True)\n args = parser.parse_args()\n return args\n\ndef readTag(tagFile):\n t = open(tagFile, 'rb')\n tag = \"\"\n while True:\n string = t.readline()\n if string == \"\":\n break\n tag += string\n t.close()\n return tag\n\ndef readKey(keyFile):\n key = open(keyFile, 'rb')\n validKey = key.readline().strip()\n key.close()\n return validKey\n\ndef readInput(msgFile):\n i = open(msgFile, 'r')\n m = \"\"\n while True:\n string = i.readline()\n if string == \"\":\n break\n m += string\n m = m.strip()\n i.close()\n return m\n\n#Pads the plaintext\ndef pad(message):\n if len(message) > 16:\n if len(message) % 16 != 0:\n message += \"0\" * (16 - (len(message) % 16))\n elif len(message) < 16:\n message += \"0\" * (16 - len(message))\n return message\n\n#XOR function\ndef xor(blocks, key32):\n message = []\n cipher = AES.new(key32, AES.MODE_ECB)\n priorBlock = blocks[0]\n message = \"\"\n for currentBlock in blocks[1:]:\n ciphertext = cipher.encrypt(str(priorBlock))\n text = \"\"\n text += \"\".join(chr(ord(a)^ord(b)) for a,b in zip(currentBlock, ciphertext))\n priorBlock = text\n message += text\n return message\n\ndef blockify(plaintext):\n #Separates the plaintext into blocks of 16 bytes\n x = 0\n blocks = []\n length = len(plaintext)\n while(len(str(length)) < 16):\n length = \"0\" + str(length)\n blocks.append(length)\n check = plaintext[:]\n while len(check) > 0:\n slicelen = min(len(plaintext), 16)\n blocks.append(check[0:slicelen])\n check = check[slicelen:]\n x += 1\n return blocks\n\ndef verify(key, message, tag):\n message = pad(str(message))\n blocks = blockify(message)\n compMsg = xor(blocks, key)\n if tag == compMsg:\n return 1\n else:\n return 0\n\ndef main():\n args = getFlags()\n key = readKey(args.keyFile)\n tag = readTag(args.tagFile)\n message = readInput(args.msgFile)\n validity = verify(key, message, tag)\n if validity == 1:\n print(\"True\")\n return 1\n else:\n print(\"False\")\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "cbcmac-validate.py", "file_name": "cbcmac-validate.py", "file_ext": "py", "file_size_in_byte": 2626, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "call"}, {"api_name": "Crypto.Cipher.AES.new", "line_number": 56, "usage_type": "call"}, {"api_name": "Crypto.Cipher.AES", "line_number": 56, "usage_type": "name"}, {"api_name": "Crypto.Cipher.AES.MODE_ECB", "line_number": 56, "usage_type": "attribute"}]} +{"seq_id": "248273076", "text": "'''\nProvides access to the Twitter REST API.\n\nAll requests are handled by a TwitterRequester object. Each of the public\nmethods of that class returns a Deferred that is fired with the body of the\nrequest response, or errback'd if the connection fails for some reason.\n\nThe RequesterError exception is used to indicate error conditions from this\nmodule. All exceptions and errors generated by the HTTP request are transformed\ninto RequesterErrors before being handed back to the caller.\n\nInternally, the actual HTTP request is handled via Twisted's http.client.Agent.\nThe agent returns a Deferred to which the TwitterRequester attaches the\n_request_callback and _request_errback functions.\n\nFor every request there are two Deferreds. The first is the \"top level\"\ndeferred, called action_done, which is returned to the caller. The second is\nused internally to handle the actual HTTP request. The second is called back\nwhen the request finishes, and its callbacks kick off collection of the response\nbody data. The first is called back once all data has been received and is ready\nto be handed back to the caller.\n\nThe ApiBody* classes are created for the sole purpose of sending and receving\nthe bodies of requests and responses. These classes are never exposed outside\nthe module (or they shouldn't be), they are strictly used internally.\n'''\n\n\nimport logging\nimport json\nfrom urllib import urlencode\n\nfrom twisted.internet.protocol import Protocol\nfrom twisted.web import client\nfrom twisted.web.http import PotentialDataLoss\nfrom twisted.web.http_headers import Headers\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet import reactor\nfrom twisted.python.failure import Failure\n\n\nLOG = logging.getLogger('twitter.requester')\n\nAPI_HOST = 'api.twitter.com'\nAPI_PATH = '/1/%s.json'\n\n\nclass TwitterRequester(object):\n '''\n Handles all interaction with the Twitter API through specialized methods for\n each API call that AgoraBot needs. Broadly, each of the public methods of\n this class returns a Deferred that is called back with the result of the\n request, or errback'd with the reason for failure.\n '''\n\n\n def __init__(self, controller, authorizer, api_host=API_HOST,\n api_path=API_PATH):\n '''\n @param controller:\n @param authorizer:\n @param api_host: The Twitter API hostname (str)\n @param api_path: Path string, must contain a %s where the specific API\n call can be expanded (str)\n '''\n self.controller = controller\n self.authorizer = authorizer\n self.agent = client.Agent(reactor)\n\n # originally these were module level, but that makes it much more\n # difficult to change the hostname and path if needed\n self.api_host = api_host\n self.api_path = api_path\n self.api_url = 'https://%s%s' % (self.api_host, self.api_path)\n self.api = {\n 'update' : self.api_url % 'statuses/update',\n 'retweet' : self.api_url % 'statuses/retweet/%s',\n 'follow' : self.api_url % 'friendships/create',\n 'dm' : self.api_url % 'direct_messages/new',\n 'verify_credentials' : self.api_url % 'account/verify_credentials',\n }\n\n\n def _do_request(self, method, uri, params):\n '''\n Perform the HTTP request.\n\n Generates the appropriate headers, including the Host and Authorization\n headers, makes the requests and assigns (call|err)backs to the returned\n Deferred object.\n\n @param method: The HTTP method to use (str)\n @param uri: A fully defined URI against which the request will be made\n (str)\n @param params: A set of parameters to include with the request (dict)\n @returns: A deferred that gets fired when the entire action is\n completed (twisted.internet.defer.Deferred)\n '''\n headers = Headers()\n headers.addRawHeader('Host', self.api_host)\n headers.addRawHeader('Authorization',\n self.authorizer.generate_authorization_header(\n method, uri, params,\n realm='https://api.twitter.com'))\n\n params = urlencode(params)\n\n if method == 'POST':\n body_producer = ApiBodyProducer(params)\n else:\n body_producer = None\n uri = '%s?%s' % (uri, params)\n\n action_done = Deferred()\n\n LOG.info('Performing HTTP request: %s %s', method, uri)\n finished = self.agent.request(method, uri, headers, body_producer)\n finished.addCallback(_request_callback, action_done)\n finished.addErrback(_request_errback, action_done)\n\n return action_done\n\n\n def update(self, status):\n '''\n Post a tweet with the status passed in.\n\n @param tweet: A tweet object from which to derive this tweet (dict)\n @param retweet: If True, use Twitter's retweet mechanism, if False, do a\n manual repost using the format provided in the config (bool)\n @returns: A deferred that will be fired when the action is complete\n (twisted.internet.defer.Deferred)\n '''\n LOG.info('Tweeting: %s', status)\n return self._do_request('POST', self.api['update'],\n { 'status': status })\n\n\n def retweet(self, tweet_id):\n '''\n Post a native retweet of the tweet whose ID is passed in.\n\n @param tweet_id: The ID of the tweet to retweet (str)\n @returns: A deferred that will be fired when the action is complete\n (twisted.internet.defer.Deferred)\n '''\n LOG.info('Retweeting tweet with ID: %s', tweet_id)\n return self._do_request('POST', self.api['retweet'] % tweet_id, {})\n\n\n def direct_message(self, screen_name, user_id, message):\n '''\n @param screen_name: Screen name of the user who should receive the DM\n (str)\n @param user_id: User ID of the user who should receive the DM (str)\n @param message: Direct message text (str)\n @returns: A deferred that will be fired when the action is complete\n (twisted.internet.defer.Deferred)\n '''\n LOG.info('Sending DM to user: %s', screen_name)\n return self._do_request('POST', self.api['dm'],\n { 'screen_name': screen_name,\n 'user_id': user_id,\n 'text': message })\n\n\n def follow(self, screen_name, user_id):\n '''\n @param screen_name: Screen name of the user to follow (str)\n @param user_id: User ID of the user to follow (str)\n @returns: A deferred that will be fired when the action is complete\n (twisted.internet.defer.Deferred)\n '''\n LOG.info('Sending follow request to user: %s', screen_name)\n return self._do_request('POST', self.api['follow'],\n { 'screen_name': screen_name,\n 'user_id': user_id,\n 'follow': True })\n\n\n def verify_user(self):\n '''\n @returns: A deferred that will be fired when the action is complete\n (twisted.internet.defer.Deferred)\n '''\n LOG.info('Requesting user credentials')\n return self._do_request('GET', self.api['verify_credentials'],\n { 'skip_status': True })\n\n\n#\n# (Call|Err)back methods for the Deferred returned by the Agent's request\n# method\n#\n\n\ndef _request_callback(response, action_done):\n '''\n Callback that handles a successful HTTP request against the API.\n\n @param response: The response from Twitter (twisted.web.client.Response)\n @param action_done: A deferred that will be fired when the action is\n complete (twisted.internet.defer.Deferred)\n @returns: None\n '''\n LOG.info('Received response: %d %s', response.code, response.phrase)\n\n if response.code == 200:\n # success! deliver the body and move on\n response.deliverBody(ApiBodyReceiver(action_done))\n else:\n failure = None\n if response.code == 304:\n # not modified -- no new data\n failure = Failure(RequesterError(RequesterError.GIVEUP,\n 'No new data for this response'))\n elif response.code == 401:\n # unauthorized -- missing auth credentials\n failure = Failure(RequesterError(RequesterError.REAUTH,\n 'Missing or invalid OAuth '\n 'credentials'))\n elif response.code == 403:\n # forbidden -- response has been refused\n failure = Failure(RequesterError(RequesterError.BACKOFF,\n 'response denied due to update '\n 'limit'))\n elif response.code == 404:\n failure = Failure(RequesterError(RequesterError.GIVEUP,\n 'Requested resource not found'))\n elif response.code == 406:\n # unacceptable -- search api: invalid format\n # shouldn't ever hit this since we're not using the search API\n failure = Failure(RequesterError(RequesterError.GIVEUP,\n 'Invalid format specified'))\n elif response.code == 420:\n failure = Failure(RequesterError(RequesterError.BACKOFF,\n 'API rate limit hit'))\n elif response.code == 500:\n # something broken on their end\n failure = Failure(RequesterError(RequesterError.REST,\n 'Something at Twitter is broken'))\n elif response.code == 502:\n # bad gateway -- twitter is down\n failure = Failure(RequesterError(RequesterError.REST,\n 'Twitter API is down'))\n elif response.code == 503:\n failure = Failure(RequesterError(RequesterError.BACKOFF,\n 'API is up but overloaded'))\n else:\n # buh.... we should never hit this\n failure = Failure(RequesterError(RequesterError.GIVEUP,\n 'Invalid response from Twitter '\n 'API'))\n action_done.errback(failure)\n\n\ndef _request_errback(failure, action_done):\n '''\n Errback that handles a failed request against the Twitter API.\n\n @param failure: A Failure instance containing information about what\n went wrong (twisted.python.failure.Failure)\n @param action_done: A deferred that will be fired when the action is\n complete (twisted.internet.defer.Deferred)\n @returns: None\n '''\n action_done.errback(RequesterError(RequesterError.TRYAGAIN,\n '%s: %s' % (failure.type.__name__,\n failure.getErrorMessage())))\n\n\nclass ApiBodyProducer(object):\n '''\n Writes a POST body for sending to the Twitter API. Very simple, very\n straightforward.\n '''\n\n\n def __init__(self, body):\n '''\n @param body: A URL encoded string to write as the body of the request\n (str)\n '''\n self.body = body\n self.length = len(self.body)\n self.deferred = Deferred()\n\n\n def startProducing(self, consumer):\n '''\n Start producing the body. Since there's not much that needs to be\n produced, one call should be sufficient to produce the entire request\n body.\n\n @param consumer: An object that implements Twisted's IConsumer protocol\n (object)\n @returns: a Deferred that has already been fired with a callback of None\n (Deferred)\n '''\n consumer.write(self.body)\n LOG.debug('Wrote request body: %s', self.body)\n self.deferred.callback(None)\n return self.deferred\n\n\n def stopProducing(self):\n '''\n A stub method. I don't have a use for this now. It should prevent the\n Deferred from being fired, but there's no way the body wouldn't have\n already been entirely produced and the Deferred is out in the wild.\n\n @returns: None\n '''\n pass\n\n\nclass ApiBodyReceiver(Protocol):\n '''\n An IProtocol provider for receiving the body of an API request.\n '''\n\n\n def __init__(self, action_done):\n '''\n @param action_done: A Deferred that is called back with the contents of\n the body of the HTTP request (twisted.internet.defer.Deferred)\n '''\n self._buffer = []\n self.action_done = action_done\n\n\n def dataReceived(self, data):\n '''\n Called every time a chunk of body data is received.\n\n @param data: a chunk of data from the body of the HTTP request (bytes)\n '''\n self._buffer.append(data)\n\n\n def connectionLost(self, reason):\n '''\n Called when the connection finishes, whether cleanly or not.\n\n @param reason: the reason the connection was closed\n (twisted.python.failure.Failure)\n '''\n if reason.type == client.ResponseDone:\n data = json.loads(''.join([b.decode() for b in self._buffer]))\n LOG.debug('Response body received:\\n%s', json.dumps(data, indent=2))\n self.action_done.callback(data)\n else:\n if reason.type == PotentialDataLoss:\n failure = Failure(RequesterError(RequesterError.TRYAGAIN,\n 'Some data may have been '\n 'lost'))\n elif reason.type == client.ResponseFailed:\n failure = Failure(RequesterError(RequesterError.TRYAGAIN,\n 'Request failed'))\n else:\n failure = Failure(RequesterError(RequesterError.TRYAGAIN,\n 'Unknown error'))\n self.action_done.errback(failure)\n\n\nclass RequesterError(Exception):\n '''\n An exception raised in the event of a problem completing a request to the\n Twitter API.\n '''\n\n # actions\n GIVEUP = 1 # abandon the current request\n BACKOFF = 2 # back off and try again later\n REAUTH = 3 # fix the OAuth headers and try again\n REST = 4 # take a long break; something's wrong over there\n TRYAGAIN = 5 # try again immediately\n\n\n def __init__(self, action, message):\n '''\n @param action: the action to suggest to the catcher (int)\n @param value: a free form message, passed directly to the Exception\n constructor (str)\n '''\n self.action = action\n self.message = message\n\n\n def __str__(self):\n if self.action == RequesterError.GIVEUP:\n action_message = 'give up'\n elif self.action == RequesterError.BACKOFF:\n action_message = 'back off and try again'\n elif self.action == RequesterError.REAUTH:\n action_message = 'fix your OAuth credentials and try again'\n elif self.action == RequesterError.REST:\n action_message = 'rest and try again'\n elif self.action == RequesterError.TRYAGAIN:\n action_message = 'try again immediately'\n else:\n action_message = 'start panicking now'\n return '%s; %s' % (self.message, action_message)\n", "sub_path": "twitter/requester.py", "file_name": "requester.py", "file_ext": "py", "file_size_in_byte": 15634, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 42, "usage_type": "call"}, {"api_name": "twisted.web.client.Agent", "line_number": 68, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 68, "usage_type": "argument"}, {"api_name": "twisted.web.client", "line_number": 68, "usage_type": "name"}, {"api_name": "twisted.web.http_headers.Headers", "line_number": 99, "usage_type": "call"}, {"api_name": "urllib.urlencode", "line_number": 106, "usage_type": "call"}, {"api_name": "twisted.internet.defer.Deferred", "line_number": 114, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 215, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 219, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 224, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 228, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 233, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 236, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 240, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 244, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 247, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 251, "usage_type": "call"}, {"api_name": "twisted.internet.defer.Deferred", "line_number": 286, "usage_type": "call"}, {"api_name": "twisted.internet.protocol.Protocol", "line_number": 317, "usage_type": "name"}, {"api_name": "twisted.web.client.ResponseDone", "line_number": 348, "usage_type": "attribute"}, {"api_name": "twisted.web.client", "line_number": 348, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 349, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 350, "usage_type": "call"}, {"api_name": "twisted.web.http.PotentialDataLoss", "line_number": 353, "usage_type": "name"}, {"api_name": "twisted.python.failure.Failure", "line_number": 354, "usage_type": "call"}, {"api_name": "twisted.web.client.ResponseFailed", "line_number": 357, "usage_type": "attribute"}, {"api_name": "twisted.web.client", "line_number": 357, "usage_type": "name"}, {"api_name": "twisted.python.failure.Failure", "line_number": 358, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 361, "usage_type": "call"}]} +{"seq_id": "161780667", "text": "from setuptools import find_packages, setup\n\n\nlong_desc = '''\\\nCherryOnTop sits atop CherryPy, it provides convenience methods for binding\nroutes and handling JSON request/response payloads.\n'''\n\n\nif __name__ == '__main__':\n setup(\n packages=find_packages(),\n name='CherryOnTop',\n version='0.0.7',\n author='Christopher Sira',\n author_email='cbsira@gmail.com',\n license='BSD',\n url='https://github.com/csira/cherryontop',\n description='Helper utilities for building JSON APIs with CherryPy.',\n long_description=long_desc,\n install_requires=[\n 'cherrypy',\n 'routes',\n 'ujson',\n ],\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Framework :: CherryPy',\n 'Intended Audience :: Developers',\n 'License :: Freely Distributable',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: HTTP Servers',\n 'Topic :: Software Development :: Libraries :: Application Frameworks',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n )\n", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1475, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 11, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "348932604", "text": "from sqlalchemy.dialects.postgresql import TSVECTOR\n\nfrom .actor import Actor\nfrom .base_model import BaseModel, db\nfrom .category import Category\nfrom .film_actor import FilmActor\nfrom .film_category import FilmCategory\nfrom .language import Language\n\nsearch_like_escape = BaseModel.search_like_escape\n\n\nclass Film(BaseModel):\n __tablename__ = 'film'\n\n film_id = db.Column(db.Integer, primary_key=True, server_default=db.text(\n \"nextval('film_film_id_seq'::regclass)\"))\n title = db.Column(db.String(255), nullable=False, index=True)\n description = db.Column(db.Text)\n release_year = db.Column(db.Integer)\n language_id = db.Column(db.ForeignKey('language.language_id',\n ondelete='RESTRICT', onupdate='CASCADE'), nullable=False, index=True)\n rental_duration = db.Column(\n db.SmallInteger, nullable=False, server_default=db.text(\"3\"))\n rental_rate = db.Column(db.Numeric(4, 2), nullable=False,\n server_default=db.text(\"4.99\"))\n length = db.Column(db.SmallInteger)\n replacement_cost = db.Column(\n db.Numeric(5, 2), nullable=False, server_default=db.text(\"19.99\"))\n rating = db.Column(db.Enum('G', 'PG', 'PG-13', 'R', 'NC-17',\n name='mpaa_rating'), server_default=db.text(\"'G'::mpaa_rating\"))\n last_update = db.Column(db.DateTime, nullable=False,\n server_default=db.text(\"now()\"))\n special_features = db.Column(db.ARRAY(db.Text()))\n fulltext = db.Column(TSVECTOR, nullable=False, index=True)\n\n language = db.relationship('Language')\n\n categories = db.relationship('Category', secondary=\"film_category\",\n back_populates=\"films\")\n actors = db.relationship('Actor', secondary=\"film_actor\",\n back_populates=\"films\")\n\n def __repr__(self):\n return ''.format(self.film_id, self.title)\n\n @classmethod\n def datatable_search(cls, args):\n\n offset = args.get('offset') or 0\n limit = args.get('limit') or 10\n filters = args.get('filters') or {}\n orders = args.get('orders') or []\n\n records_total = Film.query.count()\n\n rs_filters = []\n for filter in filters:\n filter_id = filter.get('id')\n\n search_value = filter.get('value') or ''\n if search_value == '':\n continue\n\n if filter_id == 'title':\n rs_filters.append(Film.title.ilike(\n search_like_escape(search_value)))\n continue\n\n if filter_id == 'categories.category':\n rs_filters.append(Film.categories.any(\n Category.name.ilike(search_like_escape(search_value))\n ))\n continue\n\n if filter_id == 'actors.full_name':\n rs_filters.append(\n Film.actors.any(\n Actor.full_name.ilike(\n search_like_escape(search_value)),\n )\n )\n continue\n\n if filter_id == 'length':\n rs_filters.append(db.cast(Film.length, db.Text).ilike(\n search_like_escape(search_value)))\n continue\n\n if filter_id == 'rating':\n rs_filters.append(db.cast(Film.rating, db.Text).ilike(\n search_like_escape(search_value)))\n continue\n\n if filter_id == 'language.name':\n rs_filters.append(Language.name.ilike(\n search_like_escape(search_value)))\n continue\n\n if filter_id == 'rental_rate':\n rs_filters.append(db.cast(Film.rental_rate, db.Text).ilike(\n search_like_escape(search_value)))\n continue\n\n rs_filtered = Film.query.join(Language).filter(db.and_(*rs_filters))\n\n # Count without limit\n records_filtered = rs_filtered.with_entities(\n db.func.count(db.distinct(Film.film_id))).scalar()\n\n order_columns = []\n for order in orders:\n order_id = order.get('id')\n order_desc = order.get('desc')\n\n if order_id == 'title':\n order_columns.append([Film.title, order_desc])\n continue\n\n if order_id == 'length':\n order_columns.append([Film.length, order_desc])\n continue\n\n if order_id == 'rating':\n order_columns.append(\n [db.cast(Film.rating, db.Text), order_desc])\n continue\n\n if order_id == 'language.name':\n order_columns.append([Language.name, order_desc])\n continue\n\n if order_id == 'rental_rate':\n order_columns.append([Film.rental_rate, order_desc])\n continue\n\n raise NameError('Unknown sort column {}'.format(order_id))\n\n rs_orders = list(map(lambda order: order[0].desc() if order[1] else order[0].asc(),\n order_columns))\n select_columns = list(map(lambda order: order[0], order_columns))\n\n # Only interested on film_id AFTER order and limit\n filtered_with_limit_subq = rs_filtered \\\n .with_entities(Film.film_id).order_by(*rs_orders) \\\n .limit(limit).offset(offset).subquery()\n\n final_query = Film.query \\\n .join(filtered_with_limit_subq, Film.film_id == filtered_with_limit_subq.c.film_id) \\\n .join(Language).outerjoin(Category, Film.categories).outerjoin(Actor, Film.actors) \\\n .options(db.contains_eager(Film.language), db.contains_eager(Film.categories), db.contains_eager(Film.actors)) \\\n .order_by(*rs_orders) # Apply order again for eager loading\n\n # Force order on actor and category\n final_query = final_query.order_by(\n Actor.full_name.asc(), Category.name.asc())\n\n films = final_query.all()\n\n film_list = {\n 'records_total': records_total,\n 'records_filtered': records_filtered,\n 'films': films,\n }\n\n return film_list\n", "sub_path": "api/models/film.py", "file_name": "film.py", "file_ext": "py", "file_size_in_byte": 6239, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "base_model.BaseModel.search_like_escape", "line_number": 10, "usage_type": "attribute"}, {"api_name": "base_model.BaseModel", "line_number": 10, "usage_type": "name"}, {"api_name": "base_model.BaseModel", "line_number": 13, "usage_type": "name"}, {"api_name": "base_model.db.Column", "line_number": 16, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 16, "usage_type": "name"}, {"api_name": "base_model.db.Integer", "line_number": 16, "usage_type": "attribute"}, {"api_name": "base_model.db.text", "line_number": 16, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 18, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 18, "usage_type": "name"}, {"api_name": "base_model.db.String", "line_number": 18, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 19, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 19, "usage_type": "name"}, {"api_name": "base_model.db.Text", "line_number": 19, "usage_type": "attribute"}, {"api_name": "base_model.db.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 20, "usage_type": "name"}, {"api_name": "base_model.db.Integer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "base_model.db.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 21, "usage_type": "name"}, {"api_name": "base_model.db.ForeignKey", "line_number": 21, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 23, "usage_type": "name"}, {"api_name": "base_model.db.SmallInteger", "line_number": 24, "usage_type": "attribute"}, {"api_name": "base_model.db", "line_number": 24, "usage_type": "name"}, {"api_name": "base_model.db.text", "line_number": 24, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 25, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 25, "usage_type": "name"}, {"api_name": "base_model.db.Numeric", "line_number": 25, "usage_type": "call"}, {"api_name": "base_model.db.text", "line_number": 26, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 26, "usage_type": "name"}, {"api_name": "base_model.db.Column", "line_number": 27, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 27, "usage_type": "name"}, {"api_name": "base_model.db.SmallInteger", "line_number": 27, "usage_type": "attribute"}, {"api_name": "base_model.db.Column", "line_number": 28, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 28, "usage_type": "name"}, {"api_name": "base_model.db.Numeric", "line_number": 29, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 29, "usage_type": "name"}, {"api_name": "base_model.db.text", "line_number": 29, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 30, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 30, "usage_type": "name"}, {"api_name": "base_model.db.Enum", "line_number": 30, "usage_type": "call"}, {"api_name": "base_model.db.text", "line_number": 31, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 31, "usage_type": "name"}, {"api_name": "base_model.db.Column", "line_number": 32, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 32, "usage_type": "name"}, {"api_name": "base_model.db.DateTime", "line_number": 32, "usage_type": "attribute"}, {"api_name": "base_model.db.text", "line_number": 33, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 33, "usage_type": "name"}, {"api_name": "base_model.db.Column", "line_number": 34, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 34, "usage_type": "name"}, {"api_name": "base_model.db.ARRAY", "line_number": 34, "usage_type": "call"}, {"api_name": "base_model.db.Text", "line_number": 34, "usage_type": "call"}, {"api_name": "base_model.db.Column", "line_number": 35, "usage_type": "call"}, {"api_name": "sqlalchemy.dialects.postgresql.TSVECTOR", "line_number": 35, "usage_type": "argument"}, {"api_name": "base_model.db", "line_number": 35, "usage_type": "name"}, {"api_name": "base_model.db.relationship", "line_number": 37, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 37, "usage_type": "name"}, {"api_name": "base_model.db.relationship", "line_number": 39, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 39, "usage_type": "name"}, {"api_name": "base_model.db.relationship", "line_number": 41, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 41, "usage_type": "name"}, {"api_name": "category.Category.name.ilike", "line_number": 72, "usage_type": "call"}, {"api_name": "category.Category.name", "line_number": 72, "usage_type": "attribute"}, {"api_name": "category.Category", "line_number": 72, "usage_type": "name"}, {"api_name": "actor.Actor.full_name.ilike", "line_number": 79, "usage_type": "call"}, {"api_name": "actor.Actor.full_name", "line_number": 79, "usage_type": "attribute"}, {"api_name": "actor.Actor", "line_number": 79, "usage_type": "name"}, {"api_name": "base_model.db.cast", "line_number": 86, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 86, "usage_type": "name"}, {"api_name": "base_model.db.Text", "line_number": 86, "usage_type": "attribute"}, {"api_name": "base_model.db.cast", "line_number": 91, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 91, "usage_type": "name"}, {"api_name": "base_model.db.Text", "line_number": 91, "usage_type": "attribute"}, {"api_name": "language.Language.name.ilike", "line_number": 96, "usage_type": "call"}, {"api_name": "language.Language.name", "line_number": 96, "usage_type": "attribute"}, {"api_name": "language.Language", "line_number": 96, "usage_type": "name"}, {"api_name": "base_model.db.cast", "line_number": 101, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 101, "usage_type": "name"}, {"api_name": "base_model.db.Text", "line_number": 101, "usage_type": "attribute"}, {"api_name": "language.Language", "line_number": 105, "usage_type": "argument"}, {"api_name": "base_model.db.and_", "line_number": 105, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 105, "usage_type": "name"}, {"api_name": "base_model.db.func.count", "line_number": 109, "usage_type": "call"}, {"api_name": "base_model.db.func", "line_number": 109, "usage_type": "attribute"}, {"api_name": "base_model.db", "line_number": 109, "usage_type": "name"}, {"api_name": "base_model.db.distinct", "line_number": 109, "usage_type": "call"}, {"api_name": "base_model.db.cast", "line_number": 126, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 126, "usage_type": "name"}, {"api_name": "base_model.db.Text", "line_number": 126, "usage_type": "attribute"}, {"api_name": "language.Language.name", "line_number": 130, "usage_type": "attribute"}, {"api_name": "language.Language", "line_number": 130, "usage_type": "name"}, {"api_name": "actor.Actor", "line_number": 150, "usage_type": "argument"}, {"api_name": "category.Category", "line_number": 150, "usage_type": "argument"}, {"api_name": "language.Language", "line_number": 150, "usage_type": "argument"}, {"api_name": "base_model.db.contains_eager", "line_number": 151, "usage_type": "call"}, {"api_name": "base_model.db", "line_number": 151, "usage_type": "name"}, {"api_name": "actor.Actor.full_name.asc", "line_number": 156, "usage_type": "call"}, {"api_name": "actor.Actor.full_name", "line_number": 156, "usage_type": "attribute"}, {"api_name": "actor.Actor", "line_number": 156, "usage_type": "name"}, {"api_name": "category.Category.name.asc", "line_number": 156, "usage_type": "call"}, {"api_name": "category.Category.name", "line_number": 156, "usage_type": "attribute"}, {"api_name": "category.Category", "line_number": 156, "usage_type": "name"}]} +{"seq_id": "535873681", "text": "# -*- coding: utf-8 -*-\n# @Time : 2018/11/12 10:46\n# @Author : zjm\n# @Version : 1.0.1\n\nfrom __future__ import absolute_import\n\nimport requests\nimport cv2\nimport os\nimport uuid\n\nfrom api.errorcode import ErrorCode\nfrom config import setting\nfrom datetime import datetime\nfrom log import logger\nfrom models.media.folder import folders\nfrom models.media.file import files, FileType\nfrom models.media.image import images\nfrom services.media.folder import FolderService\nfrom sqlalchemy.sql import select\n\n\nIMAGE_TYPES = ['jpg', 'jpeg', 'png', 'gif']\n\nfolderservice = FolderService()\n\n\nclass ImageService:\n\n def find_folder(self, db, root_dir, dir_name):\n \"\"\"\n 查找图片文件目录\n Parameters\n ----------\n root_dir : str\n 根目录名称\n dir_name : str\n 目录名称\n\n Returns\n -------\n folder\n 目录信息\n \"\"\"\n folder = None\n try:\n t = folders.alias('f')\n query = select([t.c.id, t.c.name]).where(t.c.code == root_dir)\n row = db.execute(query).fetchone()\n if row is not None:\n query = select([t.c.id, t.c.name]).where(t.c.code == dir_name)\n query = query.where(t.c.parent_id == row[0])\n row = db.execute(query).fetchone()\n if row is not None:\n full_path = self.create_image_folder(root_dir, dir_name)\n url_path = self.create_url_path(root_dir, dir_name)\n folder = {'id': row[0], 'code': dir_name, 'name': row[1],\n 'full_path': full_path, 'url_path': url_path}\n except Exception:\n logger.exception(' root_dir: ' + root_dir +\n ', dir_name: ' + dir_name + ', error: ')\n folder = None\n return folder\n\n def save_image(self, db, folder, file_name, url):\n result = {'code': ErrorCode.OK.value,\n 'message': ErrorCode.OK.name}\n try:\n folder_id = folder['id']\n full_path = folder['full_path']\n url_path = folder['url_path']\n logger.info(' folder_id: ' + str(folder_id) +\n ', file_name: ' + file_name)\n uid = str(uuid.uuid1())\n new_file_name = uid + os.path.splitext(file_name)[1]\n r = self.download(full_path, new_file_name, url)\n if r:\n save_file_name = full_path + os.path.sep + new_file_name\n file_size = os.path.getsize(save_file_name)\n file_path = \"{0}/{1}\".format(url_path, new_file_name)\n data = {'uuid': uid,\n 'name': new_file_name,\n 'original_filename': file_name,\n 'type': FileType.IMAGE,\n 'file_path': file_path,\n 'file_szie': file_size,\n 'folder_id': folder_id,\n 'created_date': datetime.now()}\n\n img = cv2.imread(save_file_name)\n sp = img.shape\n print(sp)\n print(sp[0])\n print(sp[1])\n image_date = {'img_height': sp[0], 'img_width': sp[1]}\n result = self.save(db, uid, file_name, data, image_date)\n except Exception as e:\n logger.exception(' error: ')\n result['code'] = ErrorCode.EXCEPTION.value\n result['message'] = str(e)\n\n return result\n\n def upload(self, db, folder_id, file_name, file_content,\n user={}, create_date_folder=True):\n \"\"\"\n 上传图片文件,包括将上传文件保存到磁盘和保存上传文件数据库信息。\n Parameters\n ----------\n folder_id : str\n 上传文件目录ID\n file_name : str\n 上传文件名称\n file_content : str\n 上传文件内容\n user : dict\n 操作用户信息\n create_date_folder : boolean\n 是否根据日期每天新建一个子目录\n\n Returns\n -------\n result\n 文件上传结果\n \"\"\"\n result = {'code': ErrorCode.OK.value,\n 'message': ErrorCode.OK.name}\n try:\n logger.info(' folder_id: ' +\n str(folder_id) + ', file_name: ' + file_name)\n ext_name = os.path.splitext(file_name)[1]\n ext_name = ext_name.lower()\n if len(ext_name) > 1:\n ext_name = ext_name[1:]\n if ext_name not in IMAGE_TYPES:\n result['code'] = ErrorCode.UNSUPPORTED_FILE_TYPE.value\n result['message'] = ErrorCode.UNSUPPORTED_FILE_TYPE.name\n return result\n if folder_id is not None:\n folder = folderservice.get_folder_path(db, folder_id)\n if folder is not None:\n now = datetime.now()\n media_root = setting['media_root']\n path = folder['path']\n path_list = path.split(os.path.sep)\n dir_name = media_root + os.path.sep + path\n folderservice.create_abs_folder(dir_name)\n if create_date_folder:\n date = datetime.strftime(now, \"%Y%m%d\")\n path_list.append(date)\n dir_name = dir_name + os.path.sep + date\n folderservice.create_abs_folder(dir_name)\n result = self.save_image_file(\n dir_name, file_name, file_content)\n if result['code'] == ErrorCode.OK.value:\n uuid = result['uid']\n name = result['name']\n path_list.append(name)\n file_path = '/'.join(path_list)\n data = {'uuid': uuid,\n 'name': name,\n 'original_filename': file_name,\n 'file_path': file_path,\n 'type': FileType.IMAGE,\n 'file_size': result['fileSize'],\n 'folder_id': folder_id,\n 'created_date': now}\n image_date = {'img_height': result['height'],\n 'img_width': result['width']}\n result = self.save(\n db, uuid, file_name, data, image_date)\n result['uuid'] = uuid\n result['save_name'] = name\n result['file_name'] = file_name\n else:\n result['code'] = ErrorCode.NOT_FOUND.value\n result['message'] = \"folder {0} not found!\".format(\n folder_id)\n else:\n result['code'] = ErrorCode.MISS_PARAM.value\n result['message'] = \"miss param folder_id!\"\n except Exception as e:\n logger.exception(' folder_id: ' + str(folder_id) +\n ', file_name: ' + file_name + ', error: ')\n result['code'] = ErrorCode.EXCEPTION.value\n result['message'] = str(e)\n return result\n\n def save(self, db, uuid, file_name, file_data, image_date):\n \"\"\"\n 保存文件数据库信息\n Parameters\n ----------\n db : db\n db 操作对象\n uuid : str\n 生成的uuid\n file_name : str\n 文件名称\n data : dict\n 数据\n\n Returns\n -------\n result\n 保存结果\n \"\"\"\n result = {'code': ErrorCode.OK.value,\n 'message': ErrorCode.OK.name}\n tx = db.begin()\n try:\n logger.debug(' uuid: ' + uuid + ', file_name: ' + file_name)\n file = db.save(files, file_data)\n file_id = file['id']\n image_date['id'] = file_id\n db.insert(images, image_date)\n tx.commit()\n result['file_id'] = file_id\n except Exception as e:\n logger.exception(' uuid: ' + uuid +\n ', file_name: ' + file_name + ', error: ')\n result['code'] = ErrorCode.EXCEPTION.value\n result['message'] = str(e)\n tx.rollback()\n\n return result\n\n def create_image_folder(self, root_dir, dir_name):\n \"\"\"\n 创建图片文件目录,根据日期每天新建一个目录\n Parameters\n ----------\n root_dir : str\n 根目录\n dir_name : str\n 目录名称\n\n Returns\n -------\n image_path\n 图片文件目录完整路径\n \"\"\"\n image_path = None\n try:\n logger.info(' root_dir: ' + root_dir +\n ', dir_name: ' + dir_name)\n media_root = setting['media_root']\n date = datetime.strftime(datetime.now(), \"%Y%m%d\")\n root_path = media_root + os.path.sep + root_dir\n dir_path = root_path + os.path.sep + dir_name\n image_path = dir_path + os.path.sep + date\n self.create_abs_folder(image_path)\n except Exception:\n logger.exception(' root_dir: ' + root_dir +\n ', dir_name: ' + dir_name + ', error: ')\n image_path = False\n return image_path\n\n def create_url_path(self, root, path):\n \"\"\"\n 创建图片相对URL\n Parameters\n ----------\n root : str\n 根目录\n path : str\n 目录名称\n\n Returns\n -------\n url_path\n 图片相对URL\n \"\"\"\n url_path = ''\n try:\n date = datetime.strftime(datetime.now(), \"%Y%m%d\")\n url_path = \"{0}/{1}/{2}\".format(root, path, date)\n except Exception:\n logger.exception(' root: ' + root +\n ', path: ' + path + ', error: ')\n return url_path\n\n def create_image_url(self, file_path):\n \"\"\"\n 创建图片完整URL\n Parameters\n ----------\n root : str\n 根目录\n path : str\n 目录名称\n\n Returns\n -------\n image_url\n 图片完整URL\n \"\"\"\n image_url = ''\n try:\n media_url = setting['media_url']\n image_url = \"{0}/{1}\".format(media_url, file_path)\n except Exception:\n logger.exception(' error: ')\n return image_url\n\n def create_abs_folder(self, name):\n result = True\n try:\n logger.debug(' name: ' + name)\n if not os.path.exists(name):\n logger.info(' name: ' + name)\n os.makedirs(name)\n except Exception:\n logger.exception(' error: ')\n result = False\n return result\n\n def get_ext_name(self, file_name):\n \"\"\"\n 获取文件扩展名\n Parameters\n ----------\n file_name : str\n 文件名称\n\n Returns\n -------\n ext_name\n 文件扩展名\n \"\"\"\n ext_name = None\n try:\n ext = os.path.splitext(file_name)[1]\n if len(ext) > 1:\n ext = ext.lower()\n ext_name = ext[1:]\n return ext_name\n except Exception:\n logger.exception(' file_name: ' +\n file_name + ', error: ')\n ext_name = None\n return ext_name\n\n def save_image_file(self, dir_name, file_name, file_content):\n \"\"\"\n 保存图片文件\n Parameters\n ----------\n dir_name : str\n 文件保存目录\n file_name : str\n 文件原名称\n file_content : str\n 文件内容\n\n Returns\n -------\n result\n 文件保存结果\n \"\"\"\n result = {'code': ErrorCode.OK.value,\n 'message': ErrorCode.OK.name}\n try:\n logger.info(' dir_name: ' +\n dir_name + ', file_name: ' + file_name)\n uid = str(uuid.uuid1())\n ext = os.path.splitext(file_name)[1]\n ext = ext.lower()\n new_file_name = uid + ext\n save_file_name = dir_name + os.path.sep + new_file_name\n logger.info(' save_file_name: ' + save_file_name)\n with open(save_file_name, 'wb') as f:\n f.write(file_content)\n f.close()\n\n img = cv2.imread(save_file_name)\n sp = img.shape\n print(sp)\n print(sp[0])\n print(sp[1])\n result['uid'] = uid\n result['name'] = new_file_name\n result['fileName'] = file_name\n result['fileSize'] = os.path.getsize(save_file_name)\n result['height'] = sp[0]\n result['width'] = sp[1]\n except Exception as e:\n logger.exception(' file_name: ' +\n file_name + ', error: ')\n result['code'] = ErrorCode.EXCEPTION.value\n result['message'] = str(e)\n\n return result\n\n def download(self, save_dir, save_file_name, url):\n \"\"\"\n 下载文件\n Parameters\n ----------\n save_dir : str\n 下载文件保存目录完整路径\n save_file_name : str\n 下载文件保存名称\n url : str\n 下载文件URL地址\n\n Returns\n -------\n result\n True or False\n \"\"\"\n result = True\n try:\n logger.info(' save_dir: ' + save_dir +\n ', save_file_name: ' + save_file_name)\n r = requests.get(url)\n with open(save_dir + os.path.sep + save_file_name, 'wb') as f:\n f.write(r.content)\n except Exception:\n logger.exception(' error: ')\n result = False\n\n return result\n", "sub_path": "services/media/image.py", "file_name": "image.py", "file_ext": "py", "file_size_in_byte": 14425, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "services.media.folder.FolderService", "line_number": 26, "usage_type": "call"}, {"api_name": "models.media.folder.folders.alias", "line_number": 48, "usage_type": "call"}, {"api_name": "models.media.folder.folders", "line_number": 48, "usage_type": "name"}, {"api_name": "sqlalchemy.sql.select", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.sql.select", "line_number": 52, "usage_type": "call"}, {"api_name": "log.logger.exception", "line_number": 61, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 61, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 67, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 67, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 68, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 68, "usage_type": "name"}, {"api_name": "log.logger.info", "line_number": 73, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 73, "usage_type": "name"}, {"api_name": "uuid.uuid1", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "models.media.file.FileType.IMAGE", "line_number": 85, "usage_type": "attribute"}, {"api_name": "models.media.file.FileType", "line_number": 85, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 89, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 89, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 91, "usage_type": "call"}, {"api_name": "log.logger.exception", "line_number": 99, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 99, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.EXCEPTION", "line_number": 100, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 100, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 127, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 127, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 128, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 128, "usage_type": "name"}, {"api_name": "log.logger.info", "line_number": 130, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 130, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path", "line_number": 132, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode.UNSUPPORTED_FILE_TYPE", "line_number": 137, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 137, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.UNSUPPORTED_FILE_TYPE", "line_number": 138, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 138, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 143, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 143, "usage_type": "name"}, {"api_name": "config.setting", "line_number": 144, "usage_type": "name"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strftime", "line_number": 150, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 150, "usage_type": "name"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 156, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 156, "usage_type": "name"}, {"api_name": "models.media.file.FileType.IMAGE", "line_number": 165, "usage_type": "attribute"}, {"api_name": "models.media.file.FileType", "line_number": 165, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.NOT_FOUND", "line_number": 177, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 177, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.MISS_PARAM", "line_number": 181, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 181, "usage_type": "name"}, {"api_name": "log.logger.exception", "line_number": 184, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 184, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.EXCEPTION", "line_number": 186, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 186, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 209, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 209, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 210, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 210, "usage_type": "name"}, {"api_name": "log.logger.debug", "line_number": 213, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 213, "usage_type": "name"}, {"api_name": "models.media.file.files", "line_number": 214, "usage_type": "argument"}, {"api_name": "models.media.image.images", "line_number": 217, "usage_type": "argument"}, {"api_name": "log.logger.exception", "line_number": 221, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 221, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.EXCEPTION", "line_number": 223, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 223, "usage_type": "name"}, {"api_name": "log.logger.info", "line_number": 246, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 246, "usage_type": "name"}, {"api_name": "config.setting", "line_number": 248, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 249, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 249, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 249, "usage_type": "call"}, {"api_name": "os.path", "line_number": 250, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 251, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 252, "usage_type": "attribute"}, {"api_name": "log.logger.exception", "line_number": 255, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 255, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 277, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 277, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 277, "usage_type": "call"}, {"api_name": "log.logger.exception", "line_number": 280, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 280, "usage_type": "name"}, {"api_name": "config.setting", "line_number": 301, "usage_type": "name"}, {"api_name": "log.logger.exception", "line_number": 304, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 304, "usage_type": "name"}, {"api_name": "log.logger.debug", "line_number": 310, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 310, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 311, "usage_type": "call"}, {"api_name": "os.path", "line_number": 311, "usage_type": "attribute"}, {"api_name": "log.logger.info", "line_number": 312, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 312, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 313, "usage_type": "call"}, {"api_name": "log.logger.exception", "line_number": 315, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 315, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 334, "usage_type": "call"}, {"api_name": "os.path", "line_number": 334, "usage_type": "attribute"}, {"api_name": "log.logger.exception", "line_number": 340, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 340, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 362, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 362, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.OK", "line_number": 363, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 363, "usage_type": "name"}, {"api_name": "log.logger.info", "line_number": 365, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 365, "usage_type": "name"}, {"api_name": "uuid.uuid1", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 368, "usage_type": "call"}, {"api_name": "os.path", "line_number": 368, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 371, "usage_type": "attribute"}, {"api_name": "log.logger.info", "line_number": 372, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 372, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 377, "usage_type": "call"}, {"api_name": "os.path.getsize", "line_number": 385, "usage_type": "call"}, {"api_name": "os.path", "line_number": 385, "usage_type": "attribute"}, {"api_name": "log.logger.exception", "line_number": 389, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 389, "usage_type": "name"}, {"api_name": "api.errorcode.ErrorCode.EXCEPTION", "line_number": 391, "usage_type": "attribute"}, {"api_name": "api.errorcode.ErrorCode", "line_number": 391, "usage_type": "name"}, {"api_name": "log.logger.info", "line_number": 415, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 415, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 417, "usage_type": "call"}, {"api_name": "os.path", "line_number": 418, "usage_type": "attribute"}, {"api_name": "log.logger.exception", "line_number": 421, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 421, "usage_type": "name"}]} +{"seq_id": "327365600", "text": "import pytest\n\nfrom ...model.corpus import Corpus\n\nfrom ..fixtures import tiny_corpus, sample_corpus, whole_corpus\n\n\nslow = pytest.mark.skipif(\n not pytest.config.getoption(\"--runslow\"),\n reason=\"need --runslow option to run\"\n)\n\n\ndef test_tiny():\n corpus = Corpus(source=tiny_corpus())\n assert corpus.successes == 1\n assert corpus.failures == 1\n\n\n@slow\ndef test_sample():\n corpus = Corpus(source=sample_corpus())\n assert corpus.successes == 36\n assert corpus.failures == 3\n\n\n@pytest.mark.skipif(not whole_corpus(),\n reason=\"Need to set oracc_corpus_path to point \"\n \"to the whole corpus, which is not bundled with \"\n \"pyoracc\")\n@slow\ndef test_whole():\n corpus = Corpus(source=whole_corpus())\n assert corpus.successes == 2474\n assert corpus.failures == 394\n", "sub_path": "pyoracc/test/model/test_corpus.py", "file_name": "test_corpus.py", "file_ext": "py", "file_size_in_byte": 860, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pytest.mark.skipif", "line_number": 8, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pytest.config.getoption", "line_number": 9, "usage_type": "call"}, {"api_name": "pytest.config", "line_number": 9, "usage_type": "attribute"}, {"api_name": "model.corpus.Corpus", "line_number": 15, "usage_type": "call"}, {"api_name": "fixtures.tiny_corpus", "line_number": 15, "usage_type": "call"}, {"api_name": "model.corpus.Corpus", "line_number": 22, "usage_type": "call"}, {"api_name": "fixtures.sample_corpus", "line_number": 22, "usage_type": "call"}, {"api_name": "model.corpus.Corpus", "line_number": 33, "usage_type": "call"}, {"api_name": "fixtures.whole_corpus", "line_number": 33, "usage_type": "call"}, {"api_name": "pytest.mark.skipif", "line_number": 27, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 27, "usage_type": "attribute"}, {"api_name": "fixtures.whole_corpus", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "518118769", "text": "# -*- coding: utf-8 -*-\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm\nfrom openerp.tools.float_utils import float_round as round\nfrom openerp import workflow\nfrom openerp.tools.float_utils import float_compare\nimport time\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass sale_order(models.Model):\n\n _inherit = 'sale.order'\n\n use_invoice_plan = fields.Boolean(\n string='Use Invoice Plan',\n readonly=True,\n states={'draft': [('readonly', False)]},\n default=False,\n help=\"It indicates that the invoice has been sent.\",\n )\n invoice_plan_ids = fields.One2many(\n 'sale.invoice.plan',\n 'order_id',\n string='Invoice Plan',\n copy=True,\n readonly=True,\n states={'draft': [('readonly', False)],\n 'invoice_except': [('readonly', False)]},\n )\n invoice_plan_wd_ids = fields.One2many(\n 'sale.invoice.plan',\n 'order_id',\n string='Invoice Plan with Advance',\n copy=True,\n )\n use_deposit = fields.Boolean(\n string='Advance on 1st Invoice',\n readonly=True,\n )\n invoice_mode = fields.Selection(\n [('change_price', 'As 1 Job (change price)'),\n ('change_quantity', 'As Units (change quantity)')],\n string='Invoice Mode',\n requied=True,\n readonly=True,\n )\n\n @api.model\n def _calculate_subtotal(self, vals):\n if vals.get('invoice_plan_ids', False) or \\\n vals.get('invoice_plan_wd_ids', False):\n plan_ids = self.invoice_plan_ids or self.invoice_plan_wd_ids\n old_installment = 0\n subtotal = 0.0\n index_list = [] # Keep the subtotal line index\n i = 0\n for line in plan_ids:\n if line.installment > old_installment: # Start new installment\n if len(index_list) > 0:\n del index_list[-1] # Remove last index\n subtotal = 0.0\n index_list.append(i)\n if line.installment == 0:\n line.subtotal = 0.0\n else:\n subtotal += line.invoice_amount\n line.subtotal = subtotal\n old_installment = line.installment\n i += 1\n if len(index_list) > 0:\n del index_list[-1]\n # Now, delete subtotal not in the index_list\n for i in index_list:\n self.invoice_plan_ids[i].subtotal = 0.0\n\n @api.model\n def _validate_invoice_plan(self, vals):\n if vals.get('invoice_plan_ids', False):\n for line in vals.get('invoice_plan_ids'):\n # Deleting (2) line that is not being cancelled\n plan = self.env['sale.invoice.plan'].browse(line[1])\n if line[0] == 2: # Deletion\n plan = self.env['sale.invoice.plan'].browse(line[1])\n if plan.state and plan.state != 'cancel':\n raise except_orm(\n _('Delete Error!'),\n _(\"You are trying deleting line(s) \"\n \"that has not been cancelled!\\n\"\n \"Please discard change and try again!\"))\n\n # Don't know why, but can't use v8 API !!, so revert to v7\n def copy(self, cr, uid, id, default=None, context=None):\n default = default or {}\n order_id = super(sale_order, self).copy(cr, uid, id,\n default, context)\n order = self.browse(cr, uid, order_id)\n for invoice_plan in order.invoice_plan_ids:\n copy_to_line_id = invoice_plan.order_line_id and \\\n invoice_plan.order_line_id.copy_to_line_id.id\n self.pool.get('sale.invoice.plan').write(\n cr, uid, [invoice_plan.id],\n {'order_line_id': copy_to_line_id}, context)\n return order_id\n\n @api.multi\n def write(self, vals):\n for sale in self:\n sale._validate_invoice_plan(vals)\n res = super(sale_order, self).write(vals)\n for sale in self:\n sale._calculate_subtotal(vals)\n self.env['sale.invoice.plan']._validate_installment_date(\n self.invoice_plan_ids)\n return res\n\n @api.onchange('use_invoice_plan')\n def _onchange_use_invoice_plan(self):\n if self.use_invoice_plan:\n self.order_policy = 'manual'\n else:\n default_order_policy = self.env['ir.values'].get_default(\n 'sale.order', 'order_policy')\n self.order_policy = default_order_policy or 'manual'\n\n @api.one\n def _check_invoice_plan(self):\n if self.use_invoice_plan:\n # kittiu: problem with decimal, so we dicide to test with 0\n # obj_precision = self.env['decimal.precision']\n # prec = obj_precision.precision_get('Account')\n prec = 1\n # --\n for order_line in self.order_line:\n subtotal = self.price_include and \\\n order_line.product_uom_qty * order_line.price_unit or \\\n order_line.price_subtotal\n invoice_lines = self.env['sale.invoice.plan'].search(\n [('order_line_id', '=', order_line.id)])\n total_amount = 0.0\n for line in invoice_lines:\n total_amount += line.invoice_amount\n # Validate percent\n if round(line.invoice_percent / 100 * subtotal, prec) != \\\n round(line.invoice_amount, prec):\n raise except_orm(\n _('Invoice Plan Percent Mismatch!'),\n _(\"%s on installment %s\")\n % (order_line.name, line.installment))\n if round(total_amount, prec) != round(subtotal, prec):\n raise except_orm(\n _('Invoice Plan Amount Mismatch!'),\n _(\"%s, plan amount %s not equal to line amount %s!\")\n % (order_line.name,\n '{:,.2f}'.format(total_amount),\n '{:,.2f}'.format(subtotal)))\n return True\n\n @api.multi\n def action_button_confirm(self):\n assert len(self) == 1, \\\n 'This option should only be used for a single id at a time.'\n self._check_invoice_plan()\n super(sale_order, self).action_button_confirm()\n return True\n\n @api.multi\n def action_cancel_draft_invoices(self):\n assert len(self) == 1, \\\n 'This option should only be used for a single id at a time.'\n # Get all unpaid invoice\n for invoice in self.invoice_ids:\n if invoice.state in ('draft'):\n workflow.trg_validate(\n self._uid, 'account.invoice',\n invoice.id, 'invoice_cancel', self._cr)\n return True\n\n @api.model\n def _prepare_deposit_invoice_line(self, name, order, amount):\n company = self.env.user.company_id\n account_id = company.account_deposit_customer.id\n return {\n 'name': name,\n 'origin': order.name,\n 'user_id': order.user_id.id,\n 'account_id': account_id,\n 'price_unit': amount,\n 'quantity': 1.0,\n 'discount': False,\n 'uos_id': False,\n 'product_id': False,\n 'invoice_line_tax_id': [\n (6, 0, [x.id for x in order.order_line[0].tax_id])],\n 'account_analytic_id': order.project_id.id or False,\n }\n\n @api.multi\n def _create_deposit_invoice(self, percent, amount, date_invoice=False):\n for order in self:\n if amount:\n advance_label = 'Advance'\n name = _(\"%s of %s %%\") % (advance_label, percent)\n # create the invoice\n inv_line_values = \\\n self._prepare_deposit_invoice_line(name, order, amount)\n inv_values = self._prepare_invoice(order, inv_line_values)\n inv_values.update({'is_advance': True,\n 'date_invoice': date_invoice})\n # Chainging from [6, 0, ...] to [0, 0, ...]\n inv_values['invoice_line'] = [\n (0, 0, inv_values['invoice_line'][0][2])]\n inv_id = self.env[\n 'sale.advance.payment.inv']._create_invoices(inv_values,\n self.id)\n # Calculate due date\n invoice = self.env['account.invoice'].browse(inv_id)\n if date_invoice:\n data = invoice.onchange_payment_term_date_invoice(\n order.payment_term.id, date_invoice)\n else:\n data = invoice.onchange_payment_term_date_invoice(\n order.payment_term.id,\n time.strftime(DEFAULT_SERVER_DATE_FORMAT))\n if data.get('value', False):\n invoice.write(data['value'])\n return inv_id\n return False\n\n @api.multi\n def action_invoice_create(self, grouped=False,\n states=None, date_invoice=False):\n self._check_invoice_plan()\n # Mixed Invoice plan and grouping is not allowed.\n if grouped and (True in [order.use_invoice_plan for order in self]):\n raise except_orm(\n _('Warning'),\n _(\"Mix order and order with invoice plan is not allowed!\"))\n invoice_ids = []\n # Case use_invoice_plan, create multiple invoice by installment\n for order in self:\n first_time_invoice_plan = not order.invoice_ids and True or False\n if order.use_invoice_plan:\n plan_obj = self.env['sale.invoice.plan']\n installments = list(set([plan.installment\n for plan in order.invoice_plan_ids]))\n for installment in installments:\n # Getting invoice plan for each installment\n blines = plan_obj.search(\n [('installment', '=', installment),\n ('order_id', '=', order.id),\n ('state', 'in', [False, 'cancel'])])\n if blines:\n if installment == 0: # Deposit Case\n inv_id = self._create_deposit_invoice(\n blines[0].deposit_percent,\n blines[0].deposit_amount,\n blines[0].date_invoice)\n invoice_ids.append(inv_id)\n blines.write({'ref_invoice_id': inv_id})\n else:\n percent_dict = {}\n date_invoice = (blines and\n blines[0].date_invoice or\n False)\n for b in blines:\n percent_dict.update(\n {b.order_line_id: b.invoice_percent})\n order = order.with_context(\n installment=installment,\n invoice_plan_percent=percent_dict)\n inv_id = super(\n sale_order, order).action_invoice_create(\n grouped=grouped,\n states=states,\n date_invoice=date_invoice)\n invoice_ids.append(inv_id)\n blines.write({'ref_invoice_id': inv_id})\n else:\n inv_id = super(sale_order, order).action_invoice_create(\n grouped=grouped, states=states, date_invoice=date_invoice)\n invoice_ids.append(inv_id)\n order.with_context(first_time=first_time_invoice_plan).\\\n _action_invoice_create_hook(invoice_ids) # Special Hook\n return inv_id\n\n @api.model\n def _action_invoice_create_hook(self, invoice_ids):\n # Hook\n # Check total amount PO must equal to Invoice\n if self._context.get('first_time', False) and len(invoice_ids) > 0:\n self._cr.execute(\"\"\"\n select coalesce(sum(amount_untaxed), 0.0)\n from account_invoice where id in %s\n \"\"\", (tuple(invoice_ids), ))\n invoice_untaxed = self._cr.fetchone()[0]\n prec = self.env['decimal.precision'].precision_get('Account')\n if float_compare(invoice_untaxed, self.amount_untaxed,\n precision_digits=prec) != 0:\n raise except_orm(\n _('Amount mismatch!'),\n _('Total invoice amount, %s, not equal to sales '\n 'order amount, %s.\\nThis may be caused by quantity '\n 'rounding from invoice plan to invoice line.') %\n ('{:,.2f}'.format(invoice_untaxed),\n '{:,.2f}'.format(self.amount_untaxed)))\n return\n\n @api.model\n def _make_invoice(self, order, lines):\n inv_id = super(sale_order, self)._make_invoice(order, lines)\n if order.use_invoice_plan:\n invoice = self.env['account.invoice'].browse(inv_id)\n for line in invoice.invoice_line:\n if line.price_unit < 0: # Remove line with negative price line\n line.unlink()\n for deposit_inv in order.invoice_ids:\n if deposit_inv.state not in ('cancel',) and \\\n deposit_inv.is_advance:\n for preline in deposit_inv.invoice_line:\n ratio = (order.amount_untaxed and\n (invoice.amount_untaxed /\n order.amount_untaxed) or 1.0)\n inv_line = preline.copy(\n {'invoice_id': inv_id,\n 'price_unit': -preline.price_unit * ratio})\n inv_line.quantity = 1.0\n invoice.button_compute()\n return inv_id\n\n @api.multi\n def manual_invoice(self, context=None):\n # If use_invoice_plan, view invoices in list view.\n res = super(sale_order, self).manual_invoice()\n if self[0].use_invoice_plan:\n res = self.action_view_invoice()\n return res\n\n\nclass sale_order_line(models.Model):\n _inherit = 'sale.order.line'\n\n invoice_plan_ids = fields.One2many(\n 'sale.invoice.plan',\n 'order_line_id',\n string='Invoice Plan',\n readonly=True,\n )\n copy_from_line_id = fields.Many2one(\n 'sale.order.line',\n string=\"Copied from\",\n readonly=True,\n )\n copy_to_line_id = fields.Many2one(\n 'sale.order.line',\n string=\"Last copied to\",\n readonly=True,\n )\n\n def copy_data(self, cr, uid, id, default=None, context=None):\n default = dict(default or {})\n default.update({'copy_from_line_id': id, 'copy_to_line_id': False})\n return super(sale_order_line, self).copy_data(cr, uid, id,\n default, context=context)\n\n @api.model\n def create(self, vals):\n new_line = super(sale_order_line, self).create(vals)\n if new_line.copy_from_line_id:\n old_line = self.browse(new_line.copy_from_line_id.id)\n old_line.copy_to_line_id = new_line.id\n return new_line\n\n @api.model\n def _prepare_order_line_invoice_line(self, line, account_id=False):\n # Call super\n res = super(sale_order_line,\n self.with_context(force_ignore_line_percent=True)).\\\n _prepare_order_line_invoice_line(line, account_id)\n # For invoice plan\n invoice_plan_percent = self._context.get('invoice_plan_percent', False)\n if not res and invoice_plan_percent: # But if invoice plan, try again\n res = self._prepare_order_line_invoice_line_hook(line, account_id)\n if invoice_plan_percent:\n if line in invoice_plan_percent:\n if line.order_id.invoice_mode == 'change_quantity':\n res.update({'quantity': (res.get('quantity') or 0.0) *\n (line and invoice_plan_percent[line] or 0.0) /\n 100})\n elif line.order_id.invoice_mode == 'change_price':\n res.update({'price_unit': (res.get('price_unit') or 0.0) *\n (res.get('quantity') or 0.0) *\n (line and invoice_plan_percent[line] or 0.0) /\n 100,\n 'quantity': 1.0})\n else:\n return False\n # From invoice_percentage,\n line_percent = self._context.get('line_percent', False)\n if line_percent:\n res.update({'quantity': ((res.get('quantity') or 0.0) *\n (line_percent / 100))})\n return res\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n", "sub_path": "sale_invoice_plan/models/sale.py", "file_name": "sale.py", "file_ext": "py", "file_size_in_byte": 17583, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "openerp.models.Model", "line_number": 14, "usage_type": "attribute"}, {"api_name": "openerp.models", "line_number": 14, "usage_type": "name"}, {"api_name": "openerp.fields.Boolean", "line_number": 18, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 18, "usage_type": "name"}, {"api_name": "openerp.fields.One2many", "line_number": 25, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 25, "usage_type": "name"}, {"api_name": "openerp.fields.One2many", "line_number": 34, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 34, "usage_type": "name"}, {"api_name": "openerp.fields.Boolean", "line_number": 40, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 40, "usage_type": "name"}, {"api_name": "openerp.fields.Selection", "line_number": 44, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 44, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 52, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 52, "usage_type": "name"}, {"api_name": "openerp.exceptions.except_orm", "line_number": 89, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 90, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 91, "usage_type": "call"}, {"api_name": "openerp.api.model", "line_number": 80, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 80, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 109, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 109, "usage_type": "name"}, {"api_name": "openerp.api.onchange", "line_number": 120, "usage_type": "call"}, {"api_name": "openerp.api", "line_number": 120, "usage_type": "name"}, {"api_name": "openerp.tools.float_utils.float_round", "line_number": 147, "usage_type": "call"}, {"api_name": "openerp.tools.float_utils.float_round", "line_number": 148, "usage_type": "call"}, {"api_name": "openerp.exceptions.except_orm", "line_number": 149, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 150, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 151, "usage_type": "call"}, {"api_name": "openerp.tools.float_utils.float_round", "line_number": 153, "usage_type": "call"}, {"api_name": "openerp.exceptions.except_orm", "line_number": 154, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 155, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 156, "usage_type": "call"}, {"api_name": "openerp.api.one", "line_number": 129, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 129, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 162, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 162, "usage_type": "name"}, {"api_name": "openerp.workflow.trg_validate", "line_number": 177, "usage_type": "call"}, {"api_name": "openerp.workflow", "line_number": 177, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 170, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 170, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 182, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 182, "usage_type": "name"}, {"api_name": "openerp._", "line_number": 206, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 227, "usage_type": "call"}, {"api_name": "openerp.tools.DEFAULT_SERVER_DATE_FORMAT", "line_number": 227, "usage_type": "argument"}, {"api_name": "openerp.api.multi", "line_number": 201, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 201, "usage_type": "name"}, {"api_name": "openerp.exceptions.except_orm", "line_number": 239, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 240, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 241, "usage_type": "call"}, {"api_name": "openerp.api.multi", "line_number": 233, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 233, "usage_type": "name"}, {"api_name": "openerp.tools.float_utils.float_compare", "line_number": 301, "usage_type": "call"}, {"api_name": "openerp.exceptions.except_orm", "line_number": 303, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 304, "usage_type": "call"}, {"api_name": "openerp._", "line_number": 305, "usage_type": "call"}, {"api_name": "openerp.api.model", "line_number": 290, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 290, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 312, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 312, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 334, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 334, "usage_type": "name"}, {"api_name": "openerp.models.Model", "line_number": 343, "usage_type": "attribute"}, {"api_name": "openerp.models", "line_number": 343, "usage_type": "name"}, {"api_name": "openerp.fields.One2many", "line_number": 346, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 346, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 352, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 352, "usage_type": "name"}, {"api_name": "openerp.fields.Many2one", "line_number": 357, "usage_type": "call"}, {"api_name": "openerp.fields", "line_number": 357, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 369, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 369, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 377, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 377, "usage_type": "name"}]} +{"seq_id": "345644719", "text": "'''\r\nCreated on Oct 22, 2015\r\n\r\n@author: wujz\r\n'''\r\n# -*- coding: utf-8 -*- \r\nimport math\r\nimport json\r\nimport urllib.request\r\nfrom common.JSONObj import JSONObj\r\n\r\nclass GithubApiInfoObj:\r\n GITHUB_API_URL = \"https://api.github.com/orgs/ibmpredictiveanalytics/repos?page={0}&per_page={1}\"\r\n MAX_REPO_NUM = 1000\r\n PER_PAGE = 100 \r\n KEY_LIST = ['repository','description','pushed_at']\r\n REPOSITORY, DESCRIPTION, PUSHED_AT = 0,1,2\r\n \r\n def __init__(self):\r\n self.item_list = []\r\n for page_index in range(1, math.floor(GithubApiInfoObj.MAX_REPO_NUM/GithubApiInfoObj.PER_PAGE)+1): \r\n try:\r\n pageName = GithubApiInfoObj.GITHUB_API_URL.format(page_index,GithubApiInfoObj.PER_PAGE)\r\n api_json_data = json.loads(urllib.request.urlopen(pageName).read().decode('utf-8'))\r\n except:\r\n raise Exception(\"Cannot request data from github api: '\"+pageName+\"'.\\n\")\r\n \r\n if len(api_json_data) == 0:\r\n break\r\n \r\n for item in api_json_data: \r\n temp_json_list = []\r\n #ignore .io repository\r\n if('IBMPredictiveAnalytics.github.io' == item['name']):\r\n continue \r\n for key in GithubApiInfoObj.KEY_LIST:\r\n if key == 'repository':\r\n key_name_in_api = 'name'\r\n else:\r\n key_name_in_api= key\r\n \r\n if item[key_name_in_api] is None:\r\n item[key_name_in_api] = \"\"\r\n\r\n try:\r\n temp_json_list.append(JSONObj(key, item[key_name_in_api].strip())) \r\n except:\r\n raise Exception(\"Github api (\"+GithubApiInfoObj.GITHUB_API_URL+\") does not provide information of \"+key+\". Please check!\\n\")\r\n \r\n self.item_list.append(temp_json_list) \r\n", "sub_path": "CreatePackage/CreateExtensionIndex/GithubApiInfoObj.py", "file_name": "GithubApiInfoObj.py", "file_ext": "py", "file_size_in_byte": 2023, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "math.floor", "line_number": 21, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 24, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 24, "usage_type": "name"}, {"api_name": "common.JSONObj.JSONObj", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "199589735", "text": "import csv\nimport os\nimport glob\nimport numpy as np\nimport pymongo\nimport json\nimport argparse\nimport traceback\nimport datetime\nimport pytz\nfrom numba import jit\nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\n\n\n''' load config and secrets '''\nwith open('/app/config.json') as cjson:\n config = json.load(cjson)\n\nwith open('/app/secrets.json') as sjson:\n secrets = json.load(sjson)\n\nfor k in secrets:\n config[k].update(secrets.get(k, {}))\n\n\ndef utc_now():\n return datetime.datetime.now(pytz.utc)\n\n\ndef connect_to_db():\n \"\"\" Connect to the mongodb database\n\n :return:\n \"\"\"\n try:\n # there's only one instance of DB, it's too big to be replicated\n _client = pymongo.MongoClient(host=config['database']['host'],\n port=config['database']['port'])\n # grab main database:\n _db = _client[config['database']['db']]\n except Exception as _e:\n raise ConnectionRefusedError\n try:\n # authenticate\n _db.authenticate(config['database']['user'], config['database']['pwd'])\n except Exception as _e:\n raise ConnectionRefusedError\n\n return _client, _db\n\n\ndef insert_db_entry(_db, _collection=None, _db_entry=None):\n \"\"\"\n Insert a document _doc to collection _collection in DB.\n It is monitored for timeout in case DB connection hangs for some reason\n :param _collection:\n :param _db_entry:\n :return:\n \"\"\"\n assert _collection is not None, 'Must specify collection'\n assert _db_entry is not None, 'Must specify document'\n try:\n _db[_collection].insert_one(_db_entry)\n except Exception as _e:\n print('Error inserting {:s} into {:s}'.format(str(_db_entry['_id']), _collection))\n traceback.print_exc()\n print(_e)\n\n\ndef insert_multiple_db_entries(_db, _collection=None, _db_entries=None):\n \"\"\"\n Insert a document _doc to collection _collection in DB.\n It is monitored for timeout in case DB connection hangs for some reason\n :param _db:\n :param _collection:\n :param _db_entries:\n :return:\n \"\"\"\n assert _collection is not None, 'Must specify collection'\n assert _db_entries is not None, 'Must specify documents'\n try:\n _db[_collection].insert_many(_db_entries, ordered=False)\n except pymongo.errors.BulkWriteError as bwe:\n print(bwe.details)\n except Exception as _e:\n traceback.print_exc()\n print(_e)\n\n\n@jit\ndef deg2hms(x):\n \"\"\"Transform degrees to *hours:minutes:seconds* strings.\n\n Parameters\n ----------\n x : float\n The degree value c [0, 360) to be written as a sexagesimal string.\n\n Returns\n -------\n out : str\n The input angle written as a sexagesimal string, in the\n form, hours:minutes:seconds.\n\n \"\"\"\n assert 0.0 <= x < 360.0, 'Bad RA value in degrees'\n # ac = Angle(x, unit='degree')\n # hms = str(ac.to_string(unit='hour', sep=':', pad=True))\n # print(str(hms))\n _h = np.floor(x * 12.0 / 180.)\n _m = np.floor((x * 12.0 / 180. - _h) * 60.0)\n _s = ((x * 12.0 / 180. - _h) * 60.0 - _m) * 60.0\n hms = '{:02.0f}:{:02.0f}:{:07.4f}'.format(_h, _m, _s)\n # print(hms)\n return hms\n\n\n@jit\ndef deg2dms(x):\n \"\"\"Transform degrees to *degrees:arcminutes:arcseconds* strings.\n\n Parameters\n ----------\n x : float\n The degree value c [-90, 90] to be converted.\n\n Returns\n -------\n out : str\n The input angle as a string, written as degrees:minutes:seconds.\n\n \"\"\"\n assert -90.0 <= x <= 90.0, 'Bad Dec value in degrees'\n # ac = Angle(x, unit='degree')\n # dms = str(ac.to_string(unit='degree', sep=':', pad=True))\n # print(dms)\n _d = np.floor(abs(x)) * np.sign(x)\n _m = np.floor(np.abs(x - _d) * 60.0)\n _s = np.abs(np.abs(x - _d) * 60.0 - _m) * 60.0\n dms = '{:02.0f}:{:02.0f}:{:06.3f}'.format(_d, _m, _s)\n # print(dms)\n return dms\n\n\ndef process_file(_file, _collection, _batch_size=2048, verbose=False, _dry_run=False):\n\n # connect to MongoDB:\n if verbose:\n print('Connecting to DB')\n _client, _db = connect_to_db()\n if verbose:\n print('Successfully connected')\n\n print(f'processing {_file}')\n documents = []\n batch_num = 1\n\n # column names:\n column_names = [('ID', int),\n ('version', str),\n ('HIP', int),\n ('TYC', str),\n ('UCAC', str),\n ('TWOMASS', str),\n ('SDSS', int),\n ('ALLWISE', str),\n ('GAIA', str),\n ('APASS', str),\n ('KIC', int),\n ('objType', str),\n ('typeSrc', str),\n ('ra', float),\n ('dec', float),\n ('POSflag', str),\n ('pmRA', float),\n ('e_pmRA', float),\n ('pmDEC', float),\n ('e_pmDEC', float),\n ('PMflag', str),\n ('plx', float),\n ('e_plx', float),\n ('PARflag', str),\n ('gallong', float),\n ('gallat', float),\n ('eclong', float),\n ('eclat', float),\n ('Bmag', float),\n ('e_Bmag', float),\n ('Vmag', float),\n ('e_Vmag', float),\n ('umag', float),\n ('e_umag', float),\n ('gmag', float),\n ('e_gmag', float),\n ('rmag', float),\n ('e_rmag', float),\n ('imag', float),\n ('e_imag', float),\n ('zmag', float),\n ('e_zmag', float),\n ('Jmag', float),\n ('e_Jmag', float),\n ('Hmag', float),\n ('e_Hmag', float),\n ('Kmag', float),\n ('e_Kmag', float),\n ('TWOMflag', str),\n ('prox', float),\n ('w1mag', float),\n ('e_w1mag', float),\n ('w2mag', float),\n ('e_w2mag', float),\n ('w3mag', float),\n ('e_w3mag', float),\n ('w4mag', float),\n ('e_w4mag', float),\n ('GAIAmag', float),\n ('e_GAIAmag', float),\n ('Tmag', float),\n ('e_Tmag', float),\n ('TESSflag', str),\n ('SPFlag', str),\n ('Teff', float),\n ('e_Teff', float),\n ('logg', float),\n ('e_logg', float),\n ('MH', float),\n ('e_MH', float),\n ('rad', float),\n ('e_rad', float),\n ('mass', float),\n ('e_mass', float),\n ('rho', float),\n ('e_rho', float),\n ('lumclass', str),\n ('lum', float),\n ('e_lum', float),\n ('d', float),\n ('e_d', float),\n ('ebv', float),\n ('e_ebv', float),\n ('numcont', int),\n ('contratio', float),\n ('disposition', str),\n ('duplicate_i', int),\n ('priority', float),\n ('objID', int)]\n\n try:\n with open(_file) as f:\n reader = csv.reader(f, delimiter=',')\n # skip header:\n f.readline()\n for row in reader:\n try:\n doc = {column_name[0]: val for column_name, val in zip(column_names, row)}\n\n doc['_id'] = doc['ID']\n\n # convert\n for col_name, col_type in column_names:\n try:\n if doc[col_name] == 'NOT_AVAILABLE':\n continue\n elif doc[col_name] in ('false', 'true'):\n doc[col_name] = eval(doc[col_name].capitalize())\n elif len(doc[col_name]) == 0:\n doc[col_name] = None\n else:\n doc[col_name] = col_type(doc[col_name])\n except Exception as e:\n traceback.print_exc()\n print(e)\n\n # print(doc)\n # print('\\n')\n\n doc['coordinates'] = {}\n # doc['coordinates']['epoch'] = doc['ref_epoch']\n _ra = doc['ra']\n _dec = doc['dec']\n _radec = [_ra, _dec]\n # string format: H:M:S, D:M:S\n # tic = time.time()\n _radec_str = [deg2hms(_ra), deg2dms(_dec)]\n # print(time.time() - tic)\n # print(_radec_str)\n doc['coordinates']['radec_str'] = _radec_str\n # for GeoJSON, must be lon:[-180, 180], lat:[-90, 90] (i.e. in deg)\n _radec_geojson = [_ra - 180.0, _dec]\n doc['coordinates']['radec_geojson'] = {'type': 'Point',\n 'coordinates': _radec_geojson}\n # radians:\n doc['coordinates']['radec_rad'] = [_ra * np.pi / 180.0, _dec * np.pi / 180.0]\n doc['coordinates']['radec_deg'] = [_ra, _dec]\n\n # print(doc['coordinates'])\n\n documents.append(doc)\n\n # time.sleep(1)\n\n # insert batch, then flush\n if len(documents) == _batch_size:\n print(f'inserting batch #{batch_num}')\n if not _dry_run:\n insert_multiple_db_entries(_db, _collection=_collection, _db_entries=documents)\n # flush:\n documents = []\n batch_num += 1\n\n except Exception as e:\n traceback.print_exc()\n print(e)\n continue\n\n except Exception as e:\n traceback.print_exc()\n print(e)\n\n # stuff left from the last file?\n if len(documents) > 0:\n print(f'inserting batch #{batch_num}')\n if not _dry_run:\n insert_multiple_db_entries(_db, _collection=_collection, _db_entries=documents)\n\n # disconnect from db:\n try:\n _client.close()\n finally:\n if verbose:\n print('Successfully disconnected from db')\n\n\nif __name__ == '__main__':\n ''' Create command line argument parser '''\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description='')\n\n parser.add_argument('--dryrun', action='store_true', help='enforce execution')\n\n args = parser.parse_args()\n\n dry_run = args.dryrun\n\n # connect to MongoDB:\n print('Connecting to DB')\n client, db = connect_to_db()\n print('Successfully connected')\n\n collection = 'TIC_7'\n\n # create 2d index: [placeholder]\n print('Creating 2d index')\n if not dry_run:\n db[collection].create_index([('coordinates.radec_geojson', '2dsphere'),\n ('_id', pymongo.ASCENDING)], background=True)\n\n # number of records to insert\n batch_size = 4096\n\n _location = '/_tmp/tic_7/'\n\n files = glob.glob(os.path.join(_location, 'tic_dec*.csv'))\n\n print(f'# files to process: {len(files)}')\n\n # init threaded operations\n # pool = ThreadPoolExecutor(2)\n pool = ProcessPoolExecutor(10)\n\n # for ff in files[::-1]:\n for ff in sorted(files):\n pool.submit(process_file, _file=ff, _collection=collection, _batch_size=batch_size,\n verbose=True, _dry_run=dry_run)\n # process_file(_file=ff, _collection=collection, _batch_size=batch_size,\n # verbose=True, _dry_run=dry_run)\n\n # wait for everything to finish\n pool.shutdown(wait=True)\n\n # # create 2d index:\n # print('Creating 2d index')\n # if not dry_run:\n # db[collection].create_index([('coordinates.radec_geojson', '2dsphere')], background=True)\n\n print('All done')\n", "sub_path": "kowalski/dev/ingest_tic_7.py", "file_name": "ingest_tic_7.py", "file_ext": "py", "file_size_in_byte": 12666, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 18, "usage_type": "call"}, {"api_name": "json.load", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pytz.utc", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pymongo.MongoClient", "line_number": 38, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 67, "usage_type": "call"}, {"api_name": "pymongo.errors", "line_number": 84, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 112, "usage_type": "call"}, {"api_name": "numba.jit", "line_number": 91, "usage_type": "name"}, {"api_name": "numpy.floor", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 140, "usage_type": "call"}, {"api_name": "numba.jit", "line_number": 119, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 252, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 273, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 295, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 314, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 319, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 338, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 338, "usage_type": "attribute"}, {"api_name": "pymongo.ASCENDING", "line_number": 358, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 365, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 365, "usage_type": "call"}, {"api_name": "os.path", "line_number": 365, "usage_type": "attribute"}, {"api_name": "concurrent.futures.ProcessPoolExecutor", "line_number": 371, "usage_type": "call"}]} +{"seq_id": "204712228", "text": "from collections import deque, defaultdict\nimport random\nimport numpy as np\nimport csv\n\nfrom Dsatur import Dsatur\nclass SWO:\n def __init__(self,graph):\n self.graph = graph\n \n def squeaky_wheel_opt(self):\n graph = self.graph.copy()\n max_value = 10000000\n blame = defaultdict(list)\n alpha = 0.9\n b = 2\n best_solution = defaultdict(list)\n \n for i in range(0,100):\n print(\"iteration :\",i)\n# print(\"iteration :\",i)\n obj = Dsatur(graph)\n colored_graph,cur_value = obj.dsatur()\n # pen_val = Penalty(stu_to_sub,colored_graph).find_penalty()\n # print(\"max_value:\",max_value)\n # print(\"penalty:\",pen_val)\n if cur_value <= max_value:\n max_value = cur_value\n best_solution = colored_graph.copy()\n for j in range(0,len(graph)):\n blame[j] = j\n if colored_graph[j] > alpha*cur_value:\n blame[j] = blame[j] + b\n blame = {k: v for k, v in sorted(blame.items(), key=lambda item: item[1],reverse = True)}\n # print(blame)\n temp = defaultdict(list)\n for key,value in blame.items():\n temp[key] = graph[key].copy()\n graph = temp.copy()\n \n return max_value,best_solution", "sub_path": "AI/Offline 2/.ipynb_checkpoints/SWO-checkpoint.py", "file_name": "SWO-checkpoint.py", "file_ext": "py", "file_size_in_byte": 1372, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "collections.defaultdict", "line_number": 14, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 17, "usage_type": "call"}, {"api_name": "Dsatur.Dsatur", "line_number": 22, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "240455474", "text": "\"\"\"\nThis module takes care of starting the API Server, Loading the DB and Adding the endpoints\n\"\"\"\nimport os\nfrom flask import Flask, request, jsonify, url_for\nfrom flask_migrate import Migrate\nfrom flask_swagger import swagger\nfrom flask_cors import CORS\nfrom utils import APIException, generate_sitemap\nfrom admin import setup_admin\nfrom models import db, User\nfrom datastructures import FamilyStructure\n#from models import Person\n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\n# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n# MIGRATE = Migrate(app, db)\n# db.init_app(app)\nCORS(app)\n# setup_admin(app)\n\nsmith_family = FamilyStructure(\"Smith\")\n\n# Handle/serialize errors like a JSON object\n@app.errorhandler(APIException)\ndef handle_invalid_usage(error):\n return jsonify(error.to_dict()), error.status_code\n\n# generate sitemap with all your endpoints\n@app.route('/')\ndef sitemap():\n return generate_sitemap(app)\n\n@app.route('/members')\ndef create_family_tree():\n members = smith_family.getAllMembers()\n grandparent = members[0]\n parent_1 = smith_family.createFamilyMember(1, \"Allan\", 40, (grandparent['0_id']), \"Joe\")\n p_1_child_1 = smith_family.createFamilyMember(3, \"Zoey\", 21, (parent_1['0_id']), \"Allan\")\n p_1_child_2 = smith_family.createFamilyMember(5, \"Van\", 17, (parent_1['0_id']), \"Allan\")\n parent_2 = smith_family.createFamilyMember(2, \"Eric\", 38, (grandparent['0_id']), \"Joe\")\n p_2_child_1 = smith_family.createFamilyMember(4, \"Luke\", 19, (parent_2['0_id']), \"Eric\")\n p_2_child_2 = smith_family.createFamilyMember(6, \"Hailey\", 16, (parent_2['0_id']), \"Eric\")\n family_tree = smith_family.getAllMembers()\n return jsonify(family_tree), 200\n\n# this only runs if `$ python src/main.py` is executed\nif __name__ == '__main__':\n PORT = int(os.environ.get('PORT', 3000))\n app.run(host='0.0.0.0', port=PORT, debug=False)\n", "sub_path": "src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1963, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 21, "usage_type": "call"}, {"api_name": "datastructures.FamilyStructure", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 29, "usage_type": "call"}, {"api_name": "utils.APIException", "line_number": 27, "usage_type": "argument"}, {"api_name": "utils.generate_sitemap", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 47, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 51, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 51, "usage_type": "attribute"}]} +{"seq_id": "374992044", "text": "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.patches as mpatches\nimport numpy as np\n\n\"\"\"\narr = np.array([[0.73, 0.14, 0.08, 0.03], [0.32, 0.47, 0.10, 0.09], [0.18, 0.11, 0.56, 0.14], [0.09, 0.10, 0.13, 0.66]])\n\ndf_cm = pd.DataFrame(arr, index = [i for i in ['0->0', '0->1', '1->0', '1->1']],\n columns = [i for i in ['0->0', '0->1', '1->0', '1->1']])\n\nsns.set(font_scale=1.5)\nsns.heatmap(df_cm, annot=True, cmap='Blues', fmt='g', cbar_kws={'label': 'percentage of labels in particular class'}, vmin=0, vmax=1)\nplt.title(\"Prediction results of SVM with rbf-kernel\")\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.tight_layout()\nplt.show()\n\"\"\"\n#https://stackoverflow.com/questions/28356359/one-colorbar-for-seaborn-heatmaps-in-subplot\n\narr = np.array([[0.73, 0.14, 0.08, 0.03], [0.32, 0.47, 0.1, 0.09], [0.18, 0.11, 0.56, 0.14], [0.09, 0.1, 0.13, 0.66]])\n\n\n\ndf_cm = pd.DataFrame(arr, index = [i for i in ['0->0', '0->1', '1->0', '1->1']],\n columns = [i for i in ['0->0', '0->1', '1->0', '1->1']])\n\nsns.set(font_scale=1.3)\nsns.heatmap(df_cm, annot=True, cmap='Blues', fmt='g', cbar_kws={'label': 'row-wise percentage'}, vmin=0, vmax=1)\nplt.title(\"Prediction results of SVM with rbf-kernel\")\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.tight_layout()\nplt.show()\n\n\n\ndf = pd.DataFrame([[0.2961, 0.9585]], columns=[\"2\", \"20\"])\nsns.set(font_scale=1.8)\nsns.barplot(data=df, orient = 'h')\nplt.xlabel(\"total variance of components\")\nplt.ylabel(\"Number of principle components\")\nplt.title(\"Used principle components and their explained variance\")\nplt.show()\n", "sub_path": "Skripte/Plots_v2.py", "file_name": "Plots_v2.py", "file_ext": "py", "file_size_in_byte": 1655, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 27, "usage_type": "call"}, {"api_name": "seaborn.set", "line_number": 30, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 40, "usage_type": "call"}, {"api_name": "seaborn.set", "line_number": 41, "usage_type": "call"}, {"api_name": "seaborn.barplot", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}]} +{"seq_id": "24967185", "text": "\"\"\" Version 2.1a Ultimate Brick (stable)\nAnderson Ang Wei Jian and Qingyun Liu\n\nUses trivial graphical tiles to create a game environment -\nthe objective is to spawn an environment with tiles and sprites using non-trivial\ncode (with interaction elements)\n\nChangelog: (Total hours: 32 hours minimum, 40 hours maximum)\n\n- Version 1.0 (base game) (complete)\nIncludes:\n - Basic sprite formation (ball, player bar, blocks)\n - Level randomization (block position, color)\n - Ball spawn randomization (position)\n\n- Version 1.1 (estimated 13 hours) (complete)\nIncludes:\n - Sound support (bgm, interactive)\n - Controller interaction (keyboard input)\n - Collision physics\n - Bar + Ball physics\n - Ball + Block physics\n - Screen edge detection\n - Ball + edge physics\n - Sprite motion (ball & bar)\n - Add game_over flash screen\n\n- Version 1.2 (est. 6 hours) (complete)\n - Multi-face playablility\n - Bar + edge physics\n - Reform code grid into MVC format\n\n- Version 2.0 (est. 4 hours) (complete)\n - Randomized ball trajectory at game's start (upwards and downwards) (fair play consideration)\n - Fixed game over mechanics for Player 2\n - Sound support for 2P\n\n-------------- T.M.V.P (Team's Minimum Viable) : \"we have tall expectations\" ---------\n\n- Version 2.1 (est. 9 hours) (complete)\n - Support 2P generation (multiplayer)\n - Develop competitive elements (inter-player sprite interaction)\n - Addition of flash screen for instructions\n - In-game restart capability\n - Movespeed for players changed to 20 pixels/tick, to balance gameplay.\n - Complete classic game mode functionalities\n\n- Stretch goal: Version 3.0 (est. 4 + 4 hours) (CANCELLED)\n - Effect tiles (shortens tile length, lengthen tile's length, speed up/down ball)\n - Multiple game modes (Time attack, Classic, Point Rush)\n\n------------ THIS IS A STABLE VERSION. -------------------------\n\n\"\"\"\n\n# Libraries\nimport math\nimport pygame\nimport random\n\n# Colors (for bar and ball only)\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nred = (255,0,0)\nblue = (0,0,255)\n\n\n# Block sizes\nblock_width = 23\nblock_height = 15\n\n# Number of players\nplayercount = 2\n\n# Height and width of screen\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\n\n## MODEL ##\n\nclass Block(pygame.sprite.Sprite):\n \"\"\"This class represents each block that will get knocked out by the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n\n def __init__(self, color, x, y):\n \"\"\" Constructor. Passes in the color of the block,\n and its x and y position. \"\"\"\n\n # Call the parent class (Sprite) constructor\n super(Block,self).__init__()\n\n # Create the image of the block of appropriate size\n # The width and height are sent as a list for the first parameter.\n self.image = pygame.Surface([block_width, block_height])\n\n # Fill the image with the appropriate color\n self.image.fill(color)\n\n # Fetch the rectangle object that has the dimensions of the image\n self.rect = self.image.get_rect()\n\n # Move the top left of the rectangle to x,y.\n # This is where our block will appear..\n self.rect.x = x\n self.rect.y = y\n\n\nclass Ball(pygame.sprite.Sprite):\n \"\"\" This class represents the ball\n It derives from the \"Sprite\" class in Pygame \"\"\"\n\n # Speed in pixels per cycle\n speed = 10.0\n\n # Floating point representation of where the ball spawns\n # Alternates between spawning from left/right of screen\n x = float(random.randrange(0,801,799))\n # Varies between the top 1/3rd to the lower 1/3rd of the screen height\n y = float(random.randint(120, 280))\n\n # Initial direction of ball (in degrees)\n # Spawns either at 30 degrees (upwards trajectory)\n # or 150 degrees (downwards trajectory)\n direction = random.randrange(30,151,120)\n\n width = 10\n height = 10\n\n # Constructor. Pass in the color of the block, and its x and y position\n def __init__(self):\n # Call the parent class (Sprite) constructor\n super(Ball, self).__init__()\n\n # Create the image of the ball\n self.image = pygame.Surface([self.width, self.height])\n\n # Color the ball\n self.image.fill(white)\n\n # Get a rectangle object that shows where our image is\n self.rect = self.image.get_rect()\n\n # Get attributes for the height/width of the screen\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n\n def bounce(self, diff):\n \"\"\" This function will bounce the ball\n off surfaces (Controller-model interface 2) \"\"\"\n\n self.direction = (180 - self.direction) % 360\n self.direction -= diff\n\n def update(self):\n \"\"\" Update the position of the ball. (Controller-Model interface) \"\"\"\n # Sine and Cosine work in degrees, so we have to convert them\n direction_radians = math.radians(self.direction)\n\n # Change the position (x and y) according to the speed and direction\n self.x += self.speed * math.sin(direction_radians)\n self.y -= self.speed * math.cos(direction_radians)\n\n ## Classic implementation\n # Move the image to where our x and y are\n self.rect.x = self.x\n self.rect.y = self.y\n\n # Do we bounce off the left of the screen?\n if self.x <= 0:\n self.direction = (360 - self.direction) % 360\n self.x = 1\n\n # Do we bounce of the right side of the screen?\n if self.x > self.screenwidth - self.width:\n self.direction = (360 - self.direction) % 360\n self.x = self.screenwidth - self.width - 1\n\n # Did we fall off the bottom edge of the screen?\n if self.y > 600:\n return True\n\n ## Version 2.0 (2P-enabled)\n # Do we \"fall\" off the top of the screen?\n if self.y <= 0:\n return True\n\nclass Player(pygame.sprite.Sprite):\n \"\"\" This class represents the bar(s) that the\n player(s) controls. \"\"\"\n\n def __init__(self,color,x,y):\n \"\"\" View Constructor for player creation. Passes in color of bar, x and y location \"\"\"\n # Call the parent's constructor\n super(Player, self).__init__()\n\n self.width = 75\n self.height = 15\n\n # Create and claims surface geometry and color\n self.image = pygame.Surface([self.width, self.height])\n self.image.fill((color))\n\n # Make the rect from the passed-in location.\n self.rect = self.image.get_rect()\n self.screenheight = pygame.display.get_surface().get_height()\n self.screenwidth = pygame.display.get_surface().get_width()\n\n self.rect.x = x\n self.rect.y = self.screenheight-y\n\n\n def update(self, xdiff):\n \"\"\" Acts as the controller-model interface for the player's bar \"\"\"\n # Set the left side of the player bar according to player input\n self.rect.x += xdiff\n\n ## Classic implementation\n\n # Right limit for paddle\n if self.rect.x > self.screenwidth - self.width:\n self.rect.x = self.screenwidth - self.width\n\n # Left limit for paddle\n if self.rect.x < 0:\n self.rect.x = 0\n\n# Splash integration - v2.0 (fixed)\ndef drawPressKeyMsg(screen,font):\n \"\"\" Draws auxiliary message on the splash screen\"\"\"\n pressKeySurf = font.render('Press any key to play.', True, white)\n pressKeyRect = pressKeySurf.get_rect()\n pressKeyRect.topleft = (SCREEN_WIDTH - 250, SCREEN_HEIGHT - 30)\n screen.blit(pressKeySurf, pressKeyRect)\n\ndef checkForKeyPress():\n \"\"\" Function detects keypresses for termination or continuation\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.display.quit()\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.display.quit()\n pygame.quit()\n quit()\n else:\n return event.key\n\ndef showStartScreen(screen,font,clock):\n \"\"\" Creates a splash screen to buffer the start of gameplay\"\"\"\n # Creates title font\n titleFont = pygame.font.Font(None, 100)\n titleSurf1 = titleFont.render('ULTIMATE BRICKS!', True, white)\n\n degrees1 = 0\n degrees2 = 0\n\n while True:\n screen.fill(black)\n rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)\n rotatedRect1 = rotatedSurf1.get_rect()\n rotatedRect1.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n screen.blit(rotatedSurf1, rotatedRect1)\n\n drawPressKeyMsg(screen,font)\n if checkForKeyPress():\n pygame.event.get() # clear event queue\n return\n\n pygame.display.update()\n\n clock.tick(30)\n # rotate font by 3 degree each cycle\n degrees1 += 3\n\n# In-game restart mechanism - fixed in v2.1a\ndef restartprompt(screen):\n \"\"\" Creates a interactive dialog that allows the user to restart within the game\"\"\"\n # Fonts for restart prompt\n bigfont = pygame.font.Font(None,80)\n smallfont = pygame.font.Font(None,45)\n\n\n text = bigfont.render(\"press R to restart\", 13, (0, 0, 0))\n textx = SCREEN_WIDTH / 2 - text.get_width() / 2\n texty = SCREEN_HEIGHT / 2+100 - text.get_height() / 2\n textx_size = text.get_width()\n texty_size = text.get_height()\n pygame.draw.rect(screen, (255, 255, 255), ((textx - 5, texty -95),\n (textx_size + 10, texty_size)))\n\n screen.blit(text, (SCREEN_WIDTH / 2 - text.get_width() / 2,\n SCREEN_HEIGHT / 2 - text.get_height() / 2))\n\n## VIEW ##\ndef main():\n # Call this function so the Pygame library can initialize itself\n pygame.init()\n\n # Create an 800x600 sized screen\n screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT ])\n\n # Set the title of the window\n pygame.display.set_caption('Ultimate Brick')\n\n # Enable this to make the mouse disappear when over our window\n pygame.mouse.set_visible(0)\n\n # Font for game_over\n font = pygame.font.Font(None, 36)\n\n # Clock to limit speed\n clock = pygame.time.Clock()\n\n # Splash screen appears - function takes in screen, font, and pygame clock\n showStartScreen(screen,font,clock)\n\n # Create a surface we can draw on\n background = pygame.Surface(screen.get_size())\n\n # Create sprite lists\n blocks = pygame.sprite.Group()\n balls = pygame.sprite.Group()\n players = pygame.sprite.Group()\n allsprites = pygame.sprite.Group()\n\n # Create the player paddle objects\n if playercount == 2:\n player = Player(red, 0, 15)\n player2 = Player(blue, (800-75), 600)\n players.add(player)\n players.add(player2)\n allsprites.add(player)\n allsprites.add(player2)\n else:\n player = Player(white,0,15)\n players.add(player)\n allsprites.add(player)\n\n # Positional start points for Player bars\n x_position=0\n xx_position=780\n\n y_position=580\n yy_position=600\n\n x_move = 0\n x2_move = 0\n x2_position=650\n\n y2_position=0\n xx2_position=0\n yy2_position=-150\n\n # Create the ball\n ball = Ball()\n allsprites.add(ball)\n balls.add(ball)\n\n # The top of the block (y position)\n top = 160\n\n # Number of blocks to create\n blockcount = 28\n # Number of rows to create\n rowcount = random.randint(2,8)\n\n ## Create blocks\n\n # Range controls the number of rows\n for row in range(rowcount):\n # 28 columns with a max diff of 28-8-4 = 16\n for column in range(random.randint(2,8), blockcount - random.randint(0,4)):\n # Create a block (color,x,y)\n # randint starts at 80 to create brighter hues\n rainbow = (random.randint(100,255), random.randint(90,255), random.randint(90,250))\n block = Block(rainbow, column * (block_width + 2 ) + 1, top)\n blocks.add(block)\n allsprites.add(block)\n # Starts at the next row\n top += block_height + 2\n\n\n # Is the game over?\n game_over = False\n\n # Exit the program?\n exit_program = False\n\n # Plays the BGM on launch\n pygame.mixer.music.load(\"BGM2.mp3\")\n pygame.mixer.music.play(-1)\n\n # Collision sounds\n collide_sound = pygame.mixer.Sound(\"Collide.mp3\")\n\n\n ## CONTROLLER ##\n while not exit_program:\n\n # Limit to 30 fps\n clock.tick(30)\n\n # Clear the screen\n screen.fill(black)\n\n # Process the events in the game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_program = True\n pygame.display.quit()\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_move = -20\n if event.key == pygame.K_RIGHT:\n x_move = 20\n if event.key == pygame.K_q:\n x2_move = -20\n if event.key == pygame.K_e:\n x2_move = 20\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT:\n x_move = 0\n if event.key == pygame.K_RIGHT:\n x_move = 0\n if event.key == pygame.K_q:\n x2_move = 0\n if event.key == pygame.K_e:\n x2_move = 0\n #x_position += x_move\n #x2_position += x2_move\n\n # Controller portion: update positions as it goes\n if not game_over:\n # Update the player and ball positions\n player.update(x_move)\n player2.update(x2_move)\n game_over = ball.update()\n\n # Print game over if the ball hits the top or bottom corner\n if game_over:\n text = font.render(\"Game Over\", True, white)\n textpos = text.get_rect(centerx=background.get_width()/2)\n textpos.top = 50\n screen.blit(text, textpos)\n restartprompt(screen)\n if checkForKeyPress() == pygame.K_r:\n pygame.event.get() # Flushes cache\n return True\n\n # See if the ball hits the player 1's paddle\n if pygame.sprite.spritecollide(player, balls, False):\n pygame.mixer.Sound.play(collide_sound)\n # The 'diff' lets you try to bounce the ball left or right\n # depending where on the paddle you hit it\n diff = (player.rect.x + player.width/2) - (ball.rect.x+ball.width/2)\n\n # Set the ball's y position in case\n # we hit the ball on the edge of the paddle\n ball.rect.y = screen.get_height() - player.rect.height - ball.rect.height - 1\n ball.bounce(diff)\n\n if pygame.sprite.spritecollide(player2, balls, False):\n pygame.mixer.Sound.play(collide_sound)\n # The 'diff' lets you try to bounce the ball left or right\n # depending where on the paddle you hit it\n diff2 = (player2.rect.x + player2.width/2) - (ball.rect.x+ball.width/2)\n\n # Set the ball's y position in case\n # we hit the ball on the edge of the paddle\n ball.rect.y = screen.get_height() - player2.rect.height - ball.rect.height - 1\n ball.bounce(diff2)\n\n # Check for collisions between the ball and the blocks\n deadblocks = pygame.sprite.spritecollide(ball, blocks, True)\n\n # If we actually hit a block, bounce the ball\n if len(deadblocks) > 0:\n pygame.mixer.Sound.play(collide_sound)\n ball.bounce(0)\n\n # Game ends if all the blocks are gone\n if len(blocks) == 0:\n game_over = True\n\n # Draw Everything\n allsprites.draw(screen)\n\n # Flip the screen and show what we've drawn\n pygame.display.flip()\n\nif __name__ == \"__main__\":\n restart = main()\n # Restart program if restartprompt() in main() returns True\n while restart == True:\n # Toggles restart to False\n restart = False\n restart = main()\n", "sub_path": "ultimateBrick-2-1a.py", "file_name": "ultimateBrick-2-1a.py", "file_ext": "py", "file_size_in_byte": 16212, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pygame.sprite", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 94, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 108, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 117, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 119, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 124, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 135, "usage_type": "call"}, {"api_name": "pygame.display.get_surface", "line_number": 144, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 144, "usage_type": "attribute"}, {"api_name": "pygame.display.get_surface", "line_number": 145, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 145, "usage_type": "attribute"}, {"api_name": "math.radians", "line_number": 157, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 160, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 161, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 187, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 200, "usage_type": "call"}, {"api_name": "pygame.display.get_surface", "line_number": 205, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 205, "usage_type": "attribute"}, {"api_name": "pygame.display.get_surface", "line_number": 206, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 206, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 237, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 237, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 238, "usage_type": "attribute"}, {"api_name": "pygame.display.quit", "line_number": 239, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 239, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 240, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 242, "usage_type": "attribute"}, {"api_name": "pygame.K_ESCAPE", "line_number": 243, "usage_type": "attribute"}, {"api_name": "pygame.display.quit", "line_number": 244, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 245, "usage_type": "call"}, {"api_name": "pygame.font.Font", "line_number": 253, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 253, "usage_type": "attribute"}, {"api_name": "pygame.transform.rotate", "line_number": 261, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 261, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 268, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 268, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 271, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 271, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 281, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 281, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 282, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 282, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 290, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 290, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 299, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 302, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 302, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 305, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 305, "usage_type": "attribute"}, {"api_name": "pygame.mouse.set_visible", "line_number": 308, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 308, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 311, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 311, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 314, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 314, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 320, "usage_type": "call"}, {"api_name": "pygame.sprite.Group", "line_number": 323, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 323, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 324, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 324, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 325, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 325, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 326, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 326, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 367, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 374, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 377, "usage_type": "call"}, {"api_name": "pygame.mixer.music.load", "line_number": 392, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 392, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 393, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 393, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 396, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 396, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 409, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 409, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 410, "usage_type": "attribute"}, {"api_name": "pygame.display.quit", "line_number": 412, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 412, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 413, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 415, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 416, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 418, "usage_type": "attribute"}, {"api_name": "pygame.K_q", "line_number": 420, "usage_type": "attribute"}, {"api_name": "pygame.K_e", "line_number": 422, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 424, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 425, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 427, "usage_type": "attribute"}, {"api_name": "pygame.K_q", "line_number": 429, "usage_type": "attribute"}, {"api_name": "pygame.K_e", "line_number": 431, "usage_type": "attribute"}, {"api_name": "pygame.K_r", "line_number": 450, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 451, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 451, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 455, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 455, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound.play", "line_number": 456, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 456, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 466, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 466, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound.play", "line_number": 467, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 467, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 478, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 478, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound.play", "line_number": 482, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 482, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 493, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 493, "usage_type": "attribute"}]} +{"seq_id": "164693860", "text": "import re\nimport json\n\n# Capture `value ;` blocks\nre_value_definition = re.compile(r\"(value(?:[\\s\\S]+?)+?;)+\")\n\n# Capture attribute name \nre_attribute_name = re.compile(r\"value\\s+\\$?([\\w]+)\")\n\n# Capture key-value pairs\nre_key_value = re.compile(r\"'?([^'\\\"\\s]+)'?\\s*=\\s*'(.+)'\")\n\n\ndef parse_sas(path, save_as=\"\"):\n \"\"\"Parse SAS file with labels descriptions\n \n Args:\n path (str): SAS file path\n save_as (:obj:`str`, optional): output path for json file\n\n Returns:\n attr_dict (dict): dictionary with labels descriptions\n \n \"\"\"\n \n with open(path) as file:\n # Capture attribute name \n blocks_iter = re_value_definition.finditer(file.read())\n\n attr_dict = dict()\n for block in blocks_iter:\n # Capture attribute name\n attr = re_attribute_name.search(block.group(1))\n\n attr_dict[attr.group(1)] = {\n match.group(1): match.group(2).strip()\n # Capture key-value pairs\n for match in re_key_value.finditer(block.group(1))\n }\n \n if save_as:\n with open(save_as, \"w\") as file:\n json.dump(attr_dict, file, indent=True)\n \n return attr_dict\n", "sub_path": "projects/project-6/sas_parser.py", "file_name": "sas_parser.py", "file_ext": "py", "file_size_in_byte": 1207, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "re.compile", "line_number": 5, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 8, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 11, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "66087406", "text": "# -*-coding:utf-8-*-\r\n# getlonlat.py\r\n# from: mamq\r\n# run: python3 getlonlat.py\r\nimport pymysql.cursors\r\nfrom urllib import parse\r\nfrom urllib.request import urlopen\r\nimport requests\r\nimport re\r\n\r\nconnection = pymysql.connect(host=\"localhost\", user='root', password='wq65929102', db='lian_jia', charset='utf8mb4',\r\n cursorclass=pymysql.cursors.DictCursor)\r\n\r\n\r\ndef parse_address(address):\r\n url = 'http://api.map.baidu.com/geocoding/v3/'\r\n output = 'json'\r\n ak = 'Sj9CsksGB3dyurIao0wDFCvPXwBbC4ZK' # 浏览器端密钥\r\n address = parse.quote(address) # 由于本文地址变量为中文,为防止乱码,先用quote进行编码\r\n uri = url + '?' + 'address=' + address + '&output=' + output + '&ak=' + ak + \"&callback=showLocation\"\r\n req = urlopen(uri)\r\n res = req.read().decode()\r\n pattern_lng = \"lng\\\":(.*?),\"\r\n pattern_lat = \"lat\\\":(.*?)}\"\r\n lng = re.findall(pattern_lng, res)\r\n lat = re.findall(pattern_lat, res)\r\n if lng or lat:\r\n data = (float(lng[0]), float(lat[0]))\r\n return data\r\n\r\n\r\ndef get_address():\r\n try:\r\n with connection.cursor() as cursor:\r\n sql_select = \"select District,sub_district,`position` from suzhou_real\"\r\n cursor.execute(sql_select)\r\n connection.commit()\r\n result = cursor.fetchall()\r\n except:\r\n connection.rollback()\r\n address_list = []\r\n for i in result:\r\n address = '苏州' + i['District'] + i['sub_district'] + i['position']\r\n address_list.append(address)\r\n return address_list\r\n\r\n\r\ntry:\r\n with connection.cursor() as cursor:\r\n address_list = set(get_address())\r\n sql_create=\"create table if not exists lat_lng ( id int primary key auto_increment, addr_parse varchar(255),lng double, lat double);\"\r\n cursor.execute(sql_create)\r\n connection.commit()\r\n for addr in address_list:\r\n lng_lat = parse_address(addr)\r\n lng = lng_lat[0]\r\n lat = lng_lat[1]\r\n sql_insert = \"insert into lat_lng(addr_parse,lng,lat) values(%s,%s,%s);\"\r\n\r\n cursor.execute(sql_insert, [addr,lng,lat])\r\n\r\n connection.commit()\r\n print(\"正在插入经纬度\")\r\n\r\nfinally:\r\n\r\n connection.close()\r\n", "sub_path": "get_lat_lng_new.py", "file_name": "get_lat_lng_new.py", "file_ext": "py", "file_size_in_byte": 2279, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pymysql.cursors.connect", "line_number": 11, "usage_type": "call"}, {"api_name": "pymysql.cursors", "line_number": 11, "usage_type": "name"}, {"api_name": "pymysql.cursors.cursors", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pymysql.cursors", "line_number": 12, "usage_type": "name"}, {"api_name": "urllib.parse.quote", "line_number": 19, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 19, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 21, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 25, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "106363034", "text": "from get_file_from_url import get_file\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport unicodedata\nimport os\nimport pickle\nimport json\nimport numpy as np\n\nclass TheNumbersWebCrawler(object):\n \"\"\"\n It takes the website www.the-numbers.com and takes the data from it needed for the project\n this data is then return back into a pandas dataframe\n \"\"\"\n \n \n def get_year_page_movie_list(self,year):\n \"\"\"\n Takes a given year and calls the webpage with all the movies that year\n then returns a list with all movies that have a budget listed.\n \"\"\"\n \n ##get the webpage with all the movies from that year\n request=get_file(self._base_link+'/movies/year/'+str(year))\n soup = BeautifulSoup(request.text)\n output=[]\n for item in soup.findAll('table')[0].findAll('tr'):\n \n ##only add movies to list when they have budget listed\n budget=item.find(\"td\", { \"class\" : \"data\" })\n if budget is not None and len(budget.text)>1: \n s=item.find('a').decode().split('\"')\n output.append(s[1])\n \n return output\n \n def scrape_movie_data_to_dic(self,request):\n \"\"\"\n Takes a reuest.get() and returns a dictionary with the desired values\n \"\"\"\n soup = BeautifulSoup(request.text)\n dic={}\n \n ##add the title\n value= soup.find(\"h1\", { \"itemprop\" : \"name\" }).text\n value= unicodedata.normalize('NFKD', value).encode('ascii','ignore')\n dic['Movie Title']=value\n \n ##grab the data from each section in finance section\n finances=soup.find(\"table\", { \"id\" : \"movie_finances\" })\n for item in finances.findAll(\"td\", { \"class\" : \"data\" }):\n ##get the key\n key=item.previousSibling.previousSibling.text\n key=unicodedata.normalize('NFKD', key).encode('ascii','ignore')\n ##get the value\n value=unicodedata.normalize('NFKD', item.text).encode('ascii','ignore')\n dic[key]= item.text\n \n ##grab the data from each section in the summary section\n data=soup.find(\"div\", { \"id\" : \"summary\" }).findAll('table')[1]\n for item in data.findAll('tr'):\n ##change text to string and replace new line with '' and split by :\n s=unicodedata.normalize('NFKD', item.text).encode('ascii','ignore')\n s= s.replace(\"\\n\",'').split(':')\n dic[s[0]]=[s[1]]\n \n return dic\n \n def get_cast_crew(self,url):\n request=get_file(url)\n soup = BeautifulSoup(request.text)\n main_dic={}\n\n lst=[u'Cast',u'Production and Technical Credits']\n for i in xrange(len(lst)):\n main_dic[lst[i]]=np.nan\n dic={}\n try:\n lst[i]=soup.findAll('div',{'id':'cast'})[i].find('h1').text\n for row in soup.findAll('div',{'id':'cast'})[i].findAll('tr'):\n position, filler, name = row.findAll('td')\n position= unicodedata.normalize('NFKD', position.text).encode('ascii','ignore')\n name = unicodedata.normalize('NFKD', name.text).encode('ascii','ignore')\n if position in dic:\n dic[position]+=[name]\n else:\n dic[position]=[name]\n dic=json.dumps(dic)\n except:\n dic=np.nan\n\n main_dic[lst[i]]=dic\n return main_dic\n \n def movie_list_to_df(self,movie_list):\n \"\"\"\n Takes the list movies and process then adds the data to the dataframe\n \"\"\"\n for movie in movie_list:\n request=get_file(self._base_link+movie)\n \n ##build dic of furture dataframe column with dic keys\n ##and dataframe value as dic[key]=value\n dic=self.scrape_movie_data_to_dic(request)\n cast_crew=self.get_cast_crew((self._base_link+movie).replace('summary','cast-and-crew'))\n \n ##merge together\n dic['Cast']=cast_crew[u'Cast']\n dic['Crew']=cast_crew[u'Production and Technical Credits']\n \n ##build new dataframe and append it to total\n df=pd.DataFrame.from_dict(dic)\n self._df=self._df.append(df)\n \n\n def df_exists(self,out_path,file_name):\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n if os.path.isfile(out_path + '/' + file_name):\n return pd.read_pickle(out_path + '/' + file_name)\n return None\n \n def get_df(self):\n \"\"\"\n Wrapper returning the pandas dataframe\n \"\"\"\n return self._df.reset_index()\n \n def __init__(self,start_year=1915,end_year=2014,out_path='dataframes'):\n \"\"\"\n Given the \n Calls the functions in correctly to get the data and build the dataframe\n \"\"\"\n self._base_link='http://www.the-numbers.com'\n file_name='df_the_numbers_'+str(start_year)+'_'+str(end_year)+'_raw.p'\n \n self._df=self.df_exists(out_path,file_name)\n \n \n if self._df is None:\n ##start new empty df then later append to it movie by movie\n self._df=pd.DataFrame()\n for year in xrange(start_year,end_year +1):\n lst=self.get_year_page_movie_list(year)\n self.movie_list_to_df(lst)\n ##save main dataframe\n self._df.to_pickle(out_path + '/' + file_name)", "sub_path": "the_numbers_web_crawler.py", "file_name": "the_numbers_web_crawler.py", "file_ext": "py", "file_size_in_byte": 5591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "get_file_from_url.get_file", "line_number": 24, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 25, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 41, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 46, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 54, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 56, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 63, "usage_type": "call"}, {"api_name": "get_file_from_url.get_file", "line_number": 70, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 76, "usage_type": "attribute"}, {"api_name": "unicodedata.normalize", "line_number": 82, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 83, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 90, "usage_type": "attribute"}, {"api_name": "get_file_from_url.get_file", "line_number": 100, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 112, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 112, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pandas.read_pickle", "line_number": 120, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 142, "usage_type": "call"}]} +{"seq_id": "341436880", "text": "import hashlib\nimport json\nimport sys\nimport time\nimport traceback\n\nimport six\nfrom fluent import handler, sender\nfrom fluent.handler import FluentRecordFormatter\n\nimport metaappscriptsdk\n\n\nclass FluentSender(sender.FluentSender):\n def _make_packet(self, label, timestamp, data):\n if label:\n tag = '.'.join((self.tag, label))\n else:\n tag = self.tag\n\n if 'channel' not in data:\n data['channel'] = tag\n\n data['level_name'] = data['type']\n del data['type']\n packet = {'tag': tag, 'ts': timestamp, 'data': json.dumps(data, separators=(',', ':'))}\n\n message = ('[\"%(tag)s\",%(ts)s,%(data)s]' % packet).encode('utf-8')\n if self.verbose:\n print(message)\n return message\n\n\nclass FluentHandler(handler.FluentHandler):\n def __init__(self, tag, host='localhost', port=24224, timeout=3.0, verbose=False):\n super(FluentHandler, self).__init__(tag, host=host, port=port, timeout=timeout, verbose=verbose)\n self.sender = FluentSender(tag, host=host, port=port, timeout=timeout, verbose=verbose)\n\n\nclass FluentRecordFormatter(FluentRecordFormatter, object):\n converter = time.gmtime # timestamps are in UTC zone\n\n def formatTime(self, record, datefmt=None):\n \"\"\"\n https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-date-format.html#mapping-date-format\n yyyy-MM-dd'T'HH:mm:ss.SSS # date_hour_minute_second_millis\n :type record logging.LogRecord\n :type datefmt str\n :rtype: str\n \"\"\"\n ct = self.converter(record.created)\n\n # @see https://docs.python.org/2/library/time.html#time.strftime\n t = time.strftime(\"%Y-%m-%dT%H:%M:%S\", ct)\n s = \"%s.%03d\" % (t, record.msecs)\n return s\n\n def format(self, record):\n dict__ = record.__dict__\n context = dict(dict__.get('context', {}))\n context.update(metaappscriptsdk.logger.LOGGER_ENTITY)\n # add exception details (if any)\n context.update(self.formatException(record))\n\n # Only needed for python2.6\n if sys.version_info[0:2] <= (2, 6) and self.usesTime():\n record.asctime = self.formatTime(record, self.datefmt)\n\n # Compute attributes handled by parent class.\n super(FluentRecordFormatter, self).format(record)\n # Add ours\n record.hostname = self.hostname\n # Apply format\n data = dict([(key, value % dict__)\n for key, value in self._fmt_dict.items()])\n data['context'] = context\n data['@timestamp'] = self.formatTime(record)\n data.setdefault('extra', {})\n data['extra']['md5Msg'] = hashlib.md5(record.msg.encode('utf-8')).hexdigest()\n self._structuring(data, record.msg)\n return data\n\n def formatException(self, record):\n \"\"\"\n Format and return the specified exception information as a string.\n :type record logging.LogRecord\n :rtype: dict\n \"\"\"\n if record.exc_info is None:\n return {}\n\n (exc_type, exc_message, trace) = record.exc_info\n\n return {\n 'e': {\n 'class': str(exc_type.__name__), # ZeroDivisionError\n 'message': str(exc_message), # integer division or modulo by zero\n 'trace': list(traceback.format_tb(trace)),\n }\n }\n\n def usesTime(self):\n return any([value.find('%(asctime)') >= 0\n for value in self._fmt_dict.values()])\n\n def _structuring(self, data, msg):\n \"\"\" Melds `msg` into `data`.\n\n :param data: dictionary to be sent to fluent server\n :param msg: :class:`LogRecord`'s message to add to `data`.\n `msg` can be a simple string for backward compatibility with\n :mod:`logging` framework, a JSON encoded string or a dictionary\n that will be merged into dictionary generated in :meth:`format.\n \"\"\"\n if isinstance(msg, dict):\n self._add_dic(data, msg)\n elif isinstance(msg, six.string_types):\n try:\n self._add_dic(data, json.loads(str(msg)))\n except ValueError:\n self._add_dic(data, {'message': msg})\n else:\n self._add_dic(data, {'message': msg})\n\n @staticmethod\n def _add_dic(data, dic):\n for key, value in dic.items():\n if isinstance(key, six.string_types):\n data[str(key)] = value\n", "sub_path": "metaappscriptsdk/logger/custom_fluent.py", "file_name": "custom_fluent.py", "file_ext": "py", "file_size_in_byte": 4487, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "fluent.sender.FluentSender", "line_number": 14, "usage_type": "attribute"}, {"api_name": "fluent.sender", "line_number": 14, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 26, "usage_type": "call"}, {"api_name": "fluent.handler.FluentHandler", "line_number": 34, "usage_type": "attribute"}, {"api_name": "fluent.handler", "line_number": 34, "usage_type": "name"}, {"api_name": "time.gmtime", "line_number": 41, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 54, "usage_type": "call"}, {"api_name": "metaappscriptsdk.logger", "line_number": 61, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 66, "usage_type": "attribute"}, {"api_name": "hashlib.md5", "line_number": 79, "usage_type": "call"}, {"api_name": "traceback.format_tb", "line_number": 98, "usage_type": "call"}, {"api_name": "six.string_types", "line_number": 117, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 119, "usage_type": "call"}, {"api_name": "six.string_types", "line_number": 128, "usage_type": "attribute"}]} +{"seq_id": "172556853", "text": "from torchvision import transforms as T\nimport utils.transforms_DL as T_DL\n\nnum_classes = 10\ninput_channel = 4\nrandom_seed = 6666\ndevice = 'cuda:2'\nroot_dir = '/home/cailinhao/landUseProj_master/landUseProj/'\nlogfile = root_dir + '/code/log/smp_unetpp_pretrain_b8_chnl4-rgb_argu_discolor-alltrain_100ep-0302.log'\n\ntrain_mean = [0.485, 0.456, 0.406, 0.5]\ntrain_std = [0.229, 0.224, 0.225, 0.25]\ntest_mean = [0.485, 0.456, 0.406, 0.5]\ntest_std = [0.229, 0.224, 0.225, 0.25]\n\n# 配置transform\n# 注意:train和val涉及到label,需要用带_DL后缀的transform\n# test不涉及label,用原来的transform\nprob = 0.5\ntrain_transform = T.Compose([\n T_DL.ToTensor_DL(), # 转为tensor\n T_DL.RandomFlip_DL(p=prob), # 概率p水平或者垂直翻转\n T_DL.RandomRotation_DL(p=prob), # 概率p发生随机旋转(只会90,180,270)\n # T_DL.RandomColorJitter_DL(p=prob, brightness=1, contrast=1, saturation=1, hue=0.5), # 概率p调整rgb\n T_DL.Normalized_DL(mean=train_mean[:input_channel], std=train_std[:input_channel]), # 归一化\n])\n\nval_transform = T.Compose([\n T_DL.ToTensor_DL(), # 转为tensor\n # T_DL.RandomColorJitter_DL(p=prob, brightness=1, contrast=1, saturation=1, hue=0.5), # 概率p调整rgb\n T_DL.Normalized_DL(mean=train_mean[:input_channel],\n std=train_std[:input_channel]), # 归一化\n])\n\ntest_transform = T.Compose([\n T.ToTensor(),\n T.Normalize(mean=test_mean[:input_channel], std=test_std[:input_channel]),\n])\n\ndataset_cfg = dict(\n train_dir=root_dir + '/tcdata/suichang_round1_train_210120',\n # train_dir=root_dir + '/tcdata/train',\n val_dir=root_dir + '/tcdata/validation',\n test_dir=root_dir + '/tcdata/suichang_round1_test_partA_210120',\n input_channel=input_channel, # 使用几个通道作为输入\n train_ratio=0.8,\n val_ratio=0.2,\n random_seed=999,\n\n # 配置transform,三个数据集的配置都要配置\n train_transform=train_transform,\n val_transform=val_transform,\n test_transform=test_transform,\n)\n\nmodel_cfg = dict(\n type='SMP',\n backbone='timm-efficientnet-b8',\n encoder_weights='imagenet',\n input_channel=input_channel,\n num_classes=num_classes,\n pretrained=True,\n check_point_file=root_dir + '/code/checkpoint/smp_unetpp_pretrain_b8_chnl4-rgb_argu_discolor-alltrain_100ep-0302/smp_unetpp_best.pth',\n\n # type='AttUnet',\n # input_channel=4,\n # num_classes=num_classes,\n # check_point_file=root_dir + '/code/checkpoint/AttUnet/AttUnet_model.pth'\n\n # 使用已训练的模型\n # type='CheckPoint',\n # check_point_file=root_dir + '/code/checkpoint/Unet/Unet_model.pth',\n)\n\ntrain_cfg = dict(\n num_workers=6,\n batch_size=6,\n num_epochs=95,\n optimizer_cfg=dict(type='adamw', lr=3e-4, momentum=0.9, weight_decay=5e-4),\n lr_scheduler_cfg=dict(policy='cos', T_0=3, T_mult=2, eta_min=1e-5),\n # optimizer_cfg=dict(type='sgd', lr=1e-2, momentum=0.9, weight_decay=5e-4),\n # lr_scheduler_cfg=dict(policy='cos', T_0=2, T_mult=2, eta_min=1e-5),\n auto_save_epoch=5, # 每隔几轮自动保存模型\n is_PSPNet=False, # 不是PSPNet都设为false\n is_swa=False,\n check_point_file=root_dir + '/code/checkpoint/smp_unetpp_pretrain_b7_chnl4-rgb_argu_discolor-alltrain-0218/smp_unetpp_best.pth',\n)\n\ntest_cfg = dict(\n is_predict=True, # 是否是预测分类结果\n is_evaluate=False, # 是否评估模型,也就是计算mIoU\n is_crf=False,\n tta_mode=None, # 'd4'\n dataset='test_dataset',\n batch_size=train_cfg['batch_size'],\n num_workers=train_cfg['num_workers'],\n check_point_file=root_dir + '/code/checkpoint/smp_unetpp_pretrain_b8_chnl4-rgb_argu_discolor-alltrain_100ep-0302/smp_unetpp_best.pth',\n out_dir=root_dir + '/prediction_result/smp_unetpp_pretrain_b8_chnl4-rgb_argu_discolor-alltrain_100ep-0302/',\n)\n", "sub_path": "code/config/smp_unetpp_config.py", "file_name": "smp_unetpp_config.py", "file_ext": "py", "file_size_in_byte": 3843, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torchvision.transforms.Compose", "line_number": 20, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 20, "usage_type": "name"}, {"api_name": "utils.transforms_DL.ToTensor_DL", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 21, "usage_type": "name"}, {"api_name": "utils.transforms_DL.RandomFlip_DL", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 22, "usage_type": "name"}, {"api_name": "utils.transforms_DL.RandomRotation_DL", "line_number": 23, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 23, "usage_type": "name"}, {"api_name": "utils.transforms_DL.Normalized_DL", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 25, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 28, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 28, "usage_type": "name"}, {"api_name": "utils.transforms_DL.ToTensor_DL", "line_number": 29, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 29, "usage_type": "name"}, {"api_name": "utils.transforms_DL.Normalized_DL", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.transforms_DL", "line_number": 31, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 35, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 35, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 36, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 36, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 37, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 37, "usage_type": "name"}]} +{"seq_id": "177891963", "text": "import os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport config\nimport data\n\n\ndef visualize_layers(layers):\n plt.figure()\n plt.scatter(layers.head(5000)['top'], layers.head(5000)['orgc_value_avg'])\n plt.show()\n\ndef visualize_profile_depth(layers):\n bottom_per_profile = layers.groupby(['profile_id'], sort=False)['bottom'].max().dropna()\n\n plt.figure()\n plt.suptitle('Distribution of bottom depth (cm) per profile')\n\n plt.subplot(211)\n sns.distplot(bottom_per_profile, kde=False)\n\n plt.subplot(212)\n sns.distplot(bottom_per_profile, bins=10, kde=False, hist_kws={'range': (0, 250)})\n\n plt.savefig(os.path.join(config.visualizations_dir, 'bottom_dist.png'))\n\nif __name__ == '__main__':\n attributes, profiles, layers = data.load_data()\n print(f'Total layers: {len(layers)}')\n print(f'Total profiles: {len(profiles)}')\n visualize_profile_depth(layers)", "sub_path": "visualizations.py", "file_name": "visualizations.py", "file_ext": "py", "file_size_in_byte": 908, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "config.visualizations_dir", "line_number": 26, "usage_type": "attribute"}, {"api_name": "data.load_data", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "89047289", "text": "\"\"\"\nText over a Heatmap\n-------------------\n\nAn example of a layered chart of text over a heatmap using the cars dataset.\n\"\"\"\n# category: tables\nimport altair as alt\nfrom vega_datasets import data\n\nsource = data.cars()\n\n# Configure common options. We specify the aggregation\n# as a transform here so we can reuse it in both layers.\nbase = alt.Chart(source).transform_aggregate(\n mean_horsepower='mean(Horsepower)',\n groupby=['Origin', 'Cylinders']\n).encode(\n alt.X('Cylinders:O'),\n alt.Y('Origin:O'),\n)\n\n# Configure heatmap\nheatmap = base.mark_rect().encode(\n color=alt.Color('mean_horsepower:Q',\n scale=alt.Scale(scheme='viridis'),\n legend=alt.Legend(title=\"Mean of Horsepower\"),\n )\n)\n\n# Configure text\ntext = base.mark_text(baseline='middle').encode(\n text=alt.Text('mean_horsepower:Q', format=\".0f\"),\n color=alt.condition(\n alt.datum.mean_horsepower > 150,\n alt.value('black'),\n alt.value('white')\n )\n)\n\n# Draw the chart\nheatmap + text\n", "sub_path": "tests/examples_arguments_syntax/layered_heatmap_text.py", "file_name": "layered_heatmap_text.py", "file_ext": "py", "file_size_in_byte": 1001, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "vega_datasets.data.cars", "line_number": 11, "usage_type": "call"}, {"api_name": "vega_datasets.data", "line_number": 11, "usage_type": "name"}, {"api_name": "altair.Chart", "line_number": 15, "usage_type": "call"}, {"api_name": "altair.X", "line_number": 19, "usage_type": "call"}, {"api_name": "altair.Y", "line_number": 20, "usage_type": "call"}, {"api_name": "altair.Color", "line_number": 25, "usage_type": "call"}, {"api_name": "altair.Scale", "line_number": 26, "usage_type": "call"}, {"api_name": "altair.Legend", "line_number": 27, "usage_type": "call"}, {"api_name": "altair.Text", "line_number": 33, "usage_type": "call"}, {"api_name": "altair.condition", "line_number": 34, "usage_type": "call"}, {"api_name": "altair.datum", "line_number": 35, "usage_type": "attribute"}, {"api_name": "altair.value", "line_number": 36, "usage_type": "call"}, {"api_name": "altair.value", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "445996177", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom threading import Lock\nimport requests\nBUFSIZE = 256*1024\n\ndef fs_open(filepath, mode='r', url='', length=0):\n\treturn _fs(filepath, mode, url, length)\n\nclass _fs(object):\n\tdef __init__(self, file_path, mode='r', url='', length=0):\n\t\tself.lock = Lock()\n\t\tself.open(file_path, mode)\n\tdef open(self, file_path, mode='r'):\n\t\tself.fobj = open(file_path, mode)\n\tdef read(self, pos, length):\n\t\tpass\n\tdef write(self, data, pos=0):\n\t\tself.lock.acquire(True)\n\t\tself.fobj.write(data)\n\t\tself.lock.release()\n\tdef close(self):\n\t\tself.fobj.close()\n\ndef fetch_range(url, fobj, pos, length):\n\tprint(pos)\n\tprint(length)\n\tproxies = {'http': 'http://192.168.1.3:9341'}\n\theaders = {'Range': 'bytes=%s-%s'%(pos, length)}\n\tr = requests.get(url, headers=headers)\n\tprint(r.headers)\n\tfobj.write(r.content, pos)\n\tprint(len(r.content))\n\tprint(r.headers['content-length'])\n\treturn int(r.headers['content-length'])\ndef download(url, filepath):\n\tr = requests.head(url)\n\tprint(r.headers)\n\tlength = int(r.headers['content-length'])\n\tf = fs_open(filepath, 'wb', url, length)\n\tpos = 0\n\twhile length > 0:\n\t\tl = fetch_range(url, f, pos, min(BUFSIZE, length))\n\t\tpos += l\n\t\tlength -= l\n\tf.close()\n\ndef main():\n\t# download('http://c758482.r82.cf2.rackcdn.com/Sublime%20Text%202.0.2.zip', '/home/admin/temp/sublime.zip')\n\tdownload('https://dl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg', '/home/admin/temp/googlechrome.dmg')\nif __name__==\"__main__\":\n\tmain()", "sub_path": "network/download.py", "file_name": "download.py", "file_ext": "py", "file_size_in_byte": 1475, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "threading.Lock", "line_number": 13, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 31, "usage_type": "call"}, {"api_name": "requests.head", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "35854679", "text": "# coding: utf8\n\nfrom datetime import datetime, timedelta\n\nimport requests\nfrom celery.utils.log import get_task_logger\n\nfrom .application import app\nfrom . import settings\n\nlogger = get_task_logger('tasks')\n\nmd_content = \"\"\"\n![img](http://img3.weegotr.com/cms/uploads/201311171008518292.jpg)\n### 又到周五啦,开不开森?\n想好周末去哪儿嗨了没?别忘了下班之前写周报哦!\n\"\"\".strip()\n\n\n@app.task\ndef weekly_talk_notifier():\n \"\"\"在dingtalk上发送周报提醒.\"\"\"\n wikihost = 'http://wiki.feifanweige.com'\n uri = '/rest/api/content'\n\n auth = requests.auth.HTTPBasicAuth('auto0', 'auto0')\n\n dt = datetime.now()\n title = '{} - {}'.format(\n (dt - timedelta(days=4)).strftime('%Y/%m/%d'),\n dt.strftime('%Y/%m/%d')\n )\n payload = {\n \"type\": \"page\",\n \"title\": title,\n \"ancestors\": [{\"id\": 7536650}],\n \"space\": {\"key\": \"WEB\"},\n \"body\": {\n \"storage\": {\n \"representation\": \"storage\"\n }\n }\n }\n resp = requests.post('{}{}'.format(wikihost, uri), json=payload, auth=auth)\n url = '{}{}'.format(wikihost, resp.json()['_links']['tinyui'])\n\n webhook = 'https://oapi.dingtalk.com/robot/send'\n\n payload = {\n \"actionCard\": {\n \"title\": \"又到周五啦,开不开森?\",\n \"text\": md_content,\n \"hideAvatar\": \"1\",\n \"btnOrientation\": \"0\",\n \"singleTitle\": \"去写周报\",\n \"singleURL\": url\n },\n \"msgtype\": \"actionCard\"\n }\n resp = requests.post(\n webhook,\n json=payload,\n params={'access_token': settings.DINGTALK_NOTIFY['']}\n )\n if resp.status_code != 200:\n logger.error(\n 'Failed to send dingtalk message to notify weekly talk. %s',\n resp.text\n )\n return False\n return True\n", "sub_path": "flashtripdemo/scripture/tasks/weekly_talk_notifier.py", "file_name": "weekly_talk_notifier.py", "file_ext": "py", "file_size_in_byte": 1875, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "celery.utils.log.get_task_logger", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 26, "usage_type": "call"}, {"api_name": "requests.auth", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 30, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 44, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 60, "usage_type": "call"}, {"api_name": "application.app.task", "line_number": 20, "usage_type": "attribute"}, {"api_name": "application.app", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "587702538", "text": "import json\nimport argparse\n\ndef predict(input_file):\n\traw = open('emnlp_dict.txt').readlines()\n\tdictionary = dict(item.strip().split('\\t') for item in raw)\n\tinput_list = json.load(open(input_file))\n\tfor entry in input_list:\n\t\tentry['output'] = map(lambda item: dictionary.get(item, item), entry['input'])\n\tjson.dump(input_list, open('norm.pred.json', 'w'))\n\ndef main():\n parser = argparse.ArgumentParser(description = \"Baseline system with rule based replacement\")\n parser.add_argument(\"--input\", required = True, help = \"A JSON file: Your input\")\n args = parser.parse_args()\n\n predict(args.input)\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "norm.py", "file_name": "norm.py", "file_ext": "py", "file_size_in_byte": 650, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 7, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 10, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "402470163", "text": "from collections import defaultdict\nfrom copy import deepcopy\nimport json\nimport logging\nimport os\n\nimport maya.cmds as cmds\n\nimport colorbleed.maya.lib as cblib\nfrom avalon import io, api\n\n\nlog = logging.getLogger(__name__)\n\n\ndef get_workfolder():\n return os.path.dirname(cmds.file(query=True, sceneName=True))\n\n\ndef get_selected_assets():\n \"\"\"Get information from current selection\"\"\"\n\n # TODO: Investigate how we can make `long` argument work\n\n items = []\n selection = cmds.ls(selection=True)\n\n containers = get_containers(selection)\n if not containers:\n hierarchy = cmds.listRelatives(selection, allDescendents=True) or []\n containers = get_containers(hierarchy)\n if not containers:\n log.info(\"No items selected with loaded content\")\n return items\n\n for container, content in containers.iteritems():\n # Ensure we have all\n # Create an item for the tool\n item = create_item_from_container(container, content)\n if not item:\n continue\n\n items.append(item)\n\n return items\n\n\ndef get_all_assets():\n \"\"\"Get all assets from the scene\n\n Returns:\n list\n \"\"\"\n\n host = api.registered_host()\n\n items = []\n for container in host.ls():\n # We are not interested in looks but assets!\n if container[\"loader\"] == \"LookLoader\":\n continue\n # Gather all information\n container_name = container[\"objectName\"]\n content = cmds.sets(container_name, query=True)\n item = create_item_from_container(container_name, content)\n if not item:\n continue\n\n items.append(item)\n\n return items\n\n\ndef get_containers(nodes):\n \"\"\"Get containers for the nodes\n\n Args:\n nodes (list): collect of strings, e.g: selected nodes\n\n Return:\n dict\n \"\"\"\n\n host = api.registered_host()\n results = {}\n nodes = set(nodes)\n for container in host.ls():\n container_object = container['objectName']\n members = set(cmds.sets(container_object, query=True) or [])\n if nodes.intersection(members):\n results[container_object] = list(members)\n\n return results\n\n\ndef get_asset_id_item(item):\n\n if cmds.objectType(item) == \"objectSet\":\n content = cmds.sets(item, query=True)\n shapes = cmds.ls(content, long=True, type=\"shape\")\n assert len(shapes) != 0, \"Container has no shapes, this is an error\"\n item = shapes[0]\n\n # Take the first shape, assuming all shapes in the container are from\n # the same asset\n cb_id = cblib.get_id(item)\n if not cb_id:\n return\n\n asset_id = cb_id.rsplit(\":\")[0]\n\n return asset_id\n\n\ndef create_asset_id_hash(nodes):\n \"\"\"Create a hash based on cbId attribute value\n Args:\n nodes (list): a list of nodes\n\n Returns:\n dict\n \"\"\"\n node_id_hash = defaultdict(list)\n for node in nodes:\n value = cblib.get_id(node)\n if value is None:\n continue\n\n asset_id = value.split(\":\")[0]\n node_id_hash[asset_id].append(node)\n\n return node_id_hash\n\n\ndef create_item_from_container(objectname, content):\n \"\"\"Create an item for the view based the container and content of it\n\n It fetches the look document based on the asset ID found in the content.\n The item will contain all important information for the tool to work.\n\n Args:\n objectname(str): name of the objectSet (container)\n content (list): list of items which are in the\n \"\"\"\n\n id_hash = create_asset_id_hash(content)\n topnode = cblib.get_container_transforms({\"objectName\": objectname},\n members=content,\n root=True)\n\n try:\n _id = id_hash.keys()[0]\n except IndexError:\n return {}\n\n asset = io.find_one({\"_id\": io.ObjectId(_id)}, projection={\"name\": True})\n looks = fetch_looks([_id])\n\n return {\"asset\": asset,\n \"objectName\": topnode,\n \"looks\": looks,\n \"_id\": _id}\n\n\ndef fetch_looks(asset_ids):\n \"\"\"Get all looks based on the asset id from the cbId attributes\n\n Use the given asset ID from the attribute which matches an ID from the\n database to use\n\n Args:\n asset_ids (list): list of unique asset IDs\n\n Returns:\n looks (list): looks per asset {asset_name : [look_data, look_data]}\n \"\"\"\n\n publish_looks = list()\n for asset_id in asset_ids:\n # Get asset name for sorting\n object_id = io.ObjectId(asset_id)\n\n # Verify if asset ID is correct\n asset = io.find_one({\"_id\": object_id}, projection={\"name\": True})\n if not asset:\n raise ValueError(\"Could not find asset with objectId \"\n \"`{}`\".format(asset_id))\n\n # Get all data\n for subset in cblib.list_looks(object_id):\n version = io.find_one({\"type\": \"version\", \"parent\": subset[\"_id\"]},\n projection={\"name\": True, \"parent\": True},\n sort=[(\"name\", -1)])\n\n publish_looks.append({\"asset\": asset[\"name\"],\n \"subset\": subset[\"name\"],\n \"version\": version})\n\n return publish_looks\n\n\ndef process_queued_item(entry):\n \"\"\"\n Build the correct assignment for the selected asset\n Args:\n entry (dict):\n\n Returns:\n\n \"\"\"\n\n asset_name = entry[\"asset\"]\n version_id = entry[\"document\"][\"_id\"]\n\n # Get the container\n # Check if item is in a container\n container_lookup = get_containers(asset_name)\n if not container_lookup:\n node_name = asset_name.split(\"|\")[-1]\n container_lookup = get_containers([node_name])\n\n containers = container_lookup.keys()\n assert len(containers) == 1, (\"Node is found in no or multiple containers,\"\n \" this is a bug\")\n\n # Get the content of the container\n container = containers[0]\n nodes = cmds.ls(cmds.sets(container, query=True), long=True)\n\n cblib.assign_look_by_version(nodes, version_id)\n\n\ndef get_asset_data(objectId):\n\n document = io.find_one({\"_id\": io.ObjectId(objectId)})\n document_type = document[\"type\"]\n if document_type == \"representation\":\n version, subset, asset, _ = io.parenthood(document)\n elif document_type == \"asset\":\n asset = document\n else:\n print(\"Could not fetch enough data\")\n return\n\n return asset\n\n\ndef create_queue_out_data(queue_items):\n \"\"\"Create a json friendly data block\"\"\"\n\n items = []\n for item in queue_items:\n # Ensure the io.ObjectId object is a string\n new_item = deepcopy(item)\n new_item[\"document\"][\"_id\"] = str(item[\"document\"][\"_id\"])\n new_item[\"document\"][\"parent\"] = str(item[\"document\"][\"parent\"])\n items.append(new_item)\n\n return items\n\n\ndef create_queue_in_data(queue_items):\n \"\"\"Create a database friendly data block for the tool\"\"\"\n items = []\n for item in queue_items:\n new_item = deepcopy(item)\n document = item[\"document\"]\n new_item[\"document\"][\"_id\"] = io.ObjectId(document[\"_id\"])\n new_item[\"document\"][\"parent\"] = io.ObjectId(document[\"parent\"])\n items.append(new_item)\n\n return items\n\n\ndef save_to_json(filepath, items):\n \"\"\"Store data in a json file\"\"\"\n\n log.info(\"Writing queue file ...\")\n with open(filepath, \"w\") as fp:\n json.dump(items, fp, ensure_ascii=False)\n log.info(\"Successfully written file\")\n\n\ndef remove_unused_looks():\n \"\"\"Removes all loaded looks for which none of the shaders are used.\n\n This will cleanup all loaded \"LookLoader\" containers that are unused in\n the current scene.\n\n \"\"\"\n\n host = api.registered_host()\n\n unused = list()\n for container in host.ls():\n if container['loader'] == \"LookLoader\":\n members = cmds.sets(container['objectName'], query=True)\n look_sets = cmds.ls(members, type=\"objectSet\")\n for look_set in look_sets:\n # If the set is used than we consider this look *in use*\n if cmds.sets(look_set, query=True):\n break\n else:\n unused.append(container)\n\n for container in unused:\n log.warning(\"Removing unused look container: %s\",\n container['objectName'])\n api.remove(container)\n", "sub_path": "mayalookassigner/commands.py", "file_name": "commands.py", "file_ext": "py", "file_size_in_byte": 8461, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 17, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 17, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 26, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 26, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 30, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 30, "usage_type": "name"}, {"api_name": "avalon.api.registered_host", "line_number": 55, "usage_type": "call"}, {"api_name": "avalon.api", "line_number": 55, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 64, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 64, "usage_type": "name"}, {"api_name": "avalon.api.registered_host", "line_number": 84, "usage_type": "call"}, {"api_name": "avalon.api", "line_number": 84, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 89, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 89, "usage_type": "name"}, {"api_name": "maya.cmds.objectType", "line_number": 98, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 98, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 99, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 99, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 100, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 100, "usage_type": "name"}, {"api_name": "colorbleed.maya.lib.get_id", "line_number": 106, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib", "line_number": 106, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 123, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib.get_id", "line_number": 125, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib", "line_number": 125, "usage_type": "name"}, {"api_name": "colorbleed.maya.lib.get_container_transforms", "line_number": 147, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib", "line_number": 147, "usage_type": "name"}, {"api_name": "avalon.io.find_one", "line_number": 156, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 156, "usage_type": "name"}, {"api_name": "avalon.io.ObjectId", "line_number": 156, "usage_type": "call"}, {"api_name": "avalon.io.ObjectId", "line_number": 181, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 181, "usage_type": "name"}, {"api_name": "avalon.io.find_one", "line_number": 184, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 184, "usage_type": "name"}, {"api_name": "colorbleed.maya.lib.list_looks", "line_number": 190, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib", "line_number": 190, "usage_type": "name"}, {"api_name": "avalon.io.find_one", "line_number": 191, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 191, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 228, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 228, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 228, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib.assign_look_by_version", "line_number": 230, "usage_type": "call"}, {"api_name": "colorbleed.maya.lib", "line_number": 230, "usage_type": "name"}, {"api_name": "avalon.io.find_one", "line_number": 235, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 235, "usage_type": "name"}, {"api_name": "avalon.io.ObjectId", "line_number": 235, "usage_type": "call"}, {"api_name": "avalon.io.parenthood", "line_number": 238, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 238, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 254, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 266, "usage_type": "call"}, {"api_name": "avalon.io.ObjectId", "line_number": 268, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 268, "usage_type": "name"}, {"api_name": "avalon.io.ObjectId", "line_number": 269, "usage_type": "call"}, {"api_name": "avalon.io", "line_number": 269, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 280, "usage_type": "call"}, {"api_name": "avalon.api.registered_host", "line_number": 292, "usage_type": "call"}, {"api_name": "avalon.api", "line_number": 292, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 297, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 297, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 298, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 298, "usage_type": "name"}, {"api_name": "maya.cmds.sets", "line_number": 301, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 301, "usage_type": "name"}, {"api_name": "avalon.api.remove", "line_number": 309, "usage_type": "call"}, {"api_name": "avalon.api", "line_number": 309, "usage_type": "name"}]} +{"seq_id": "85873967", "text": "import tkinter as tk\r\nimport schedule.construct.data_arrange as data\r\n\r\nfrom .popup.hover_info import HoverInfo\r\nfrom ..gui.popup.task_addition import TaskAddition\r\nfrom ..gui.popup.task_deletion import TaskDeletion\r\nfrom ..construct.layer import Layer\r\n\r\nfrom calendar import monthrange\r\nfrom datetime import date\r\nfrom time import strftime\r\n\r\n# Author Jadd, Nov 8 2020\r\n# To display all tasks in series of days in the week\r\n\r\nclass WeekSet(Layer):\r\n\r\n # To initialize all variable, buttons and GUI features\r\n def __init__(self, *args, **kwargs):\r\n Layer.__init__(self, *args, **kwargs)\r\n\r\n def ms_wheel(event): self.schedule.yview_scroll(int(-7 * (event.delta/100)), 'units') # Scroll Control\r\n\r\n self.WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\r\n\r\n self.BG = '#222'\r\n self.FG = '#333'\r\n self.TEXT = 'white'\r\n self.BUTTON = '#3A3A3A'\r\n\r\n self.real_year = int(date.today().strftime('%Y'))\r\n self.real_month = int(date.today().strftime('%m'))\r\n self.real_day = int(date.today().strftime('%d'))\r\n\r\n self.tools = tk.Frame(self, bg=self.FG, highlightthickness=0)\r\n self.real_time = tk.Label(self.tools, font='Courier 80', bg=self.FG, fg=self.TEXT)\r\n self.clock()\r\n self.average_frame = tk.Frame(self.tools, bg=self.FG)\r\n\r\n self.select_month = tk.Scale(self.tools, from_=1, to=12, resolution=1, highlightthickness=0, length=220,\r\n font='verdana 10', bg=self.FG, activebackground=self.FG, fg=self.TEXT, width=20,\r\n label='Month', command=lambda e: self.draw_timetable('LOG', self.select_year.get(),\r\n self.select_month.get(), self.real_day))\r\n\r\n self.select_year = tk.Scale(self.tools, from_=2000, to=2100, resolution=1, highlightthickness=0, length=220,\r\n font='verdana 10', bg=self.FG, activebackground=self.FG, fg=self.TEXT, width=20,\r\n label='Year', command=lambda e: self.draw_timetable('LOG', self.select_year.get(),\r\n self.select_month.get(), self.real_day))\r\n\r\n self.log = tk.Button(self.tools, width=10, text='LOG', font='Verdana 10 bold', bd=0, bg=self.BUTTON,\r\n fg=self.TEXT, activebackground=self.FG, activeforeground=self.TEXT,\r\n command=lambda: self.draw_timetable('LOG', self.select_year.get(),\r\n self.select_month.get(), self.real_day))\r\n\r\n self.day_schedule = tk.Button(self.tools, width=10, text='SCHEDULE', font='Verdana 10 bold', bd=0,\r\n bg=self.BUTTON, fg=self.TEXT, activebackground=self.FG, activeforeground=self.TEXT,\r\n command=lambda: self.draw_timetable('SCHEDULE', self.select_year.get(),\r\n self.select_month.get(), self.real_day))\r\n\r\n self.schedule = tk.Canvas(self, highlightthickness=0) # 'Schedule' houses the days\r\n self.schedule.bind_all('', ms_wheel)\r\n\r\n self.scrollbox = tk.Frame(self.schedule) # 'Scrollbox' is scrollable window of days\r\n self.scrollbox.bind('', lambda e: self.schedule.configure(scrollregion=self.schedule.bbox(\"all\")))\r\n self.scroll = tk.Scrollbar(self.schedule, command=self.schedule.yview)\r\n\r\n self.schedule.create_window((0, 0), window=self.scrollbox)\r\n self.schedule.configure(yscrollcommand=self.scroll.set)\r\n self.style()\r\n\r\n # Prompts add/delete windows\r\n def add_task(self): TaskAddition(self)\r\n def delete_task(self): TaskDeletion(self)\r\n\r\n # Assigns tooltip to visual entity of task\r\n def attach_hover(self, shape, text):\r\n\r\n hover_obj = HoverInfo(shape)\r\n\r\n def over(event): hover_obj.appear(text)\r\n def not_over(event): hover_obj.disappear()\r\n\r\n shape.bind('', over)\r\n shape.bind('', not_over)\r\n\r\n\r\n def clock(self):\r\n\r\n current_time = strftime('%H:%M:%S\\n')\r\n current_time = current_time + str(self.real_day) + '|' + str(self.real_month) + '|' + str(self.real_year)\r\n self.real_time.config(text=current_time)\r\n self.real_time.after(1000, self.clock)\r\n\r\n # Calculate the average hours of a certain type of task\r\n def category_averages(self, category, chosen_year, chosen_month):\r\n\r\n day_allotted = 0\r\n category_allotted = 0\r\n timetable_day = data.get_tasks(chosen_year, chosen_month)\r\n\r\n if self.real_year == chosen_year and self.real_month == chosen_month: day_limit = self.real_day\r\n else: day_limit = monthrange(chosen_year, chosen_month)[1] + 1\r\n\r\n for day in range(1, day_limit):\r\n for every in range(len(timetable_day[day])):\r\n\r\n if timetable_day[day][every].get_category() == category and timetable_day[day][every].get_perspective() == 'LOG':\r\n category_allotted += timetable_day[day][every].get_duration()\r\n\r\n day_allotted += 1\r\n if day_allotted == 0: return \"0\";\r\n return str(round(category_allotted/day_allotted, 2))\r\n\r\n\r\n def display_average(self, chosen_year, chosen_month):\r\n\r\n for widget in self.average_frame.winfo_children(): widget.destroy()\r\n\r\n tk.Label(self.average_frame,\r\n text='PRODUCTIVE: '+self.category_averages('PRODUCTIVE', chosen_year, chosen_month)+'h/day',\r\n bg=self.FG, fg=self.TEXT, font='verdana 8').pack(pady=5)\r\n\r\n tk.Label(self.average_frame,\r\n text='LEISURE: '+self.category_averages('LEISURE', chosen_year, chosen_month)+'h/day',\r\n bg=self.FG, fg=self.TEXT, font='verdana 8').pack(pady=5)\r\n\r\n tk.Label(self.average_frame,\r\n text='SLEEP: '+self.category_averages('SLEEP', chosen_year, chosen_month)+'h/day',\r\n bg=self.FG, fg=self.TEXT, font='verdana 8').pack(pady=5)\r\n\r\n\r\n def style(self):\r\n self.configure(bg=self.BG)\r\n self.select_year.set(self.real_year)\r\n self.select_month.set(self.real_month)\r\n\r\n self.real_time.pack(side=tk.LEFT, padx=5)\r\n\r\n self.select_month.pack(side=tk.RIGHT)\r\n self.select_year.pack(side=tk.RIGHT)\r\n\r\n self.log.pack(side=tk.RIGHT, padx=5, pady=5)\r\n self.day_schedule.pack(side=tk.RIGHT, padx=5, pady=5)\r\n self.average_frame.pack(expand=tk.TRUE)\r\n self.tools.pack(fill=tk.X, expand=tk.FALSE, padx=40, pady=10)\r\n\r\n self.schedule.pack(fill=tk.BOTH, expand=tk.TRUE, padx=50, pady=10)\r\n self.scroll.pack(side=tk.RIGHT, fill=tk.Y)\r\n\r\n # To Display tasks in colored bars\r\n def draw_timetable(self, selected_perspective, year_selected, month_selected, highlight_day):\r\n\r\n def draw_bars():\r\n try:\r\n for hour in range(24): # Create 24-hour timeline\r\n day_map.create_text(250+hour*40, 20, text=str(hour)+':00', font='Verdana 8', fill=self.TEXT)\r\n day_map.create_line(250+40*hour, 250, 250+40*hour, 30, dash=(4, 4), fill=self.TEXT)\r\n\r\n day_tasks = timetable_day.get(single_day)\r\n for task in range(len(day_tasks)):\r\n\r\n start = day_tasks[task].get_start_time()\r\n if start % 100 != 0: start += 20\r\n end = day_tasks[task].get_end_time()\r\n if end % 100 != 0: end += 20\r\n\r\n start = start/100\r\n end = end/100\r\n\r\n # To create bar and hover tooltip\r\n if day_tasks[task].get_perspective() == selected_perspective:\r\n\r\n divide = 220/len(day_tasks)\r\n hover_text = 'ID: ' + str(day_tasks[task].get_id()) + '\\n' + \\\r\n str(day_tasks[task].get_start_time()) + '-' + \\\r\n str(day_tasks[task].get_end_time()) + ': ' + \\\r\n str(day_tasks[task].get_duration()) + 'h\\n\\n' + \\\r\n day_tasks[task].get_description()\r\n\r\n bar = tk.Label(day_map, background=day_tasks[task].get_colour()) # Calculate bar dimensions\r\n bar.place(x=252+40*start, y=32+divide*task, height=((30+divide*(task+1))-(30+divide*task)-2),\r\n width=((250+40*end)-(250+40*start)-2))\r\n self.attach_hover(bar, text=hover_text)\r\n\r\n # Add/Delete buttons\r\n adds = tk.Button(day_map, width=10, text='ADD', font='Verdana 10', bd=0, bg=self.FG, fg=self.TEXT,\r\n activeforeground=self.TEXT, activebackground=self.FG, command=self.add_task)\r\n deletes = tk.Button(day_map, width=10, text='DELETE', font='Verdana 10', bd=0, bg=self.FG, fg=self.TEXT,\r\n activeforeground=self.TEXT, activebackground=self.FG, command=self.delete_task)\r\n day_map.create_window((145, 180), window=adds)\r\n day_map.create_window((145, 210), window=deletes)\r\n\r\n except KeyError: pass\r\n\r\n #---------------------------------------------------------------#\r\n\r\n self.display_average(year_selected, month_selected)\r\n timetable_day = data.get_tasks(year_selected, month_selected)\r\n for widget in self.scrollbox.winfo_children(): widget.destroy() # Reset data\r\n\r\n # The loop sets up the canvas for visualizing tasks with the date and time\r\n for single_day in range(1, monthrange(year_selected, month_selected)[1]+1):\r\n\r\n week_day = date(year_selected, month_selected, single_day).weekday()\r\n day_map = tk.Canvas(self.scrollbox, bg=self.FG, width=1220, height=260,\r\n highlightthickness=1, highlightbackground=self.BG)\r\n\r\n # To highlight real date\r\n if self.real_month == month_selected and self.real_year == year_selected and single_day == highlight_day:\r\n day_map.create_text(150, 55, text=self.WEEKDAYS[week_day], font='Verdana 17 bold', fill='gold')\r\n day_map.create_text(145, 130, text=single_day, font='Verdana 40 bold', fill='gold')\r\n\r\n else:\r\n day_map.create_text(150, 55, text=self.WEEKDAYS[week_day], font='Verdana 17', fill=self.TEXT)\r\n day_map.create_text(145, 130, text=single_day, font='Verdana 22', fill=self.TEXT)\r\n\r\n day_map.create_text(145, 90, text='('+selected_perspective+')', font='Verdana 10', fill=self.TEXT)\r\n draw_bars()\r\n day_map.pack()\r\n", "sub_path": "DayLogger/gui/week_set.py", "file_name": "week_set.py", "file_ext": "py", "file_size_in_byte": 10820, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "construct.layer.Layer", "line_number": 16, "usage_type": "name"}, {"api_name": "construct.layer.Layer.__init__", "line_number": 20, "usage_type": "call"}, {"api_name": "construct.layer.Layer", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 31, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 32, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 33, "usage_type": "name"}, {"api_name": "tkinter.Frame", "line_number": 35, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Scale", "line_number": 40, "usage_type": "call"}, {"api_name": "tkinter.Scale", "line_number": 45, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 50, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 55, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 60, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 63, "usage_type": "call"}, {"api_name": "tkinter.Scrollbar", "line_number": 65, "usage_type": "call"}, {"api_name": "gui.popup.task_addition.TaskAddition", "line_number": 72, "usage_type": "call"}, {"api_name": "gui.popup.task_deletion.TaskDeletion", "line_number": 73, "usage_type": "call"}, {"api_name": "popup.hover_info.HoverInfo", "line_number": 78, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 89, "usage_type": "call"}, {"api_name": "schedule.construct.data_arrange.get_tasks", "line_number": 99, "usage_type": "call"}, {"api_name": "schedule.construct.data_arrange", "line_number": 99, "usage_type": "name"}, {"api_name": "calendar.monthrange", "line_number": 102, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 119, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 123, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 127, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 137, "usage_type": "attribute"}, {"api_name": "tkinter.RIGHT", "line_number": 139, "usage_type": "attribute"}, {"api_name": "tkinter.RIGHT", "line_number": 140, "usage_type": "attribute"}, {"api_name": "tkinter.RIGHT", "line_number": 142, "usage_type": "attribute"}, {"api_name": "tkinter.RIGHT", "line_number": 143, "usage_type": "attribute"}, {"api_name": "tkinter.TRUE", "line_number": 144, "usage_type": "attribute"}, {"api_name": "tkinter.X", "line_number": 145, "usage_type": "attribute"}, {"api_name": "tkinter.FALSE", "line_number": 145, "usage_type": "attribute"}, {"api_name": "tkinter.BOTH", "line_number": 147, "usage_type": "attribute"}, {"api_name": "tkinter.TRUE", "line_number": 147, "usage_type": "attribute"}, {"api_name": "tkinter.RIGHT", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tkinter.Y", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tkinter.Label", "line_number": 180, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 186, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 188, "usage_type": "call"}, {"api_name": "schedule.construct.data_arrange.get_tasks", "line_number": 198, "usage_type": "call"}, {"api_name": "schedule.construct.data_arrange", "line_number": 198, "usage_type": "name"}, {"api_name": "calendar.monthrange", "line_number": 202, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 204, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 205, "usage_type": "call"}]} +{"seq_id": "615461241", "text": "from pandas import read_csv\nfrom pandas import datetime\nfrom matplotlib import pyplot\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.metrics import mean_squared_error\n\n \ndef parser(x):\n\treturn datetime.strptime(x, '%M-%S')\n\ndev_id = 33 \t\nseries = read_csv('knoy_pcb_1_X_320.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)\nX = series.values\nsize = int(len(X) * 0.67)\ntrain, test = X[0:size], X[size:len(X)]\nhistory = [x for x in train]\npredictions = list()\nfor t in range(len(test)):\n\tmodel = ARIMA(history, order=(5,2,0))\n\tmodel_fit = model.fit(disp=0)\n\toutput = model_fit.forecast()\n\tyhat = output[0]\n\tpredictions.append(yhat)\n\tobs = test[t]\n\thistory.append(obs)\n\tprint('predicted=%f, expected=%f' % (yhat, obs))\nerror = mean_squared_error(test, predictions)\nprint('Test MSE: %.3f' % error)\n# plot\npyplot.plot(test,label='Actual Readings')\npyplot.plot(predictions,label='Predicted Readings', color='red')\nlegend = pyplot.legend(['Actual Readings', 'Predicted Readings'],loc='upper center', shadow=True, fontsize='x-large')\npyplot.xlabel('Test Samples', fontdict=None, labelpad=None)\npyplot.ylabel('Dielectric', fontdict=None, labelpad=None)\npyplot.show()\n", "sub_path": "src/models/Arima_Rolling_two.py", "file_name": "Arima_Rolling_two.py", "file_ext": "py", "file_size_in_byte": 1201, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pandas.datetime.strptime", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 9, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 12, "usage_type": "call"}, {"api_name": "statsmodels.tsa.arima_model.ARIMA", "line_number": 19, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}]} +{"seq_id": "281347877", "text": "# coding: utf-8\n\nfrom setuptools import setup, find_packages\n\n\nif __name__ == '__main__':\n NAME = \"swagger_server\"\n VERSION = \"1.0.0\"\n\n # To install the library, run the following\n #\n # python setup.py install\n #\n # prerequisite: setuptools\n # http://pypi.python.org/pypi/setuptools\n\n REQUIRES = [\"connexion\"]\n setup(\n name=NAME,\n version=VERSION,\n description=\"ResMon - distributed resources monitoring\",\n author_email=\"mad.fis.agh@gmail.com\",\n url=\"\",\n keywords=[\"Swagger\", \"ResMon - distributed resources monitoring\"],\n install_requires=REQUIRES,\n packages=find_packages(),\n package_data={\"\": [\"swagger/swagger.yaml\"]},\n include_package_data=True,\n entry_points={\n \"console_scripts\": [\"swagger_server=swagger_server.__main__:main\"]\n },\n long_description=\"\"\"\\\n This is simple resource monitor which allows to view how much are\n used all resources on all monitored hosts. Note that we use token\n authorization with JWT so you need to provide `Authorization`\n header with `Bearer [TOKEN]` value on each request. You will\n receive token from auth server on successful sign-in or sign-on action.\n Make sure monitor uses selected auth server. Monitor should handle CORS\n with pre-flight, allowing query each path by OPTIONS to get CORS\n headers.\n \"\"\",\n )\n", "sub_path": "rest_api/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1474, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 18, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "129464509", "text": "from __future__ import print_function\nimport sys\nimport time\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import Row\nfrom pyspark.sql.types import *\n\n\n\nif __name__==\"__main__\":\n spark = SparkSession \\\n .builder \\\n .appName(\"UDF benchmark v2\") \\\n .config(\"spark.sql.autoBroadcastJoinThreshold\", \"-1\") \\\n .getOrCreate()\n sc = spark.sparkContext\n file_name = sys.argv[1]\n lines = sc.textFile(file_name)\n parts = lines.map(lambda l: l.split(\",\"))\n data = parts.map(lambda p: (int(p[0]), float(p[1]), float(p[2])))\n schema = StructType([StructField(\"id\",LongType(),True),\\\n StructField(\"x\",DoubleType(),True),\\\n StructField(\"y\",DoubleType(),True)])\n df = spark.createDataFrame(data, schema)\n df.cache().first()\n t1 = time.time()\n spark.udf.register(\"myudf\", lambda x:2*x, DoubleType())\n df.registerTempTable(\"points\")\n df1 = spark.sql(\"\"\"SELECT\n id AS id,\n SUM(myudf(x)) AS sx,\n SUM(myudf(y)) AS sy\n FROM points \n GROUP BY id \n \"\"\")\n df1.cache().first()\n t2 = time.time()\n print(\"UDF python test v2 execution time %f\" % (t2-t1))\n spark.stop()\n", "sub_path": "src/main/python/udf_v2.py", "file_name": "udf_v2.py", "file_ext": "py", "file_size_in_byte": 1288, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 11, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 11, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 26, "usage_type": "call"}, {"api_name": "time.time", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "503575608", "text": "#Importing necessary Libraries\r\nimport pandas as pd\r\nfrom pandas.plotting import scatter_matrix\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n#Load the dataset\r\ndata=pd.read_csv('files/Iris.csv')\r\nprint(data.describe())\r\n\r\n# histograms\r\ndata.hist()\r\nplt.show()\r\n\r\n# scatter plot matrix\r\nscatter_matrix(data)\r\nplt.show()\r\n\r\n# Split-out validation dataset\r\narray = data.values\r\nX = array[:,0:4]\r\nY = array[:,5]\r\n\r\nvalidation_size = 0.20\r\nseed = 7\r\nX_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=validation_size, random_state=seed)\r\n\r\n# Spot-Check Algorithms\r\nmodels = []\r\nmodels.append(('LR', LogisticRegression()))\r\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\r\nmodels.append(('KNN', KNeighborsClassifier()))\r\nmodels.append(('CART', DecisionTreeClassifier()))\r\nmodels.append(('NB', GaussianNB()))\r\nmodels.append(('SVM', SVC()))\r\n\r\n# evaluate each model in turn\r\nresults = []\r\nnames = []\r\nfor name, model in models:\r\n kfold = KFold(n_splits=10, random_state=seed)\r\n cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')\r\n results.append(cv_results)\r\n names.append(name)\r\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\r\n print(msg)\r\n \r\n# Compare Algorithms\r\nfig = plt.figure()\r\nfig.suptitle('Algorithm Comparison')\r\nax = fig.add_subplot(111)\r\nplt.boxplot(results)\r\nax.set_xticklabels(names)\r\nplt.show()\r\n\r\n# Make predictions on validation dataset based on SVC\r\nsvc = SVC()\r\nsvc.fit(X_train, Y_train)\r\npredictions = svc.predict(X_validation)\r\nprint(accuracy_score(Y_validation, predictions))\r\nprint(confusion_matrix(Y_validation, predictions))\r\nprint(classification_report(Y_validation, predictions))\r\n\r\n", "sub_path": "iris_classic.py", "file_name": "iris_classic.py", "file_ext": "py", "file_size_in_byte": 2342, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "warnings.filterwarnings", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "pandas.plotting.scatter_matrix", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 43, "usage_type": "call"}, {"api_name": "sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "line_number": 44, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 46, "usage_type": "call"}, {"api_name": "sklearn.naive_bayes.GaussianNB", "line_number": 47, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 48, "usage_type": "call"}, {"api_name": "sklearn.model_selection.KFold", "line_number": 54, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.boxplot", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "sklearn.svm.SVC", "line_number": 70, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 73, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 74, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "114711956", "text": "# 29 July 2019\n# Lisa Malins\n# GetOligos.py\n\n\"\"\"\nScript slices fasta genome assembly into overlapping oligos.\n\nAccepts as arguments the source filename, k-mer size, step size,\n output filename (optional) and log filename (optional).\n\nUsage:\npython GetOligos.py {genome filename} {keep sequences filename} {mer size} {step size} {optional: output filename} {optional: log filename}\n\nExample command:\npython GetOligos.py agra_cadabra_genome.fa 45 3 agra_cadabra_45mers.fa\n\"\"\"\n\nimport sys\nfrom os import stat\nfrom time import ctime\ntry:\n from time import process_time\nexcept:\n from time import clock as process_time #python2\nfrom datetime import timedelta\n\nclass HeaderException(Exception):\n pass\n\nclass Kmer:\n\n # Starts a new k-mer with given index and sequence\n def StartNew(self, id, seq):\n self.seq = seq\n self.id = id\n self.index = 1\n\n # Appends next sequence and forgets the same # characters that is added\n def Advance(self, addition):\n self.seq = self.seq[len(addition):] + addition\n self.index += len(addition)\n\n\n# Finds headers and returns \"ID\" next header that that matters\ndef NextHeader(source, log, good_seqs, line=\" \"):\n while True:\n # If the next line is a header\n if line[0] == \">\":\n id = line[1:].split()[0]\n if id in good_seqs:\n return id\n else:\n log.write(\"Ignored:\\n\" + line)\n # print(\"I don't care about \", line.rstrip()) #debug\n\n line = source.readline()\n\n# Reads the specified number of characters from source and returns string\ndef ReadChars(source, length):\n addition = \"\"\n while len(addition) < length:\n next_letter = source.read(1)\n\n # Append letters\n if next_letter.isalpha():\n addition += next_letter\n # Ignore whitespace\n elif next_letter.isspace():\n continue\n # Throw headers back\n elif next_letter == '>':\n line = \">\" + source.readline()\n raise HeaderException(line)\n # Throw EOF when out of letters\n elif not next_letter:\n raise EOFError\n # Anything else is a problem\n else:\n print(next_letter + \" <-- wtf\")\n exit(\"I literally can't even right now\") #debug\n return addition\n\ndef SetupIO():\n usage = \"Usage: python GetOligos.py {genome filename} {keep sequences filename} {mer size} {step size} {optional: output name} {optional: log name}\"\n\n # Read arguments\n try:\n source = open(sys.argv[1], 'r')\n except IndexError:\n exit(usage)\n except FileNotFoundError as e:\n exit(\"Genome file \" + e.filename + \" not found.\\n\" + usage)\n\n try:\n keep = open(sys.argv[2], 'r')\n except FileNotFoundError as e:\n keep_usage = \"This should be a text file of the sequences you want to get oligos from, one per line.\\n\"\n\n # Attempt to catch user forgetting keep file\n if sys.argv[2].isdigit():\n sys.stderr.write(\"I'm guessing you forgot to include a file of sequences to keep.\\n{}{}\\\n \".format(keep_usage, usage))\n exit(1)\n\n # User specified a keep file but doesn't exist\n sys.stderr.write(\"Sequences to keep file \" + e.filename + \" not found.\\n{}{}\\\n \".format(keep_usage, usage))\n exit(1)\n\n try:\n mer_size = int(sys.argv[3])\n step_size = int(sys.argv[4])\n if mer_size <= 0 or step_size <= 0:\n raise ValueError()\n if step_size > mer_size:\n exit(\"Mer size must be greater than step size\\n\" + usage)\n except IndexError:\n exit(usage)\n except ValueError:\n exit(\"Please provide the mer-size and step-size as positive integers\\n\" + usage)\n\n try:\n output = open(sys.argv[5], 'w')\n except IndexError:\n output = open(source.name.rsplit('.', 1)[0] + \"_\" + str(mer_size) + \"mers.fa\", 'w')\n\n try:\n log = open(sys.argv[6], 'w')\n except IndexError:\n log = open(output.name.rsplit('.', 1)[0] + \".log\", 'w')\n\n return source, mer_size, step_size, output, log, keep\n\n\n#-------------------main-----------------------\n\nsource, mer_size, step_size, output, log, keep = SetupIO()\n\n# Read headers from keep file and verify they all have unique ID's\ngood_seqs = list(map(lambda x: str(x).strip(), keep.readlines()))\nkeep.close()\n\nlog.write(\"Log file for GetOligos.py\\n\")\nlog.write(\"Genome file: \" + source.name + \"\\n\")\nlog.write(\"Oligo size: \" + str(mer_size))\nlog.write(\" Step size: \" + str(step_size) + \"\\n\")\nlog.write(\"Sequences to keep read from: \" + keep.name + \"\\n\")\nlog.write(\"\\n\".join(good_seqs))\nlog.write(\"\\n\")\nlog.write(\"Oligos written to: \" + output.name + \"\\n\\n\")\n\n\n# Get length of file for progress output\nfilelength = float(stat(source.name).st_size)\npercent = 10\n\nprint(\"Reading \" + str(mer_size) + \"-mers with step size of \" + str(step_size) + \\\n\" from \" + source.name + \" and writing to \" + output.name)\nprint(\"Logging to: \" + log.name)\nprint(\"Genome slicing into oligos beginning at \" + ctime())\nlog.write(\"\\nGenome slicing into oligos beginning at \" + ctime() + \"\\n\\n\")\ntime0 = process_time()\n\n# Create Kmer object\nkmer = Kmer()\nline = \" \"\n\ntry:\n while True:\n # Progress messages\n if (source.tell() / filelength * 100 >= percent):\n print(\"Read progress : \" + str(percent) + \"%\")\n percent += 10\n\n # Get header, start new k-mer\n id = NextHeader(source, log, good_seqs, line)\n kmer.StartNew(id, ReadChars(source, 45))\n\n # Print k-mers until header encountered\n while True:\n output.write(\">\" + str(id) + \"_\" + str(kmer.index) + \"\\n\")\n output.write(kmer.seq + \"\\n\")\n try:\n kmer.Advance(ReadChars(source, 3))\n # Catch header line and carry to next main loop iteration\n except HeaderException as e:\n line = e.args[0]\n break\n\n# Aaaaaaand stick the landing\nexcept (IndexError, EOFError) as e:\n source.close()\n\n proc_time = process_time() - time0\n\n print(\"Finished writing \" + str(mer_size) + \"-mers to \" + output.name)\n print(\"Program finished successfully at \" + ctime())\n print(\"Total time \" + str(timedelta(seconds=proc_time)) + \" (\" + str(proc_time) + \" seconds)\")\n print(\"Progress messages may not have reached 100% because of ignored sequences.\")\n print(\"Log available at \" + log.name)\n log.write(\"\\nGenome slicing into oligos finished successfully at \" + ctime() + \"\\n\")\n log.write(\"Total time \" + str(timedelta(seconds=proc_time)) + \" (\" + str(proc_time) + \" seconds)\\n\")\n", "sub_path": "davinci/GetOligos/GetOligos.py", "file_name": "GetOligos.py", "file_ext": "py", "file_size_in_byte": 6649, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 88, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 95, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 100, "usage_type": "attribute"}, {"api_name": "sys.stderr.write", "line_number": 101, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 101, "usage_type": "attribute"}, {"api_name": "sys.stderr.write", "line_number": 106, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 106, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 111, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 112, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 123, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 154, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 160, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 161, "usage_type": "call"}, {"api_name": "time.clock", "line_number": 162, "usage_type": "call"}, {"api_name": "time.clock", "line_number": 194, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 197, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 198, "usage_type": "call"}, {"api_name": "time.ctime", "line_number": 201, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 202, "usage_type": "call"}]} +{"seq_id": "173574319", "text": "\"\"\"\nTypical usage example:\n\n python submit.py \n\"\"\"\n\nfrom typing import List\n\nimport sys\nimport json\nimport requests\nimport cortex\n\n\ndef main():\n # parse args\n if len(sys.argv) != 3:\n print(\"usage: python submit.py \")\n sys.exit(1)\n env_name = sys.argv[1]\n dest_s3_dir = sys.argv[2]\n\n # read sample file\n with open(\"sample.json\") as f:\n sample_items: List[str] = json.load(f)\n\n # get batch endpoint\n cx = cortex.client(env_name)\n batch_endpoint = cx.get_api(\"sum\")[\"endpoint\"]\n\n # submit job\n job_spec = {\n \"workers\": 1,\n \"item_list\": {\"items\": sample_items, \"batch_size\": 1},\n \"config\": {\"dest_s3_dir\": dest_s3_dir},\n }\n response = requests.post(batch_endpoint, json=job_spec)\n print(json.dumps(response.json(), indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "test/apis/batch/sum/submit.py", "file_name": "submit.py", "file_ext": "py", "file_size_in_byte": 901, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 20, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 21, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 25, "usage_type": "name"}, {"api_name": "json.load", "line_number": 25, "usage_type": "call"}, {"api_name": "cortex.client", "line_number": 28, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 37, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "195769470", "text": "\"\"\"\nHMS Curve Number Runoff module\nGoogle Earth Engine Script\n- all fusion tables have been made public.\n\"\"\"\n\n# import ee\nimport json\n\nresult_metadata = {}\n# ee.Initialize()\n\n# NLCD landcover image\nnlcd_landcover = ee.Image('USGS/NLCD/NLCD2011').select(\"landcover\")\n\n# NLCD landcover legend\nnlcd_legend = ee.FeatureCollection('ft:1Ji3CTnGa3rRy5Te3mXdFmLusmbKBR6tWeaCXpBW1')\n\n# STATSGO soil details table\nstatsgo_soil_details = ee.FeatureCollection('ft:18lBl-j1mfqDlgAJe_hUP9XVRUYTXojvUeVZJAS_l')\n\n# STATSGO region boundary outlines\n# OBSOLETE with updated get_statsgo_region function\n# statsgo_outline = ee.FeatureCollection('ft:1IihDoAf456zaFqKe3HwSs3iWjbhzRCCkEp0bIH7V', 'geometry')\n\n\ndef get_statsgo_region(geometry):\n \"\"\"\n Gets the statsgo geometries that intersect with the provided geometry.\n :param geometry: Input geometry.\n :return: FeatureCollection containing all intersecting geomteries.\n \"\"\"\n # region = statsgo_outline.filterBounds(point).first().get('name').getInfo()\n # if (region == \"East\"):\n # return ee.FeatureCollection('ft:1oP38-oNfwi63LGT6zmLRIzdYNrKXlehCh72PUrxp', 'geometry').filterBounds(point)\n # elif (region == \"MidEast\"):\n # return ee.FeatureCollection('ft:12pF1gr-Emrv2pbu0-0NLpCvCB0ubgFD2oz_OETqx', 'geometry').filterBounds(point)\n # elif (region == \"Mid\"):\n # return ee.FeatureCollection('ft:1p16uUd4oPisU-wcJMG5beBaHQUcbQ4i7vOkgAGrH', 'geometry').filterBounds(point)\n # elif (region == \"MidWest\"):\n # return ee.FeatureCollection('ft:1FsTaBtg8Xig38Y6Hcp7gbe2KFAT0kD0JRLNSnI7C', 'geometry').filterBounds(point)\n # elif (region == \"West\"):\n # return ee.FeatureCollection('ft:1BilByJX_OWOy0X1OqSAOwKfRlUpioVumKbSs8jRM', 'geometry').filterBounds(point)\n # else:\n # return\n\n # Checks all statsgo regions if they contain any intersecting geometries with the given geometry.\n # Resolves possible boundary errors.\n statsgo_east = ee.FeatureCollection(\"ft:1oP38-oNfwi63LGT6zmLRIzdYNrKXlehCh72PUrxp\", 'geometry').filterBounds(geometry)\n statsgo_mideast = ee.FeatureCollection(\"ft:12pF1gr-Emrv2pbu0-0NLpCvCB0ubgFD2oz_OETqx\", 'geometry').filterBounds(geometry)\n statsgo_mid = ee.FeatureCollection('ft:1p16uUd4oPisU-wcJMG5beBaHQUcbQ4i7vOkgAGrH', 'geometry').filterBounds(geometry)\n statsgo_midwest = ee.FeatureCollection('ft:1FsTaBtg8Xig38Y6Hcp7gbe2KFAT0kD0JRLNSnI7C', 'geometry').filterBounds(geometry)\n statsgo_west = ee.FeatureCollection('ft:1BilByJX_OWOy0X1OqSAOwKfRlUpioVumKbSs8jRM', 'geometry').filterBounds(geometry)\n\n # Merges all the FeatureCollections of statsgo geometries into a single FeatureCollection.\n return statsgo_east.merge(statsgo_mideast).merge(statsgo_mid).merge(statsgo_midwest).merge(statsgo_west)\n\n\ndef get_hydrologic_group(musym):\n \"\"\"\n Gets the Hydrologic Soil Group details.\n :param musym: Map unit symbol.\n :return: Feature containing the HSG details.\n \"\"\"\n # Filter returns a FeatureCollection of one element, first() gets that single feature element.\n return statsgo_soil_details.filter(ee.Filter.eq(\"musym\", musym)).first()\n\n\ndef get_cn(latitude, longitude):\n \"\"\"\n Finds the curve number for a given latitude/longitude coordinate.\n TODO: Change functions to accept geometry, define geometry prior to function to allow for HUC and custom defined geometries.\n :param latitude: Requested latitude coordinate.\n :param longitude: Requested longitude coordinate.\n :return: Curve Number value\n \"\"\"\n def get_region_cn(soil):\n\n def calculate_region_cn(soil):\n type_keys = ee.Dictionary(type_count.get(\"landcover\"))\n values = ee.Dictionary(type_keys).map(adjusted_cn)\n summed = ee.Number(values.values().reduce(ee.Reducer.sum()))\n cn_nw = summed.divide(ee.Number(count.get(\"landcover\")))\n soil = soil.set({\"CN\": cn_nw})\n return ee.Feature(soil)\n def adjusted_cn(key, value):\n types = nlcd_legend.filter(ee.Filter.stringContains(\"lc_id\", key))\n cn = types.first().get(hsg)\n a = ee.Dictionary(ee.Dictionary(type_count).get(\"landcover\")).get(key)\n acn = ee.Number(a).multiply(ee.Number(cn))\n return acn\n def water_area(soil):\n soil = soil.set({\"CN\": 100})\n return ee.Feature(soil)\n type_count = nlcd_region.reduceRegion(reducer=ee.Reducer.frequencyHistogram(), geometry=point, scale=30)\n count = nlcd_region.reduceRegion(reducer=ee.Reducer.count(), geometry=point, scale=30)\n musym = soil.get(\"MUSYM\")\n soil_group = get_hydrologic_group(musym)\n hsg = soil_group.get(\"hydgrpdcd\")\n cn = ee.Algorithms.If(ee.Algorithms.IsEqual(musym, \"s8369\"), water_area(soil), calculate_region_cn(soil))\n # cn = calculate_region_cn(soil)\n return cn\n\n point = ee.Geometry.Point(ee.List([float(longitude), float(latitude)])).buffer(500)\n statsgo_region = get_statsgo_region(point) # soil data\n nlcd_region = nlcd_landcover.clip(point) # landcover data\n cns = statsgo_region.map(get_region_cn)\n cn_sum = cns.aggregate_sum(\"CN\")\n cn_size = cns.size()\n wcn = ee.Number(cn_sum).divide(cn_size)\n return wcn.getInfo()\n\n\ndef get_runoff(startdate, enddate, latitude, longitude, cn):\n\n def create_timeseries(ele):\n data = ee.Dictionary(ee.Image(ele).reduceRegion(ee.Reducer.mean(), maxPixels=1000000000))\n runoff = ee.List(ee.Dictionary(data).values()).get(0)\n f = ee.Feature(ele.geometry())\n f = f.set(\"cn_runoff\", runoff)\n f = f.set(\"date\", ele.get('system:index'))\n return f\n\n def compute_runoff(i):\n min = ee.Number(runoff_a)\n q = i.expression('(float(P) <= float(MIN)*float(S) ? 0 : ((float(P) - float(MIN)*float(S)) ** 2) / (float(P) + (1-float(MIN)) * float(S)))',\n {\n 'S': S,\n 'MIN': min,\n 'P': ee.Image(i).select('prcp')\n })\n return ee.Image(q)\n\n def clip_to_geometry(i):\n return ee.Image(i).clip(ee.Geometry(point))\n\n point = ee.Geometry.Point(ee.List([float(longitude), float(latitude)])).buffer(500)\n S = ee.Number(25.4 * ((1000/float(cn)) - 10))\n result_metadata[\"S_value\"] = S\n rain = ee.ImageCollection('NASA/ORNL/DAYMET_V3').select('prcp').map(clip_to_geometry)\\\n .filterDate(ee.Date(startdate), ee.Date(enddate))\n ts = []\n runoff_a = 0.1\n result_metadata[\"runoff_coefficient\"] = runoff_a\n Q = rain.map(compute_runoff)\n fCollection = Q.map(create_timeseries).getInfo()['features']\n\n for f in fCollection:\n date = f['properties']['date']\n data = f['properties']['cn_runoff']\n ts.append([date, data])\n\n return ts\n\n\ndef get_cn_runoff(startdate, enddate, latitude, longitude):\n result_metadata = {'startdate': startdate, 'enddate': enddate, 'latitude': latitude, 'longitude': longitude}\n weighted_cn = get_cn(latitude, longitude)\n result_runoff = get_runoff(startdate, enddate, latitude, longitude, weighted_cn)\n result = '{\"source\": \"Weighted Curve Number\", \"dataset\": \"Surface Runoff\", \"metadata\": ' + \\\n json.dumps(result_metadata) + ', \"data\": ' + json.dumps(result_runoff) + '}'\n return result", "sub_path": "modules/hms/surface_runoff_curve_number.py", "file_name": "surface_runoff_curve_number.py", "file_ext": "py", "file_size_in_byte": 7315, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.dumps", "line_number": 161, "usage_type": "call"}]} +{"seq_id": "185208500", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom account.forms import UserForm\nfrom account.models import User, EmailToken\nfrom store.models import Order, OrderStatus, OrderDetail, Product\n\n\n@login_required(login_url='/account/logining')\ndef admin_base(request):\n return redirect('orders')\n\n\n@login_required(login_url='/account/logining')\ndef orders(request):\n user = request.user\n role = user.roles\n\n orders = Order.objects.filter(status__id=1)\n\n context = {\n \"list\": orders,\n \"segment\": \"del\",\n }\n return render(request, 'delivery/orders.html', context=context)\n\n\n@login_required(login_url='/account/logining')\ndef getorders(request, id):\n try:\n order = Order.objects.get(id=id)\n except id.DoesNotExist:\n return redirect('myorders')\n status = OrderStatus.objects.get(id=2)\n order.delivery = request.user\n order.status = status\n order.save()\n return redirect('myorders')\n\n\n@login_required(login_url='/account/logining')\ndef deliveryorders(request, id):\n user = request.user\n role = user.roles\n\n order = Order.objects.get(id=id)\n\n if order.status.id != 3:\n status = OrderStatus.objects.get(id=3)\n order.status = status\n order.save()\n\n detail = OrderDetail.objects.filter(order=order)\n\n context = {\n \"order\": order,\n \"list\": detail,\n \"segment\": \"myorders\",\n }\n return render(request, 'delivery/myordersdetail.html', context=context)\n\n\n@login_required(login_url='/account/logining')\ndef myorders(request):\n user = request.user\n role = user.roles\n\n orders = Order.objects.filter(delivery=user).order_by('status')\n\n context = {\n \"list\": orders,\n \"segment\": \"myorders\",\n }\n return render(request, 'delivery/myorders.html', context=context)\n\n\n@login_required(login_url='/account/logining')\ndef orderfinish(request, id):\n user = request.user\n role = user.roles\n\n order = Order.objects.get(id=id)\n status = OrderStatus.objects.get(id=4)\n order.status = status\n order.save()\n\n return redirect('myorders')\n\n\n@login_required(login_url='/account/logining')\ndef profile(request):\n user = request.user\n role = user.roles\n\n context = {\n \"user\": user,\n \"segment\": \"profile\",\n }\n\n return render(request, 'delivery/page-user.html', context=context)\n\n\n@login_required(login_url='/account/logining')\ndef admin_deliveries(request):\n users = User.objects.filter(roles__name=\"DELIVERY\")\n return render(request, 'admin/deliveries.html', {'list': users, 'segment': 'delivery'})\n\n\ndef admin_update_deliveries(request, pk):\n if request.method == \"GET\":\n user = User.objects.get(pk=pk)\n name = user.name\n sname = user.surname\n email = user.email\n phone = user.phone\n icon = user.icon\n return render(request, 'admin/add-delivery.html', {\n 'name': name, 'icon': icon, 'sname': sname, 'email_2': email, 'phone': phone, 'segment': 'delivery',\n 'action': 'Жаңарту'})\n\n if request.method == \"POST\":\n name = request.POST['name']\n surname = request.POST['surname']\n password = request.POST['password']\n phone = request.POST['phone']\n img = request.FILES.get('icon')\n user = User.objects.get(pk=pk)\n user.name = name\n user.surname = surname\n if password:\n user.set_password(password)\n user.phone = phone\n if img:\n user.icon = img\n user.save()\n\n return redirect('deliveries_list')\n\n\n@login_required(login_url='/account/logining')\ndef admin_add_deliveries(request):\n if request.method == \"GET\":\n return render(request, 'admin/add-delivery.html', {'segment': 'delivery', 'action': \"Жеткізетін адамды қосыңыз\"})\n\n if request.method == \"POST\":\n name = request.POST['name']\n sname = request.POST['surname']\n email = request.POST['email']\n password = request.POST['password']\n phone = request.POST['phone']\n img = request.FILES\n context = {\n \"name\": name,\n \"sname\": sname,\n \"email\": email,\n \"phone\": phone,\n \"password\": password,\n \"message\": \"\"\n }\n\n user = User.objects.filter(email=email)\n if user.first():\n context[\"message\"] = \"Такой email уже существует\"\n return render(request, 'admin/add-delivery.html', context=context)\n\n user = User.objects.filter(phone=phone)\n if user.first():\n context[\"message\"] = \"Такой номер уже существует\"\n return render(request, 'admin/add-delivery.html', context=context)\n\n user = User.objects.create(name=name, surname=sname, email=email, phone=phone, icon=img.get('icon'))\n user.set_password(password)\n user.is_active = True\n user.is_staff = True\n user.roles_id = 3\n user.save()\n return redirect(\"deliveries_list\")\n\n\ndef delete_delivery(request, id):\n try:\n del_sel = User.objects.get(pk=id)\n except id.DoesNotExist:\n return redirect('deliveries_list')\n del_sel.delete()\n return redirect('deliveries_list')\n\n\ndef delete_product(request, id):\n try:\n del_sel = Product.objects.get(pk=id)\n except id.DoesNotExist:\n return redirect('admin_products')\n del_sel.delete()\n return redirect('admin_products')\n", "sub_path": "delivery/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5571, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.shortcuts.redirect", "line_number": 12, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 10, "usage_type": "call"}, {"api_name": "store.models.Order.objects.filter", "line_number": 20, "usage_type": "call"}, {"api_name": "store.models.Order.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "store.models.Order", "line_number": 20, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 15, "usage_type": "call"}, {"api_name": "store.models.Order.objects.get", "line_number": 32, "usage_type": "call"}, {"api_name": "store.models.Order.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "store.models.Order", "line_number": 32, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 34, "usage_type": "call"}, {"api_name": "store.models.OrderStatus.objects.get", "line_number": 35, "usage_type": "call"}, {"api_name": "store.models.OrderStatus.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "store.models.OrderStatus", "line_number": 35, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 39, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 29, "usage_type": "call"}, {"api_name": "store.models.Order.objects.get", "line_number": 47, "usage_type": "call"}, {"api_name": "store.models.Order.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "store.models.Order", "line_number": 47, "usage_type": "name"}, {"api_name": "store.models.OrderStatus.objects.get", "line_number": 50, "usage_type": "call"}, {"api_name": "store.models.OrderStatus.objects", "line_number": 50, "usage_type": "attribute"}, {"api_name": "store.models.OrderStatus", "line_number": 50, "usage_type": "name"}, {"api_name": "store.models.OrderDetail.objects.filter", "line_number": 54, "usage_type": "call"}, {"api_name": "store.models.OrderDetail.objects", "line_number": 54, "usage_type": "attribute"}, {"api_name": "store.models.OrderDetail", "line_number": 54, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 61, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 42, "usage_type": "call"}, {"api_name": "store.models.Order.objects.filter", "line_number": 69, "usage_type": "call"}, {"api_name": "store.models.Order.objects", "line_number": 69, "usage_type": "attribute"}, {"api_name": "store.models.Order", "line_number": 69, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 75, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 64, "usage_type": "call"}, {"api_name": "store.models.Order.objects.get", "line_number": 83, "usage_type": "call"}, {"api_name": "store.models.Order.objects", "line_number": 83, "usage_type": "attribute"}, {"api_name": "store.models.Order", "line_number": 83, "usage_type": "name"}, {"api_name": "store.models.OrderStatus.objects.get", "line_number": 84, "usage_type": "call"}, {"api_name": "store.models.OrderStatus.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "store.models.OrderStatus", "line_number": 84, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 88, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 78, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 101, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 91, "usage_type": "call"}, {"api_name": "account.models.User.objects.filter", "line_number": 106, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 106, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 107, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 104, "usage_type": "call"}, {"api_name": "account.models.User.objects.get", "line_number": 112, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 112, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 112, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 118, "usage_type": "call"}, {"api_name": "account.models.User.objects.get", "line_number": 128, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 128, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 138, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 144, "usage_type": "call"}, {"api_name": "account.models.User.objects.filter", "line_number": 162, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 162, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 162, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 165, "usage_type": "call"}, {"api_name": "account.models.User.objects.filter", "line_number": 167, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 167, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 167, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 170, "usage_type": "call"}, {"api_name": "account.models.User.objects.create", "line_number": 172, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 172, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 172, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 178, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 141, "usage_type": "call"}, {"api_name": "account.models.User.objects.get", "line_number": 183, "usage_type": "call"}, {"api_name": "account.models.User.objects", "line_number": 183, "usage_type": "attribute"}, {"api_name": "account.models.User", "line_number": 183, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 185, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 187, "usage_type": "call"}, {"api_name": "store.models.Product.objects.get", "line_number": 192, "usage_type": "call"}, {"api_name": "store.models.Product.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "store.models.Product", "line_number": 192, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 194, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 196, "usage_type": "call"}]} +{"seq_id": "238852910", "text": "#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\"\"\"knit Python/R Markdown and Jupyter, create Pandoc-Flavored Markdown\n\nUsage:\n pymd-knit [-k|--kernel ] [-m|--mtype ] \n pymd-knit [-l|--list]\n pymd-knit [-h|--help] [-v|--version]\n\nArguments:\n source filename\n\nOptions:\n -k,--kernel Jupyter kernel name\n -m,--mtype markdown type (latex(default) or beamer or beamer169)\n -l,--list List filetype\n -h,--help Show this help\n -v,--version Show version\n\"\"\"\n\nimport os\nimport sys\nfrom docopt import docopt, DocoptExit\nimport pymd\n\n\ndef main():\n\ttry:\n\t\targs = docopt(\n\t\t\t__doc__,\n\t\t\targv=None,\n\t\t\thelp=True,\n\t\t\tversion=pymd.__version__,\n\t\t\toptions_first=False\n\t\t)\n\texcept DocoptExit as e:\n\t\tprint(\"Invalid arguments or optiions\", file=sys.stderr)\n\t\tprint(e, file=sys.stderr)\n\t\tsys.exit(-1)\n\texcept SystemExit:\n\t\tsys.exit(0)\n\tctype = 'knit'\n\tif args['--list']:\n\t\tpymd.list_types(ctype)\n\t\tsys.exit(0)\n\tifile = args['']\n\tif ifile is None:\n\t\tprint(\"Indicate source file\")\n\t\tsys.exit(-1)\n\tif not os.path.exists(ifile):\n\t\tprint(\"Source file(%s) is not exists\" % ifile, file=sys.stderr)\n\t\tsys.exit(-1)\n\tibase, iext = os.path.splitext(os.path.basename(ifile))\n\tiext = iext.replace(\".\", \"\")\n\tidata = pymd.filetypes.get(iext)\n\tif idata is None:\n\t\tprint(\"Source filetype is not correspond\")\n\t\tpymd.list_types(ctype)\n\t\tsys.exit(-1)\n\tif not idata[ctype]['input']:\n\t\tprint(\"Source filetype is not correnpond in pymd-%s\" % ctype)\n\t\tsys.exit(-1)\n\tkernel = idata[ctype]['default_kernel']\n\tmtype = idata[ctype]['default_mtype']\n\thighlight = idata['syntax_highlight']\n\tif len(args['--kernel']) > 0:\n\t\tkernel = args['--kernel'][-1]\n\tif len(args['--mtype']) > 0:\n\t\tmtype = args['--mtype'][-1]\n\tibname = ibase.split('.')\n\tif len(ibname) == 3:\n\t\tkernel = ibname[1]\n\t\tmtype = ibname[2]\n\telif len(ibname) == 2:\n\t\tif ibname[1] in pymd.mtypes.keys():\n\t\t\tmtype = ibname[1]\n\t\telse:\n\t\t\tkernel = ibname[1]\n\tif mtype not in pymd.mtypes.keys():\n\t\tprint(\"indicate mtype(markdown type) from below:\")\n\t\tfor k, v in pymd.mtypes.items():\n\t\t\tprint(\" %s: %s\" % (k, v))\n\t\texit(-1)\n\toext = idata[ctype]['output_types'][0]\n\tofile = os.path.join(os.path.dirname(ifile), ibase + \".\" + oext)\n\tbase = pymd.pymdBase(ifile, ofile, kernel, iext, mtype, highlight)\n\tbase.knit()\n\treturn\n", "sub_path": "pymd/knit.py", "file_name": "knit.py", "file_ext": "py", "file_size_in_byte": 2323, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "docopt.docopt", "line_number": 30, "usage_type": "call"}, {"api_name": "pymd.__version__", "line_number": 34, "usage_type": "attribute"}, {"api_name": "docopt.DocoptExit", "line_number": 37, "usage_type": "name"}, {"api_name": "sys.stderr", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 42, "usage_type": "call"}, {"api_name": "pymd.list_types", "line_number": 45, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 46, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 52, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 54, "usage_type": "call"}, {"api_name": "pymd.filetypes.get", "line_number": 56, "usage_type": "call"}, {"api_name": "pymd.filetypes", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pymd.list_types", "line_number": 59, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 60, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 63, "usage_type": "call"}, {"api_name": "pymd.mtypes.keys", "line_number": 76, "usage_type": "call"}, {"api_name": "pymd.mtypes", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pymd.mtypes.keys", "line_number": 80, "usage_type": "call"}, {"api_name": "pymd.mtypes", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pymd.mtypes.items", "line_number": 82, "usage_type": "call"}, {"api_name": "pymd.mtypes", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path", "line_number": 86, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 86, "usage_type": "call"}, {"api_name": "pymd.pymdBase", "line_number": 87, "usage_type": "call"}]} +{"seq_id": "215549289", "text": "# FROM https://github.com/ccxt/ccxt/blob/master/examples/py/async-generator-basic.py\n\n# FROM https://github.com/ccxt/ccxt/issues/2092\n\n# -*- coding: utf-8 -*-\n\nimport asyncio\nimport os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(root + '/python')\n\nimport ccxt.async_support as ccxt # noqa: E402\n\nexchange = ccxt.binance({\n 'enableRateLimit': True, # don't remove this line or they might ban you: https://github.com/ccxt/ccxt/wiki/Manual#rate-limit\n})\n\n\nasync def poll():\n while True:\n yield await exchange.fetch_ticker('BTC/USDT')\n\n\nasync def main():\n async for ticker in poll():\n print(ticker)\n\n\nasyncio.get_event_loop().run_until_complete(main())\n", "sub_path": "cruxtraderApp/asyncio/myAsyncio/poll_binance.py", "file_name": "poll_binance.py", "file_ext": "py", "file_size_in_byte": 742, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "ccxt.async_support.binance", "line_number": 16, "usage_type": "call"}, {"api_name": "ccxt.async_support", "line_number": 16, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "429743747", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n===========================================================\nIdentifying stars in a STEREO/SECCHI COR2 coronagraph image\n===========================================================\n\nHow to use the `Vizier star catalog `_ to\nidentify bright points in a STEREO/SECCHI COR 2 image as stars.\nAs a bonus, we also identify Mars.\n\"\"\"\nimport matplotlib.pyplot as plt\n\n# astroquery is not a dependency of SunPy so will need to be\n# install this package separately.\nfrom astroquery.vizier import Vizier\nimport astropy.units as u\nfrom astropy.coordinates import SkyCoord, get_body_barycentric\n\nimport sunpy.map\nfrom sunpy.coordinates import get_body_heliographic_stonyhurst, frames\nfrom sunpy.net import helioviewer\n\n###############################################################################\n# Let's download a STEREO-A SECCHI COR2 image from Helioviewer which provide\n# pre-processed images and load it into a Map.\nhv = helioviewer.HelioviewerClient()\nf = hv.download_jp2('2014/05/15 07:54', observatory='STEREO_A', instrument='SECCHI', detector='COR2')\ncor2 = sunpy.map.Map(f)\n\n###############################################################################\n# To efficiently search the star field we need to know what stars are near the\n# Sun as observed by STEREO. We need the vector that points from STEREO to the Sun.\n# By converting to HCRS we get the vector from the Sun to STEREO\nsun_to_stereo = cor2.observer_coordinate.transform_to('hcrs')\n\n###############################################################################\n# We next reflect the vector to get our search vector which points from STEREO\n# to the Sun\nstereo_to_sun = SkyCoord(-sun_to_stereo.data, obstime=sun_to_stereo.obstime, frame='hcrs')\n\n###############################################################################\n# Let's look up bright stars using the Vizier search capability provided by\n# astroquery (note that this is not a required package of SunPy so you will likely\n# need to install it). We will search the GAIA2 star catalog for stars with magnitude\n# brighter than 7.\nvv = Vizier(columns=['**'], row_limit=-1, column_filters={'Gmag': '<7'}, timeout=1200)\nvv.ROW_LIMIT = -1\nresult = vv.query_region(stereo_to_sun, radius=4 * u.deg, catalog='I/345/gaia2')\n\n###############################################################################\n# Let's see how many stars we've found.\nprint(len(result[0]))\n\n###############################################################################\n# Now we load each star into a coordinate and transform it into the COR2\n# image coordinates. Since we don't know the distance to each of these stars\n# we will just put them very far away.\nhpc_coords = []\nfor this_object in result[0]:\n tbl_crds = SkyCoord(this_object['RA_ICRS'] * u.deg, this_object['DE_ICRS'] * u.deg,\n 1e12 * u.km, frame='icrs', obstime=cor2.date)\n hpc_coords.append(tbl_crds.transform_to(cor2.coordinate_frame))\n\n###############################################################################\n# One of the bright features is actually Mars so let's also get that coordinate.\n# get the location of Mars.\nmars = get_body_heliographic_stonyhurst('mars', cor2.date, observer=cor2.observer_coordinate)\nmars_hpc = mars.transform_to(frames.Helioprojective(observer=cor2.observer_coordinate))\n\n###############################################################################\n# Let's plot the results.\nax = plt.subplot(projection=cor2)\n\n# Let's tweak the axis to show in degrees instead of arcsec\nlon, lat = ax.coords\nlon.set_major_formatter('d.dd')\nlat.set_major_formatter('d.dd')\n\ncor2.plot(axes=ax, vmin=0, vmax=600)\ncor2.draw_limb()\n\n# plot the position of Mars\nax.plot_coord(mars_hpc, 's', color='white', fillstyle='none', markersize=12, label='Mars')\n# Plot all of the stars\nfor this_coord in hpc_coords:\n ax.plot_coord(this_coord, 'o', color='white', fillstyle='none')\nplt.legend()\nplt.show()\n", "sub_path": "examples/units_and_coordinates/STEREO_SECCHI_starfield.py", "file_name": "STEREO_SECCHI_starfield.py", "file_ext": "py", "file_size_in_byte": 3960, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sunpy.net.helioviewer.HelioviewerClient", "line_number": 26, "usage_type": "call"}, {"api_name": "sunpy.net.helioviewer", "line_number": 26, "usage_type": "name"}, {"api_name": "sunpy.map.map.Map", "line_number": 28, "usage_type": "call"}, {"api_name": "sunpy.map.map", "line_number": 28, "usage_type": "attribute"}, {"api_name": "sunpy.map", "line_number": 28, "usage_type": "name"}, {"api_name": "astropy.coordinates.SkyCoord", "line_number": 39, "usage_type": "call"}, {"api_name": "astroquery.vizier.Vizier", "line_number": 46, "usage_type": "call"}, {"api_name": "astropy.units.deg", "line_number": 48, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 48, "usage_type": "name"}, {"api_name": "astropy.coordinates.SkyCoord", "line_number": 60, "usage_type": "call"}, {"api_name": "astropy.units.deg", "line_number": 60, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 60, "usage_type": "name"}, {"api_name": "astropy.units.km", "line_number": 61, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 61, "usage_type": "name"}, {"api_name": "sunpy.coordinates.get_body_heliographic_stonyhurst", "line_number": 67, "usage_type": "call"}, {"api_name": "sunpy.coordinates.frames.Helioprojective", "line_number": 68, "usage_type": "call"}, {"api_name": "sunpy.coordinates.frames", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}]} +{"seq_id": "399070454", "text": "import numpy as np\nfrom tqdm import tqdm\n# --------特征池的获取-------------\n\npath = '/home/kai/project/video-caption-pytorch/data/feats/c3d_feats/'\n\nall_feature = np.load('all_feature_8000.npy')\nall_id = np.load('all_id_8000.npy')\n\n\nfor i in tqdm (range (8001,13000)):\n video_feature= np.load(path+'video'+str(i)+'.npy')\n vec_id = np.arange(all_feature.shape[0],video_feature.shape[0]+all_feature.shape[0])\n video_id = np.linspace(i, i, video_feature.shape[0])\n id_matrix_feature = np.vstack((vec_id,video_id)).T\n\n all_feature = np.vstack((all_feature, video_feature))\n all_id = np.vstack((all_id,id_matrix_feature))\n\n if i == 11000 :\n np.save('all_feature_'+str(i)+'.npy',all_feature)\n np.save('all_id'+str(i)+'.npy',all_id)\n\nnp.save('all_feature_13000.npy',all_feature)\nnp.save('all_id_13000.npy',all_id)", "sub_path": "faiss_learn/feature_pool.py", "file_name": "feature_pool.py", "file_ext": "py", "file_size_in_byte": 860, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.load", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 8, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "12499205", "text": "#!/usr/bin/env python\n\n#===============================================================================\n# SWL_diseases_to_snps.py\n# \n# Adds semantic links to diseases (e.g.[[is-associated-with::xyz]]) in SNP pages. \n# Disease associations are identified separately by following wikilinks directed to/from an article in the SNPedia category 'medical condition'.\n# Snp-disease links provided in 'snpedia_disease_final.csv' \n# \n# Input required: snpedia_disease_final.csv, snp_gene (gene-snp associations, details in SNPediaImporter.py) \n#\n# Apr 28, 2011; Salvatore Loguercio\n#\n#===============================================================================\n\nimport json\nimport urllib\nimport re\nimport mwclient \nimport csv\nfrom itertools import groupby\n\n\n# Load snp_gene, a dict of lists where each gene (key) is associated with a list of SNPs\n\na=open('snp_gene','r')\nb=a.read()\ngene_snps=json.loads(b)\n\n\n# get all snps in a single list\n\nsnpList=[]\n\nfor item in gene_snps.values():\n \n for x in item:\n snpList.append(x)\n \n \n# Extract a dictionary of disease-snp key-values from the input file\n\ndisease_snp=dict()\nfor line in open('snpedia_disease_final.csv','rb'):\n k, v = line.strip(\"\\n\").split(\"\\t\")\n disease_snp[k]=v.decode('utf-8')\n \n\n# Make a dictionary of lists, with a list of associated diseases for every snp (key) \n \nsnpdict=dict()\nfor snp in snpList:\n dislist=[]\n \n it = iter(sorted(disease_snp.iteritems()))\n for i in range(len(disease_snp)): \n a=it.next()\n if a[1].find(snp+'|')!=-1:\n dislist.append(a[0])\n \n snpdict[snp]=dislist\n \n \n# save it (file: 'snp_disease')\n \nsnpdict_str=json.dumps(snpdict)\nsnpdict_obj=open('snp_disease','w')\nsnpdict_obj.write(snpdict_str)\nsnpdict_obj.close()\n\n\n# To load it:\n\n# a=open('snp_disease','r')\n# b=a.read()\n# snpdict_old=json.loads(b)\n\n# Initialize urllib, mwclient; login to the target wiki (username/password required)\n\nUrlTarget='http://127.0.0.1/mediawiki/api.php'\nUrlParams={'action': 'query','prop': 'revisions','rvprop': 'content','format': 'json'}\n \nsite = mwclient.Site('127.0.0.1',path='/mediawiki/')\nsite.login('','')\n\n\n# WriteAPI loop\n\nfor snp in snpList:\n if len(snpdict[snp])!=0:\n print(snp)\n UrlParams['titles'] = snp # get snp page content from the target wiki\n f = urllib.urlopen(UrlTarget, urllib.urlencode(UrlParams))\n z = f.read()\n output2 = json.loads(z)\n pages2 = output2['query']['pages'].keys()\n if pages2[0]!=u'-1': # if the page exists\n content2 = output2['query']['pages'][pages2[0]]['revisions'][0]['*'].encode('utf-8')\n \n for j in range(len(snpdict[snp])):\n sl='\\n[[is-associated-with::'+snpdict[snp][j]+'| ]]' # add hidden semantic links to diseases at the bottom of the page\n content2 = content2+sl\n print(snpdict[snp][j])\n \n snppage=site.Pages[snp] # save edits\n res=snppage.save(content2,summary='Adding diseases to snps')\n\n\n# TODO: improve exception handling \n", "sub_path": "python/snpediamashup/SWL_diseases_to_snps.py", "file_name": "SWL_diseases_to_snps.py", "file_ext": "py", "file_size_in_byte": 3188, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.loads", "line_number": 28, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 66, "usage_type": "call"}, {"api_name": "mwclient.Site", "line_number": 83, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 93, "usage_type": "call"}, {"api_name": "urllib.urlencode", "line_number": 93, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 95, "usage_type": "call"}]} +{"seq_id": "17728526", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport Tkinter as tk\nimport Pmw\nimport json\n\n\nclass GOL():\n \"\"\"Status manager of GOL(Game of Life).\n\n Each world in game of life is a set of cells, and status of\n every cell should be alive or dead. Status changes from gen\n -eration to generation.\n \"\"\"\n def __init__(self, row = 0, col = 0):\n \"\"\"Init size and status of world.\"\"\"\n self.row = row\n self.col = col\n self.now = {}\n self.next = {}\n self.init_status([])\n\n def init_status(self, init_cells):\n \"\"\"Set status of world.\n\n if the begining status given is not empty, then use them\n to initialize the world.\n\n Args:\n init_cells: begining status given. It's a tow-dimensional\n array. Becase its size maybe smaller than the\n world, we should be map each coordinate to the\n center area of world.\n \"\"\"\n\n # get size of begining status set\n init_row = len(init_cells)\n if (init_row == 0):\n init_col = 0\n else:\n init_col = len(init_cells[0])\n # compute offset in row direction and column direction\n row_off = (self.row - init_row) / 2\n col_off = (self.col - init_col) / 2\n\n # check size\n if (row_off < 0 or col_off < 0):\n raise Exception(\"Size of begining status set is too large\")\n\n # create the world\n for crow in range(self.row):\n for ccol in range(self.col):\n srow = crow - row_off\n scol = ccol - col_off\n if (crow in range(row_off, row_off + init_row)\n and\n ccol in range(col_off, col_off + init_col)):\n self.now[crow, ccol] = init_cells[srow][scol]\n else:\n self.now[crow, ccol] = False;\n self.next[crow, ccol] = False;\n\n def update(self):\n \"\"\"Update status of world by status before.\n\n For each cell in world, do these things:\n 1. look and find how many alive neighbors around,each cell\n have eight neighbors\n 2. update status of cell according the number of its alive\n neighbors. The following are the rules\n + if cell is alive, and number of neighbors is too small\n (less than 2) or too too much(more than 3), this cell\n will die, or it will be keep alive\n + if cell is dead, and number of neighbors is three, then\n cell will be alive\n \"\"\"\n self.next = self.now.copy()\n for crow in range(self.row):\n for ccol in range(self.col):\n around = self.neighbors(crow, ccol)\n if (around < 2 or around > 3):\n self.next[crow, ccol] = False\n\n elif ((not self.now[crow, ccol]) and\n around == 3):\n self.next[crow, ccol] = True\n\n self.now = self.next.copy()\n return self.now\n\n def neighbors(self, row, col):\n \"\"\"Compute number of alive neighbors around a cell.\"\"\"\n alive_around = 0\n for i in range(row -1, row + 2):\n for j in range(col - 1, col + 2):\n irow = i % self.row\n icol = j % self.col\n if (not (irow == row and icol == col)):\n if (self.now[irow, icol]):\n alive_around = alive_around + 1\n\n return alive_around\n\n\nclass ShowGOL(tk.Tk):\n \"\"\"Diasplay the Game of Life\n\n Use Tkinter to draw the world of cells and the changes in\n the world.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Init resource and world\"\"\"\n # init resource\n tk.Tk.__init__(self, *args, **kwargs)\n self.setup_members() # initialize class members\n self.setup_window() # root window\n self.setup_toolbar() # tool bar\n self.setup_canvas() # canvas to draw world\n\n # init world\n self.create_world()\n\n # make world alive\n self.after(5, lambda: self.life(5))\n\n def setup_members(self):\n \"\"\"Initialize class members\n\n These members are main information of class.They are information\n of status, widget, resource and so on\n \"\"\"\n ### cell\n self.cell_size = 8\n self.cell_row = 80\n self.cell_col = 100\n self.color_alive = \"black\"\n self.color_dead = \"white\"\n\n ### world\n self.init_modes = {} # read modes from json file\n self.init_world = {} # begining status\n self.world = {} # world's map\n # current status of world\n self.world_status = GOL(self.cell_row, self.cell_col)\n self.world_setable = True\n self.world_alive = False\n\n # widgets\n self.toolbar_height = 40\n self.world_size = [self.cell_size * self.cell_row,\n self.cell_size * self.cell_col]\n self.window_size = self.world_size\n self.window_size[0] += self.toolbar_height\n\n # resource\n self.saver_icon = \"save.gif\"\n self.run_icon = \"run.gif\"\n self.pause_icon = \"pause.gif\"\n self.stop_icon = \"stop.gif\"\n self.modes_file = \"gol.json\"\n self.modes_names = []\n\n def setup_window(self):\n \"\"\"Create root window\"\"\"\n # make window in the center of screen\n scrn_width, scrn_height = self.maxsize()\n win_height, win_width = self.window_size\n location = '%dx%d+%d+%d'%(win_width, win_height,\n (scrn_width - win_width) / 2,\n (scrn_height - win_height) / 2)\n self.geometry(location)\n\n # set title\n self.title(\"Game of life\")\n\n def setup_toolbar(self):\n \"\"\"Create tool bar\"\"\"\n # create frame to contain buttons\n self.toolbar = tk.Frame(self, height=self.toolbar_height)\n self.toolbar.grid(row = 0, column = 0,\n sticky = tk.N+tk.S+tk.W+tk.E)\n\n # set tools\n self.setup_mode_selector()\n self.setup_mode_saver()\n self.setup_button_run()\n self.setup_button_pause()\n self.setup_button_stop()\n\n def setup_mode_selector(self):\n \"\"\"Mode selector\n\n User can select begining status of the world already exists,\n these status are called 'modes' here, and modes are save in\n file with json format\n \"\"\"\n # read modes from json file\n # TODO use more simple ways to read\n modes_reader = file(self.modes_file)\n self.init_modes = json.load(modes_reader)\n\n # set selector\n self.modes_names = self.init_modes.keys()\n self.modes_names.insert(0, \"Set by hand\")\n self.modes_selector = Pmw.ComboBox(\n self.toolbar,\n label_text = 'Modes selector',\n labelpos = 'nw',\n selectioncommand = self.prepare_world,\n scrolledlist_items = self.modes_names,\n )\n self.modes_selector.grid(row = 0, column = 0, sticky = tk.W)\n first = self.modes_names[0]\n self.modes_selector.selectitem(first)\n self.prepare_world(first)\n\n def setup_mode_saver(self):\n \"\"\"Mode saver\n\n User can save begining status set by hand to json file.\n Sharing this json file with friends is also a good idea.\n \"\"\"\n saver_icon = tk.PhotoImage(file = self.saver_icon)\n self.saver_button = tk.Button(\n self.toolbar,\n width = 24,\n height = 24,\n image = saver_icon,\n command = self.save_mode)\n self.saver_button.image = saver_icon\n self.saver_button.grid(row = 0, column = 1, sticky = tk.W)\n\n def setup_button_run(self):\n \"\"\"Button to run the Game of Life\"\"\"\n run_icon = tk.PhotoImage(file = self.run_icon)\n self.button_run = tk.Button(\n self.toolbar,\n width = 24,\n height = 24,\n image = run_icon,\n command = self.run_world)\n self.button_run.image = run_icon\n self.button_run.grid(row = 0, column = 2, sticky = tk.W)\n\n def setup_button_pause(self):\n \"\"\"Button to pause the Game of Life\"\"\"\n pause_icon = tk.PhotoImage(file = self.pause_icon)\n self.button_pause = tk.Button(\n self.toolbar,\n width = 24,\n height = 24,\n image = pause_icon,\n command = self.pause_world)\n self.button_pause.image = pause_icon\n self.button_pause.grid(row = 0, column = 3, sticky = tk.W)\n\n def setup_button_stop(self):\n \"\"\"Button to stop the Game of Life\n\n stopping will set the world to a status initialized using\n the current item in modes selector\n \"\"\"\n stop_icon = tk.PhotoImage(file = self.stop_icon)\n self.button_stop = tk.Button(\n self.toolbar,\n width = 24,\n height = 24,\n image = stop_icon,\n command=self.reset_world)\n self.button_stop.image = stop_icon\n self.button_stop.grid(row = 0, column = 4, sticky=tk.W)\n\n def setup_canvas(self):\n \"\"\"Add canvas to root window\"\"\"\n # create frame to contain canvas\n self.world_container = tk.Frame(self,\n width = self.world_size[1],\n height = self.world_size[0])\n self.world_container.grid(row = 1, column = 0, sticky = tk.W+tk.N)\n\n # create canvas\n self.canvas = tk.Canvas(\n self.world_container,\n width = self.world_size[1],\n height = self.world_size[0],\n borderwidth = 1,\n highlightthickness = 0)\n self.canvas.grid(row = 0, column = 0, sticky = tk.W)\n self.canvas.bind('', self.click_cell)\n\n def create_world(self):\n \"\"\"Create world of cells\"\"\"\n for row in range(self.cell_row):\n for col in range(self.cell_col):\n x1 = col * self.cell_size\n y1 = row * self.cell_size\n x2 = x1 + self.cell_size\n y2 = y1 + self.cell_size\n\n if (self.world_status.now[row, col]):\n self.world[row, col] = self.canvas.create_rectangle(\n x1, y1, x2, y2,\n fill = self.color_alive,\n outline = \"gray\",\n tags = \"rect\")\n else:\n self.world[row, col] = self.canvas.create_rectangle(\n x1, y1, x2, y2,\n fill = self.color_dead,\n outline = \"gray\",\n tags = \"rect\")\n\n def life(self, delay):\n \"\"\"Loop of the Game of Life\"\"\"\n # if world is not alive, then do nothing\n if (self.world_alive):\n self.world_status.update()\n for row in range(self.cell_row):\n for col in range(self.cell_col):\n item_id = self.world[row, col]\n if (self.world_status.now[row, col]):\n self.canvas.itemconfig(item_id,\n fill = self.color_alive)\n else:\n self.canvas.itemconfig(item_id,\n fill = self.color_dead)\n\n self.after(delay, lambda: self.life(delay))\n\n def prepare_world(self, mode_name):\n \"\"\"Init status of world with mode selected\"\"\"\n self.world_alive = False\n self.world_setable = True\n if (self.init_modes.has_key(mode_name)):\n mode = self.init_modes[mode_name]\n self.world_status.init_status(mode)\n\n self.init_world = self.world_status.now.copy()\n if (not (len(self.world) == 0)):\n for row in range(self.cell_row):\n for col in range(self.cell_col):\n item_id = self.world[row, col]\n if (self.world_status.now[row, col]):\n self.canvas.itemconfig(item_id,\n fill = self.color_alive)\n else:\n self.canvas.itemconfig(item_id,\n fill = self.color_dead)\n\n def save_mode(self):\n \"\"\"Save init mode to json file\"\"\"\n def save_mode_file():\n name = dialog.entry.get()\n self.init_modes[name] = self.save_list\n with open(self.modes_file, 'wb') as fp:\n json.dump(self.init_modes, fp)\n self.world_alive = old_world_status[0]\n self.world_setable = old_world_status[1]\n self.modes_names.insert(1, name)\n self.modes_selector._list.setlist(self.modes_names)\n self.modes_selector.selectitem(name)\n dialog.destroy()\n\n old_world_status = [self.world_alive, self.world_setable]\n self.world_alive = False\n self.world_setable = False\n lu_row = 0\n lu_col = 0\n rb_row = self.cell_row - 1\n rb_col = self.cell_col - 1\n for row in range(self.cell_row):\n for col in range(self.cell_col):\n if (self.init_world[row, col]):\n lu_row = row\n break\n\n for col in range(self.cell_col):\n for row in range(self.cell_row):\n if (self.init_world[row, col]):\n lu_col = col\n break\n\n for row in range(self.cell_row - 1, -1, -1):\n for col in range(self.cell_col - 1, -1 , -1):\n if (self.init_world[row, col]):\n rb_row = row\n break\n\n for col in range(self.cell_col - 1, -1, -1):\n for row in range(self.cell_row -1, -1, -1):\n if (self.init_world[row, col]):\n rb_col = col\n break\n\n self.save_list = [[False for col in range(rb_col, lu_col + 1)]\n for row in range(rb_row, lu_row + 1)]\n\n for row in range(rb_row, lu_row + 1):\n for col in range(rb_col, lu_col + 1):\n self.save_list[row - rb_row][col - rb_col] = self.init_world[\n row, col]\n\n # show a dialog window to get name or new mode\n dialog = tk.Toplevel(self)\n dialog.label = tk.Label(dialog, text=\"Please enter the name of new mode\")\n dialog.label.grid(row = 0, column = 0, sticky = tk.N)\n dialog.entry = tk.Entry(dialog)\n dialog.entry.grid(row = 1, column = 0, sticky = tk.N)\n dialog.ok_button = tk.Button(dialog, text = \"OK\", command = save_mode_file)\n dialog.ok_button.grid(row = 2, column = 0, sticky = tk.N)\n self.wait_window(dialog)\n\n\n\n def run_world(self):\n \"\"\"Make the world alive\"\"\"\n self.world_alive = True\n self.world_setable = False\n\n def pause_world(self):\n \"\"\"Pause the world\"\"\"\n self.world_alive = False\n self.world_setable = True\n\n def reset_world(self):\n \"\"\"Reset world\"\"\"\n self.world_alive = False\n self.world_setable = True\n self.world_status.now = self.init_world.copy()\n for row in range(self.cell_row):\n for col in range(self.cell_col):\n item_id = self.world[row, col]\n if (self.world_status.now[row, col]):\n self.canvas.itemconfig(item_id,\n fill = self.color_alive)\n else:\n self.canvas.itemconfig(item_id,\n fill = self.color_dead)\n\n def click_cell(self, event):\n \"\"\"Set the cell mouse clicked\"\"\"\n if (self.world_setable):\n x, y = event.x, event.y\n row = y / self.cell_size\n col = x / self.cell_size\n if ((row in range(self.cell_row)) and\n (col in range(self.cell_col))):\n status_now = not self.world_status.now[row, col]\n if (status_now):\n color = self.color_alive\n else:\n color = self.color_dead\n item_id = self.world[row, col]\n self.canvas.itemconfig(item_id, fill=color)\n self.world_status.now[row, col] = status_now\n self.world_status.next = self.world_status.now.copy()\n self.init_world = self.world_status.now.copy()\n\n\nif __name__ == \"__main__\":\n app = ShowGOL()\n app.mainloop()\n", "sub_path": "pygol.py", "file_name": "pygol.py", "file_ext": "py", "file_size_in_byte": 16747, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "Tkinter.Tk", "line_number": 105, "usage_type": "attribute"}, {"api_name": "Tkinter.Tk.__init__", "line_number": 114, "usage_type": "call"}, {"api_name": "Tkinter.Tk", "line_number": 114, "usage_type": "attribute"}, {"api_name": "Tkinter.Frame", "line_number": 179, "usage_type": "call"}, {"api_name": "Tkinter.N", "line_number": 181, "usage_type": "attribute"}, {"api_name": "Tkinter.S", "line_number": 181, "usage_type": "attribute"}, {"api_name": "Tkinter.W", "line_number": 181, "usage_type": "attribute"}, {"api_name": "Tkinter.E", "line_number": 181, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 200, "usage_type": "call"}, {"api_name": "Pmw.ComboBox", "line_number": 205, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 212, "usage_type": "attribute"}, {"api_name": "Tkinter.PhotoImage", "line_number": 223, "usage_type": "call"}, {"api_name": "Tkinter.Button", "line_number": 224, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 231, "usage_type": "attribute"}, {"api_name": "Tkinter.PhotoImage", "line_number": 235, "usage_type": "call"}, {"api_name": "Tkinter.Button", "line_number": 236, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 243, "usage_type": "attribute"}, {"api_name": "Tkinter.PhotoImage", "line_number": 247, "usage_type": "call"}, {"api_name": "Tkinter.Button", "line_number": 248, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 255, "usage_type": "attribute"}, {"api_name": "Tkinter.PhotoImage", "line_number": 263, "usage_type": "call"}, {"api_name": "Tkinter.Button", "line_number": 264, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 271, "usage_type": "attribute"}, {"api_name": "Tkinter.Frame", "line_number": 276, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 279, "usage_type": "attribute"}, {"api_name": "Tkinter.N", "line_number": 279, "usage_type": "attribute"}, {"api_name": "Tkinter.Canvas", "line_number": 282, "usage_type": "call"}, {"api_name": "Tkinter.W", "line_number": 288, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 356, "usage_type": "call"}, {"api_name": "Tkinter.Toplevel", "line_number": 404, "usage_type": "call"}, {"api_name": "Tkinter.Label", "line_number": 405, "usage_type": "call"}, {"api_name": "Tkinter.N", "line_number": 406, "usage_type": "attribute"}, {"api_name": "Tkinter.Entry", "line_number": 407, "usage_type": "call"}, {"api_name": "Tkinter.N", "line_number": 408, "usage_type": "attribute"}, {"api_name": "Tkinter.Button", "line_number": 409, "usage_type": "call"}, {"api_name": "Tkinter.N", "line_number": 410, "usage_type": "attribute"}]} +{"seq_id": "492231741", "text": "# encoding: utf-8\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django.contrib.localflavor.fr.forms import FRZipCodeField as OriginalFRZipCodeField\n\n\nclass ZipCodeField(OriginalFRZipCodeField):\n default_error_messages = {\n 'invalid': _(u\"Enterez un code postal au format XXXXX.\"),\n }\n\n def __init__(self, max_length=5, min_length=5, *args, **kwargs):\n original_label = kwargs.get('label', _('Code postal'))\n super(ZipCodeField, self).__init__(*args, **kwargs)\n self.label = original_label", "sub_path": "django_extended/forms/zipcode.py", "file_name": "zipcode.py", "file_ext": "py", "file_size_in_byte": 567, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.contrib.localflavor.fr.forms.FRZipCodeField", "line_number": 9, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 11, "usage_type": "call"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "366394627", "text": "import copy\n\nfrom unittest import mock\n\nimport pytest # noqa: F401\n\nfrom lambda_router import events, routers\n\n\nclass TestSingleRoute:\n def test_add_route(self):\n router = routers.SingleRoute()\n assert router.route is None\n\n def test_route(event):\n return {\"message\": \"ok\"}\n\n router.add_route(fn=test_route)\n assert router.route is not None\n assert test_route == router.route\n\n def test_add_route_duplicate(self):\n router = routers.SingleRoute()\n\n def test_route(event):\n return {\"message\": \"ok\"}\n\n def second_route(event):\n return {\"mesage\": \"error\"}\n\n router.add_route(fn=test_route)\n with pytest.raises(ValueError) as e:\n router.add_route(fn=second_route)\n assert \"Single route is already defined\" in str(e.value)\n\n def test_dispatch(self):\n router = routers.SingleRoute()\n\n def test_route(event):\n return {\"message\": \"ok\"}\n\n router.add_route(fn=test_route)\n response = router.dispatch(event={})\n assert {\"message\": \"ok\"} == response\n\n def test_dispatch_without_route(self):\n router = routers.SingleRoute()\n with pytest.raises(ValueError) as e:\n router.dispatch(event={})\n assert \"No route defined\" in str(e.value)\n\n\nclass TestEventField:\n def test_add_route(self):\n router = routers.EventField(key=\"field\")\n\n def test_route_one(event):\n return {\"message\": \"ok\"}\n\n def test_route_two(event):\n return {\"message\": \"ok\"}\n\n router.add_route(fn=test_route_one, key=\"one\")\n router.add_route(fn=test_route_two, key=\"two\")\n assert router.routes\n assert 2 == len(router.routes)\n assert \"one\" in router.routes\n assert \"two\" in router.routes\n\n def test_get_route(self):\n router = routers.EventField(key=\"field\")\n router.add_route(fn=lambda event: \"ok\", key=\"test\")\n event = events.LambdaEvent(raw={\"field\": \"test\"}, app=None)\n route = router.get_route(event=event)\n assert route is not None\n assert callable(route)\n\n def test_get_route_with_invalid_key(self):\n router = routers.EventField(key=\"field\")\n router.add_route(fn=lambda event: \"ok\", key=\"test\")\n event = events.LambdaEvent(raw={\"field\": \"new\"}, app=None)\n with pytest.raises(ValueError) as e:\n router.get_route(event=event)\n assert \"No route configured for given field (field).\" in str(e.value)\n\n def test_get_route_with_missing_key(self):\n router = routers.EventField(key=\"route_on\")\n router.add_route(fn=lambda event: \"ok\", key=\"test\")\n event = events.LambdaEvent(raw={\"field\": \"new\"}, app=None)\n with pytest.raises(ValueError) as e:\n router.get_route(event=event)\n assert \"Routing key (route_on) is not present in the event.\" in str(e.value)\n\n def test_dispatch(self):\n router = routers.EventField(key=\"field\")\n\n def test_route_one(event):\n return {\"message\": \"ok\"}\n\n def test_route_two(event):\n return {\"message\": \"error\"}\n\n router.add_route(fn=test_route_one, key=\"one\")\n router.add_route(fn=test_route_two, key=\"two\")\n response = router.dispatch(event=events.LambdaEvent(raw={\"field\": \"one\"}, app=None))\n assert {\"message\": \"ok\"} == response\n response = router.dispatch(event=events.LambdaEvent(raw={\"field\": \"two\"}, app=None))\n assert {\"message\": \"error\"} == response\n\n def test_dispatch_without_route(self):\n router = routers.EventField(key=\"field\")\n with pytest.raises(ValueError) as e:\n router.dispatch(event=events.LambdaEvent(raw={}, app=None))\n assert \"No route configured\" in str(e.value)\n\n\n@pytest.fixture\ndef sqs_event():\n return events.LambdaEvent(\n raw={\n \"Records\": [\n {\n \"messageId\": \"a11e7a78-fb68-4c06-ae19-d391158f31ed\",\n \"receiptHandle\": \"<...>\",\n \"body\": (\n '{\"people_id\": \"daf2ccee-8b09-4710-998e-9d82c7e9bf17\", '\n '\"asset_id\": \"25ca5c11-2a01-4c00-96d2-8654807740c1\"}'\n ),\n \"attributes\": {\n \"ApproximateReceiveCount\": \"1\",\n \"SentTimestamp\": \"1579162532037\",\n \"SenderId\": \"test\",\n \"ApproximateFirstReceiveTimestamp\": \"1579162532048\",\n },\n \"messageAttributes\": {\n \"key\": {\n \"stringValue\": \"global.person_updated\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\",\n }\n },\n \"md5OfMessageAttributes\": \"50c840a210e7560a053b1f43fb9d2bf5\",\n \"md5OfBody\": \"cffa6aa7af0c2b20ef1fc63569ac299e\",\n \"eventSource\": \"aws:sqs\",\n \"eventSourceARN\": \"arn:aws:sqs:eu-west-1::events\",\n \"awsRegion\": \"eu-west-1\",\n }\n ]\n },\n app=None,\n )\n\n\nclass TestSQSMessage:\n def test_from_raw_sqs_message(self, sqs_event):\n raw_message = sqs_event.raw[\"Records\"][0]\n message = routers.SQSMessage.from_raw_sqs_message(raw_message=raw_message, key_name=\"key\", event=sqs_event)\n assert \"global.person_updated\" == message.key\n assert \"a11e7a78-fb68-4c06-ae19-d391158f31ed\" == message.meta[\"messageId\"]\n\n\nclass TestSQSMessageField:\n def test_add_route(self):\n router = routers.SQSMessageField(key=\"key\")\n\n def test_route_one(msg):\n return {\"message\": \"ok\"}\n\n def test_route_two(msg):\n return {\"message\": \"ok\"}\n\n router.add_route(fn=test_route_one, key=\"one\")\n router.add_route(fn=test_route_two, key=\"two\")\n assert router.routes\n assert 2 == len(router.routes)\n assert \"one\" in router.routes\n assert \"two\" in router.routes\n\n def test_get_route(self, sqs_event):\n router = routers.SQSMessageField(key=\"key\")\n router.add_route(fn=lambda msg: \"ok\", key=\"global.person_updated\")\n raw_message = sqs_event.raw[\"Records\"][0]\n message = router._get_message(raw_message, event=sqs_event)\n route = router.get_route(message=message)\n assert route is not None\n assert callable(route)\n\n def test_get_route_with_invalid_key(self, sqs_event):\n router = routers.SQSMessageField(key=\"key\")\n router.add_route(fn=lambda msg: \"ok\", key=\"test\")\n raw_message = sqs_event.raw[\"Records\"][0]\n message = router._get_message(raw_message, event=sqs_event)\n with pytest.raises(ValueError) as e:\n router.get_route(message=message)\n assert \"No route configured for given field (field).\" in str(e.value)\n\n def test_get_route_with_missing_key(self, sqs_event):\n router = routers.SQSMessageField(key=\"route_on\")\n router.add_route(fn=lambda msg: \"ok\", key=\"test\")\n raw_message = sqs_event.raw[\"Records\"][0]\n message = router._get_message(raw_message, event=sqs_event)\n with pytest.raises(ValueError) as e:\n router.get_route(message=message)\n assert \"Routing key (route_on) is not present in the event.\" in str(e.value)\n\n def test_dispatch(self, sqs_event):\n router = routers.SQSMessageField(key=\"key\")\n test_message_handler = mock.MagicMock()\n router.add_route(fn=test_message_handler, key=\"global.person_updated\")\n router.dispatch(event=sqs_event)\n test_message_handler.assert_called_once()\n\n def test_dispatch_multiple(self, sqs_event):\n router = routers.SQSMessageField(key=\"key\")\n # Duplicate message.\n raw_message = copy.deepcopy(sqs_event.raw[\"Records\"][0])\n sqs_event.raw[\"Records\"].append(raw_message)\n test_message_handler = mock.MagicMock()\n router.add_route(fn=test_message_handler, key=\"global.person_updated\")\n router.dispatch(event=sqs_event)\n assert 2 == test_message_handler.call_count\n\n def test_dispatch_multiple_with_different_keys(self, sqs_event):\n router = routers.SQSMessageField(key=\"key\")\n # Duplicate message.\n raw_message = copy.deepcopy(sqs_event.raw[\"Records\"][0])\n raw_message[\"messageAttributes\"][\"key\"][\"stringValue\"] = \"global.person_created\"\n sqs_event.raw[\"Records\"].append(raw_message)\n first_message_handler = mock.MagicMock()\n second_message_handler = mock.MagicMock()\n router.add_route(fn=first_message_handler, key=\"global.person_updated\")\n router.add_route(fn=second_message_handler, key=\"global.person_created\")\n router.dispatch(event=sqs_event)\n first_message_handler.assert_called_once()\n second_message_handler.assert_called_once()\n\n\nclass TestGenericSQSRouter:\n def test_add_route(self):\n router = routers.GenericSQSMessage()\n\n def test_route_one(msg):\n return {\"message\": \"ok\"}\n\n router.add_route(fn=test_route_one)\n assert router.route\n\n def test_get_route(self, sqs_event):\n router = routers.GenericSQSMessage()\n router.add_route(fn=lambda msg: \"ok\")\n raw_message = sqs_event.raw[\"Records\"][0]\n message = router._get_message(raw_message, event=sqs_event)\n route = router.get_route(message=message)\n assert route is not None\n assert callable(route)\n\n def test_dispatch(self, sqs_event):\n router = routers.GenericSQSMessage()\n test_message_handler = mock.MagicMock()\n router.add_route(fn=test_message_handler)\n router.dispatch(event=sqs_event)\n test_message_handler.assert_called_once()\n", "sub_path": "tests/test_routers.py", "file_name": "test_routers.py", "file_ext": "py", "file_size_in_byte": 9975, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "lambda_router.routers.SingleRoute", "line_number": 12, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 12, "usage_type": "name"}, {"api_name": "lambda_router.routers.SingleRoute", "line_number": 23, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 23, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 32, "usage_type": "call"}, {"api_name": "lambda_router.routers.SingleRoute", "line_number": 37, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 37, "usage_type": "name"}, {"api_name": "lambda_router.routers.SingleRoute", "line_number": 47, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 47, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 48, "usage_type": "call"}, {"api_name": "lambda_router.routers.EventField", "line_number": 55, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 55, "usage_type": "name"}, {"api_name": "lambda_router.routers.EventField", "line_number": 71, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 71, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 73, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 73, "usage_type": "name"}, {"api_name": "lambda_router.routers.EventField", "line_number": 79, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 79, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 81, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 81, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 82, "usage_type": "call"}, {"api_name": "lambda_router.routers.EventField", "line_number": 87, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 87, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 89, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 89, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 90, "usage_type": "call"}, {"api_name": "lambda_router.routers.EventField", "line_number": 95, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 95, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 105, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 105, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 107, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 107, "usage_type": "name"}, {"api_name": "lambda_router.routers.EventField", "line_number": 111, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 111, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 112, "usage_type": "call"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 113, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 113, "usage_type": "name"}, {"api_name": "lambda_router.events.LambdaEvent", "line_number": 119, "usage_type": "call"}, {"api_name": "lambda_router.events", "line_number": 119, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 117, "usage_type": "attribute"}, {"api_name": "lambda_router.routers.SQSMessage.from_raw_sqs_message", "line_number": 158, "usage_type": "call"}, {"api_name": "lambda_router.routers.SQSMessage", "line_number": 158, "usage_type": "attribute"}, {"api_name": "lambda_router.routers", "line_number": 158, "usage_type": "name"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 165, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 165, "usage_type": "name"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 181, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 181, "usage_type": "name"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 190, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 190, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 194, "usage_type": "call"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 199, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 199, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 203, "usage_type": "call"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 208, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 208, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 209, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 209, "usage_type": "name"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 215, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 215, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 217, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 219, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 219, "usage_type": "name"}, {"api_name": "lambda_router.routers.SQSMessageField", "line_number": 225, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 225, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 227, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 230, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 230, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 231, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 231, "usage_type": "name"}, {"api_name": "lambda_router.routers.GenericSQSMessage", "line_number": 241, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 241, "usage_type": "name"}, {"api_name": "lambda_router.routers.GenericSQSMessage", "line_number": 250, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 250, "usage_type": "name"}, {"api_name": "lambda_router.routers.GenericSQSMessage", "line_number": 259, "usage_type": "call"}, {"api_name": "lambda_router.routers", "line_number": 259, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 260, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 260, "usage_type": "name"}]} +{"seq_id": "335212485", "text": "# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"mamiruzz\"\n__date__ = \"$Aug 10, 2017 9:08:43 PM$\"\n\nif __name__ == \"__main__\":\n print (\"Learn 8 experiment: based on https://pythonprogramming.net/convolutional-neural-network-kats-vs-dogs-machine-learning-tutorial/\")\n\n\nimport cv2\nimport numpy as np\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\n # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion\n\n\nTRAIN_DIR = 'C:\\\\Users\\\\mamiruzz\\\\Downloads\\\\Netbeans\\\\Python\\\\kaggledata\\\\train'\nTEST_DIR = 'C:\\\\Users\\\\mamiruzz\\\\Downloads\\\\Netbeans\\\\Python\\\\kaggledata\\\\test'\nIMG_SIZE = 16\nLR = 1e-3\n\nMODEL_NAME = 'AmirNet-{}-{}.model'.format(LR, '8conv-basic') # just so we remember which saved model is which, sizes must match\n\ndef label_img(img):\n #word_label = img.split('.')[-3]\n word_label = img.split('.')[-3]\n # conversion to one-hot array [cat,dog]\n # [much cat, no dog, no cow]\n if word_label == 'cat': return [1, 0, 0]\n # [no cat, very doggo, no cow]\n elif word_label == 'dog': return [0, 1, 0]\n # [no cat, no dog, very cow]\n elif word_label == 'cow': return [0, 0, 1]\n \ndef create_train_data():\n training_data = []\n for img in tqdm(os.listdir(TRAIN_DIR)):\n #img = [cat, dog]\n label = label_img(img)\n path = os.path.join(TRAIN_DIR, img)\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n training_data.append([np.array(img), np.array(label)])\n shuffle(training_data)\n np.save('train_data.npy', training_data)\n return training_data\n\ndef process_test_data():\n testing_data = []\n for img in tqdm(os.listdir(TEST_DIR)):\n path = os.path.join(TEST_DIR, img)\n img_num = img.split('.')[0]\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n testing_data.append([np.array(img), img_num])\n \n shuffle(testing_data)\n np.save('test_data.npy', testing_data)\n return testing_data\n\n#train_data = create_train_data()\n#testing_data = process_test_data()\n\n# If you have already created the dataset:\n#train_data = np.load('train_data.npy')\n#testing_data = np.load('test_data.npy')\n\nimport os.path\n\nif os.path.isfile('train_data.npy'):\n train_data = np.load('train_data.npy')\nelse:\n train_data = create_train_data()\n \nif os.path.isfile('test_data.npy'):\n testing_data = np.load('test_data.npy')\nelse:\n testing_data = process_test_data()\n \n\n\n\n#define neural network\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\n#convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n#\n#convnet = conv_2d(convnet, 32, 5, activation='relu')\n#convnet = max_pool_2d(convnet, 5)\n#\n#convnet = conv_2d(convnet, 64, 5, activation='relu')\n#convnet = max_pool_2d(convnet, 5)\n#\n#convnet = fully_connected(convnet, 1024, activation='relu')\n#convnet = dropout(convnet, 0.8)\n#\n##change the value 2 to number of classes\n#convnet = fully_connected(convnet, 2, activation='softmax')\n#convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n#\n#model = tflearn.DNN(convnet, tensorboard_dir='log')\n\n# adding more layers\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 128, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\nconvnet = fully_connected(convnet, 3, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet, tensorboard_dir='log')\n\n\n# model\nif os.path.exists('{}.meta'.format(MODEL_NAME)):\n model.load(MODEL_NAME)\n print('model loaded!')\n\ntrain = train_data[:-500]\ntest = train_data[-500:]\n\n#to separate my features and labels\nX = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\nY = [i[1] for i in train]\n\ntest_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\ntest_y = [i[1] for i in test]\n\n#fit for 1 epochs\nmodel.fit({'input': X}, {'targets': Y}, n_epoch=1, validation_set=({'input': test_x}, {'targets': test_y}), \n snapshot_step=500, show_metric=True, run_id=MODEL_NAME)\n\n#save model\nmodel.save(MODEL_NAME)\n\n\n\nimport matplotlib.pyplot as plt\n\n# if you need to create the data:\n#test_data = process_test_data()\n# if you already have some saved:\ntest_data = np.load('test_data.npy')\n\nfig = plt.figure()\n\nfor num, data in enumerate(test_data[:16]):\n # cat: [1,0]\n # dog: [0,1]\n \n img_num = data[1]\n img_data = data[0]\n \n y = fig.add_subplot(4, 4, num + 1)\n orig = img_data\n data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1)\n #model_out = model.predict([data])[0]\n model_out = model.predict([data])[0]\n \n# if np.argmax(model_out) == 1: str_label = 'Cow'\n# elif np.argmax(model_out) == 2: str_label = 'Dog'\n# else: str_label = 'Cat'\n argmaxValue = np.argmax(model_out)\n str_label = str(np.argmax(model_out))\n# if(str_label =='1'): str_label = 'Cow'\n# elif(str_label =='0'): str_label = 'Dog'\n \n \n y.imshow(orig, cmap='gray')\n #y.imshow(orig)\n plt.title(str_label)\n y.axes.get_xaxis().set_visible(False)\n y.axes.get_yaxis().set_visible(False)\nplt.show()\n\nwith open('submission_file.csv','w') as f:\n f.write('id,label\\n')\n \nwith open('submission_file.csv','a') as f:\n for data in tqdm(test_data):\n img_num = data[1]\n img_data = data[0]\n orig = img_data\n data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n model_out = model.predict([data])[0]\n f.write('{},{}\\n'.format(img_num,model_out[1]))\n\nprint (\"Still working\")", "sub_path": "Experiment.py", "file_name": "Experiment.py", "file_ext": "py", "file_size_in_byte": 6680, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "tqdm.tqdm", "line_number": 40, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 48, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 53, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 56, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 79, "usage_type": "call"}, {"api_name": "tflearn.layers.core.input_data", "line_number": 110, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 112, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 113, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 115, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 116, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 118, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 119, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 121, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 122, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 124, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 125, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 127, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 128, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.conv_2d", "line_number": 130, "usage_type": "call"}, {"api_name": "tflearn.layers.conv.max_pool_2d", "line_number": 131, "usage_type": "call"}, {"api_name": "tflearn.layers.core.fully_connected", "line_number": 133, "usage_type": "call"}, {"api_name": "tflearn.layers.core.dropout", "line_number": 134, "usage_type": "call"}, {"api_name": "tflearn.layers.core.fully_connected", "line_number": 136, "usage_type": "call"}, {"api_name": "tflearn.layers.estimator.regression", "line_number": 137, "usage_type": "call"}, {"api_name": "tflearn.DNN", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 208, "usage_type": "call"}]} +{"seq_id": "500579891", "text": "import os\nimport datetime\nimport json\n\nimport random\n\n\n\n\nfolder = \"//192.168.10.50/LaCie\"\nindex = dict()\n\ndef modification_date(filename):\n\ttry:\n\t\tt = os.path.getmtime(filename)\n\t\treturn datetime.datetime.fromtimestamp(t)\n\texcept: return None\n\ndef jread(file):\n\n\twith open(file, \"r\") as jsonFile:\n\t\treturn json.load(jsonFile)\n\ndef jwrite(file,data):\n\tinfo = json.dumps(data, sort_keys=True, indent=4)\n\n\tf=open(file,\"w\")\n\tf.write(info)\n\tf.close()\n\n'''\nfor root, dirs, files in os.walk( folder ):\n\troot = root.replace( \"\\\\\", \"/\" )\n\tfor f in files:\n\t\tname = f\n\t\tpath = root + \"/\" + name\n\t\tprint (path)\n\t\tif os.path.isfile( path ):\n\t\t\tdate = str(modification_date(path))\n\t\t\tsize = int(os.path.getsize( path ))\n\n\t\t\tdates = dict({ \"name\": name, \"path\":path, \"date\":date, \"size\":size })\n\t\t\thash = \"%032x\" % random.getrandbits( 128 )\n\t\t\tindex[ hash ] = dates\n\njwrite(\"info.json\", index)\n\n'''\n\n\nsizes=[]\nmov=[]\nfor name, element in jread(\"info.json\").items():\n\trutas = element[\"path\"]\n\te = name[1:].split(\".\")[-1]\n\tsizes.append((element[\"size\"], element[\"name\"]))\n\tif len(e) < 7:\n\t\tif e ==\"mp4\" :\n\t\t\tmov.append(e)\n\nrepeditdos=[]\nbefore = [0,\"0\"]\nrep = []\nfor s, n in sorted(sizes):\n\n\t\n\tif s == before[0] and n == before[1]:\n\t\trep.append( n )\n\telse: \n\t\tif len( rep ) > 1:\n\t\t\trepeditdos.append( (before[0] ,rep))\n\t\trep = []\n\n\t\t\n\tbefore = [s,n]\n\ntotal=0\nfor size, name in repeditdos:\n\ttotal += ( len( name) - 1 ) * size\n\nprint (total)", "sub_path": "code/core/indexar.py", "file_name": "indexar.py", "file_ext": "py", "file_size_in_byte": 1424, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.getmtime", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 22, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "311650102", "text": "import os\nimport numpy as np\nimport lap\nimport random\nimport cv2\nimport torch\n\ndef iou(a, b, criterion=\"union\"):\n \"\"\"\n boxoverlap computes intersection over union for bbox a and b in KITTI format.\n If the criterion is 'union', overlap = (a inter b) / a union b).\n If the criterion is 'a', overlap = (a inter b) / a, where b should be a dontcare area.\n \"\"\"\n\n x1 = np.maximum(a[0], b[0])\n y1 = np.maximum(a[1], b[1])\n x2 = np.minimum(a[2], b[2])\n y2 = np.minimum(a[3], b[3])\n\n w = np.maximum(0., x2 - x1)\n h = np.maximum(0., y2 - y1)\n\n inter = w * h\n aarea = (a[2] - a[0]) * (a[3] - a[1])\n barea = (b[2] - b[0]) * (b[3] - b[1])\n # intersection over union overlap\n if criterion.lower() == \"union\":\n o = inter / float(aarea + barea - inter)\n elif criterion.lower() == \"a\":\n o = float(inter) / float(aarea)\n else:\n raise TypeError(\"Unkown type for criterion\")\n return o\n\ndef linear_assignment(cost_matrix):\n try:\n import lap\n _, x, y = lap.lapjv(cost_matrix, extend_cost=True)\n return np.array([[y[i], i] for i in x if i >= 0])\n except ImportError:\n from scipy.optimize import linear_sum_assignment\n x, y = linear_assignment(cost_matrix)\n return np.array(list(zip(x, y)))\n\n\ndef associate_det_to_trk(dets, trks, iou_threshold=0.3):\n if(len(trks) == 0):\n return np.empty((0, 2), dtype=int), np.arange(len(dets)), np.empty((0, 5))\n iou_matrix = np.zeros((len(dets), len(trks)))\n\n for d, det in enumerate(dets):\n for t, trk in enumerate(trks):\n iou_matrix[d, t] = iou(det, trk)\n\n if min(iou_matrix.shape) > 0:\n a = (iou_matrix > iou_threshold).astype(np.int32)\n if a.sum(1).max() == 1 and a.sum(0).max() == 1:\n matched_indices = np.stack(np.where(a), axis=1)\n else:\n matched_indices = linear_assignment(-iou_matrix)\n else:\n matched_indices = np.empty(shape=(0, 2))\n\n unmatched_detections = []\n for d, det in enumerate(dets):\n if d not in matched_indices[:, 0]:\n unmatched_detections.append(d)\n unmatched_trackers = []\n for t, trk in enumerate(trks):\n if t not in matched_indices[:, 1]:\n unmatched_trackers.append(t)\n\n matches = []\n for m in matched_indices:\n if iou_matrix[m[0], m[1]] < iou_threshold:\n unmatched_detections.append(m[0])\n unmatched_trackers.append(m[1])\n else:\n matches.append(m.reshape(1, 2))\n if len(matches) == 0:\n matches = np.empty((0, 2), dtype=int)\n else:\n matches = np.concatenate(matches, axis=0)\n\n return matches, np.array(unmatched_detections), np.array(unmatched_trackers)\n\nclass KittiDataLoader():\n def __init__(self, data_root_path, image_root, annotation_root, det_root, training_set, validation_set, testing_set, seq_num, transform=None):\n self.data_root_path = data_root_path\n self.image_root_path = os.path.join(self.data_root_path, image_root)\n self.annotation_root_path = os.path.join(self.data_root_path, annotation_root)\n self.det_root_path = os.path.join(self.data_root_path, det_root)\n self.transform = transform\n self.seq_num = seq_num\n self.det_dict = self.get_detections()\n self.gt_dict = self.get_annotations()\n self.get_TD_label()\n self.dataset_split = {'train': training_set, 'val': validation_set, 'test': testing_set}\n self.index = {'train': 0, 'val': 0, 'test': 0}\n self.datasets = {'train': self.generate_samples('train'),\n 'val': self.generate_samples('val'),\n 'test': self.generate_samples('test')}\n\n\n \n def get_detections(self):\n det_dict = {x:{} for x in range(self.seq_num)}\n det_files = os.listdir(self.det_root_path)\n det_files.sort()\n for det_fn in det_files:\n seq = int(det_fn.split('.')[0])\n det_path = os.path.join(self.det_root_path, det_fn)\n dets = open(det_path).readlines()\n dets_anno = [det.strip('\\r\\n').strip('\\n').split(',') for det in dets]\n last_frame = int(dets_anno[-1][0])\n seq_dets = {x:[] for x in range(last_frame+1)}\n for det_ann in dets_anno:\n frame_id = int(det_ann[0])\n conf = float(det_ann[6])\n if conf < 0.5:\n continue\n bbox = list(map(float, det_ann[2:6]))\n bbox[2] += bbox[0]\n bbox[3] += bbox[1]\n #ann = [bbox, -1]\n bbox.extend([-1])\n seq_dets[frame_id].append(bbox)\n det_dict[seq] = seq_dets\n \n return det_dict\n\n\n def get_annotations(self):\n gt_dict = {x:{} for x in range(self.seq_num)}\n gt_files = os.listdir(self.annotation_root_path)\n gt_files.sort()\n for gt_fn in gt_files:\n seq = int(gt_fn.split('.')[0])\n gt_path = os.path.join(self.annotation_root_path, gt_fn)\n gts = open(gt_path).readlines()\n gt_annos = [gt.strip('\\r\\n').strip('\\n').split(' ') for gt in gts]\n last_frame = int(gt_annos[-1][0])\n seq_gt = {x: [] for x in range(last_frame+1)}\n for gt_ann in gt_annos:\n if gt_ann[2] == 'Car' or gt_ann[2] == 'Van':\n frame_id = int(gt_ann[0])\n id = int(gt_ann[1])\n bbox = list(map(float, gt_ann[6:10]))\n #ann = {'id': id, 'bbox': bbox}\n #ann = [bbox, id]\n bbox.extend([id])\n seq_gt[frame_id].append(bbox)\n gt_dict[seq] = seq_gt\n return gt_dict\n\n def get_TD_label(self):\n # if matched with gt, assign track_id\n for seq, seq_dets in self.det_dict.items():\n seq_gt = self.gt_dict[seq]\n for frame, frame_det in seq_dets.items():\n frame_gt = seq_gt[frame]\n frame_det_np = np.array(frame_det)\n frame_gt_np = np.array(frame_gt)\n matched, unmatched_dets, unmatched_gts = associate_det_to_trk(frame_det_np, frame_gt_np)\n for m in matched:\n id = int(frame_gt_np[m[1], -1])\n frame_det[m[0]][-1] = id\n\n def generate_samples(self, data_type):\n all_samples = []\n seq_list = self.dataset_split[data_type]\n random.shuffle(seq_list)\n for seq in seq_list:\n seq_dets = self.det_dict[seq]\n frame_list = list(seq_dets.keys())\n for i in range(len(2, frame_list)-1):\n gallery_images = []\n gallery_labels = []\n query_images = []\n query_labels = []\n x_batch = []\n y_batch = []\n frame_batch = []\n\n frame_g = frame_list[i+1]\n frame_q = frame_list[i]\n frame_h1 = frame_list[i-2]\n frame_h2 = frame_list[i-1]\n frame_batch.append([frame_h1, frame_h2, frame_q, frame_g])\n\n img_g_path = os.path.join(self.image_root_path, '%04d' %seq, '%06d.png' %frame_g)\n img_q_path = os.path.join(self.image_root_path, '%04d' %seq, '%06d.png' %frame_q)\n\n img_g = cv2.imread(img_g_path)\n img_q = cv2.imread(img_q_path)\n\n h1_dets = seq_dets[frame_h1]\n h2_dets = seq_dets[frame_h2]\n gallery_dets = seq_dets[frame_g]\n query_dets = seq_dets[frame_q]\n\n if len(gallery_dets) == 0 or len(query_dets) == 0 or len(h1_dets) == 0 or len(h2_dets) == 0:\n continue\n \n\n w, h = 1280, 375\n\n id2label = {}\n j = 0\n\n idWithPosY = []\n for det in gallery_dets:\n bbox = list(map(int, det[:4]))\n id = det[4]\n det_img = img_g[bbox[1]:bbox[3], bbox[0]:bbox[2], :]\n if self.transform:\n det_img = self.transform(det_img)\n if id == -1:\n id2label[id] = j\n label = j\n j += 1\n gallery_images.append(det_img)\n gallery_labels.append(label)\n\n bbox = det[:4]\n center_x = (bbox[2] - bbox[0]) / 2 + bbox[0]\n center_y = (bbox[3] - bbox[1]) / 2 + bbox[1]\n\n center_x_norm = (2 * center_x / w) - 1\n center_y_norm = (2 * center_y / h) - 1\n\n idWithPosY.append([center_x_norm, center_y_norm])\n y_batch.append(idWithPosY)\n\n idWithPosQ = []\n for det in query_dets:\n bbox = list(map(int, det[:4]))\n id = det[4]\n det_img = img_q[bbox[1]:bbox[3], bbox[0]:bbox[2], :]\n if self.transform:\n det_img = self.transform(det_img)\n if id != -1:\n if id in id2label:\n label = id2label[id]\n else:\n continue\n query_images.append(det_img)\n query_labels.append(label)\n\n bbox = det[:4]\n center_x = (bbox[2] - bbox[0]) / 2 + bbox[0]\n center_y = (bbox[3] - bbox[1]) / 2 + bbox[1]\n\n center_x_norm = (2 * center_x / w) - 1\n center_y_norm = (2 * center_y / h) - 1\n\n idWithPosQ.append([label, center_x_norm, center_y_norm])\n \n if len(gallery_images) == 0 or len(query_images) == 0:\n continue\n\n idWithPos1 = []\n for det in h1_dets:\n id = det[4]\n if id != -1:\n if id in id2label:\n label = id2label[id]\n else:\n continue\n bbox = det[:4]\n center_x = (bbox[2] - bbox[0]) / 2 + bbox[0]\n center_y = (bbox[3] - bbox[1]) / 2 + bbox[1]\n\n center_x_norm = (2 * center_x / w) - 1\n center_y_norm = (2 * center_y / h) - 1\n\n idWithPos1.append([label, center_x_norm, center_y_norm])\n\n idWithPos2 = []\n for det in h2_dets:\n id = det[4]\n if id != -1:\n if id in id2label:\n label = id2label[id]\n else:\n continue\n bbox = det[:4]\n center_x = (bbox[2] - bbox[0]) / 2 + bbox[0]\n center_y = (bbox[3] - bbox[1]) / 2 + bbox[1]\n\n center_x_norm = (2 * center_x / w) - 1\n center_y_norm = (2 * center_y / h) - 1\n\n idWithPos2.append([label, center_x_norm, center_y_norm])\n \n idWithPosG = []\n for det in gallery_dets:\n id = det[4]\n if id != -1:\n if id in id2label:\n label = id2label[id]\n else:\n continue\n bbox = det[:4]\n center_x = (bbox[2] - bbox[0]) / 2 + bbox[0]\n center_y = (bbox[3] - bbox[1]) / 2 + bbox[1]\n\n center_x_norm = (2 * center_x / w) - 1\n center_y_norm = (2 * center_y / h) - 1\n\n idWithPosG.append([label, center_x_norm, center_y_norm])\n x_batch.append([idWithPos1, idWithPos2, idWithPosQ, idWithPosG])\n\n all_samples.append([gallery_images, gallery_labels, query_images, query_labels, j, x_batch, y_batch, frame_batch, [seq]])\n random.shuffle(all_samples)\n return all_samples\n\n def get_iter_num(self, data_type):\n return len(self.datasets[data_type])\n\n def get_batch(self, data_type):\n all_samples = self.datasets[data_type]\n if self.index[data_type] >= len(all_samples):\n self.index[data_type] = 0\n ind = self.index[data_type]\n gallery_images, gallery_labels, query_images, query_labels, num_class, x_batch, y_batch, frame_batch, d = all_samples[ind]\n self.index[data_type] += 1\n return np.array(gallery_images), np.array(gallery_labels), np.array(query_images), np.array(query_labels), num_class, x_batch, y_batch, frame_batch, d\n\n\nclass Resizer(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n \n def __init__(self, img_size):\n self.img_size = img_size\n\n def __call__(self, image):\n height, width, _ = image.shape\n if height > width:\n scale = self.img_size / height\n resized_height = self.img_size\n resized_width = int(width * scale)\n else:\n scale = self.img_size / width\n resized_height = int(height * scale)\n resized_width = self.img_size\n\n image = cv2.resize(image, (resized_width, resized_height), interpolation=cv2.INTER_LINEAR)\n\n new_image = np.zeros((self.img_size, self.img_size, 3))\n new_image[0:resized_height, 0:resized_width] = image\n\n return new_image\n\nclass Normalizer(object):\n\n def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):\n self.mean = np.array([[mean]])\n self.std = np.array([[std]])\n\n def __call__(self, image):\n\n return ((image.astype(np.float32) - self.mean) / self.std)\n\ndef test():\n KittiDataLoader(data_root_path='data', image_root='image_02', \n annotation_root='label_02', det_root='det_02', \n training_set=[1,2,3], validation_set=[4,5,6], \n testing_set=[0], seq_num=21)\n\n\nif __name__ == \"__main__\":\n test()", "sub_path": "kitti_dataloader_SA.py", "file_name": "kitti_dataloader_SA.py", "file_ext": "py", "file_size_in_byte": 14189, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.maximum", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 21, "usage_type": "call"}, {"api_name": "lap.lapjv", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 56, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path", "line_number": 90, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path", "line_number": 92, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 163, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 191, "usage_type": "call"}, {"api_name": "os.path", "line_number": 191, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 194, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 195, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 328, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 348, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 348, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 358, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 359, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 363, "usage_type": "attribute"}]} +{"seq_id": "225222001", "text": "# -*- coding: utf-8 -*-\n# @author Wendy\n# @created on 2021/1/13\nimport scrapy\nfrom scrapy.selector import Selector\nimport helper\n\n# https://m.douban.com/rexxar/api/v2/tv/27157689?ck=lvDn&for_mobile=1\n# https://m.douban.com/rexxar/api/v2/tv/27157689/credits\n# https://m.douban.com/rexxar/api/v2/tv/27157689/rating?ck=lvDn&for_mobile=1\n\n\nclass ToScrapeMovieDetail(scrapy.Spider):\n name = 'douban_movie_detail'\n start_urls = list(map(lambda x: x[\"link\"], helper.read_json('my_collect')))[:1]\n\n def parse(self, response):\n res = parse_body(response)\n yield res\n\n\ndef parse_body(response):\n # for quote in response.css('.subjectwrap .info'):\n # info = quote.css('.info')\n # titlestr = info.css('.title em').xpath('.//text()').extract_first()\n # tagstr = info.css('.intro').xpath('.//text()').extract_first()\n\n res = {}\n rating_w = response.css('.rating_wrap')\n res['rating_avg'] = rating_w.css('[property=\"v:average\"]::text').get()\n res['rating_num'] = rating_w.css('[property=\"v:votes\"]::text').get()\n ratings = rating_w.css('.rating_per::text').getall()\n if len(ratings) > 0:\n for i, x in enumerate(ratings):\n res['rating_' + str(5 - i)] = x[:-1] if str.endswith(x, '%') else 0\n\n mark_w = response.css('.j.a_stars')\n res['mark'] = mark_w.css('#n_rating').attrib['value']\n res['mark_date'] = mark_w.css('.collection_date::text').get()\n comment = mark_w.css('span:last-child')\n if not comment.attrib['id']:\n res['mark_comment'] = comment.css('::text').get()\n\n return res\n\n\ndef main():\n body = helper.read_mock('movie_detail')\n response = Selector(text=body)\n res = parse_body(response)\n print('[yield]', res)\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "quotesbot/douban/movie_detail.py", "file_name": "movie_detail.py", "file_ext": "py", "file_size_in_byte": 1764, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "scrapy.Spider", "line_number": 13, "usage_type": "attribute"}, {"api_name": "helper.read_json", "line_number": 15, "usage_type": "call"}, {"api_name": "helper.read_mock", "line_number": 48, "usage_type": "call"}, {"api_name": "scrapy.selector.Selector", "line_number": 49, "usage_type": "call"}]} +{"seq_id": "542736254", "text": "import json\n\nfile_name = 'login_data.json'\n\n\nclass JsonClass:\n def __init__(self, file):\n self.file_name = file\n\n def json_load(self):\n with open(self.file_name, 'r+') as file:\n file_content = json.load(file)\n\n return file_content\n\n def json_dump(self,):\n with open(self.file_name, 'r+') as file:\n file_content = json.load(file)\n\n return file_content\n\n\nfiles = JsonClass(file_name)\n\n\ndef login_after_menu(name):\n print(f'welcome to our service MR. {name}')\n\n user_choice = input(\"\"\"\n Enter A - For account Details\n Enter D - For Deposite Money\n Enter S - For send money\n Enter L - Logout\n \"\"\")\n while user_choice != 'l':\n if user_choice.lower() == 'a':\n account_details(name)\n elif user_choice == 'd':\n deposite_money()\n elif user_choice == 's':\n send_money()\n else:\n print('Unknown command, Please try again..!')\n\n user_choice = input(\"\"\"\n Enter A - For account Details\n Enter D - For Deposite Money\n Enter S - For send money\n Enter L - Logout\n \"\"\")\n\n\ndef account_details(name):\n for _ in files.json_load():\n if _['username'] == name:\n print(\n f\"\"\"\n username:{_['username']}\n Email: {_['email']} \n \"\"\"\n )\n\n # login_after_menu(name)\n\n\ndef send_money():\n total_tk = 1000000\n tk = int(input(\"Enter amount you want to sent: \"))\n print(f\"your previous tk was:${total_tk} \")\n remaining_tk = total_tk - tk\n print(f\"After send you have :${remaining_tk}\")\n\n\n", "sub_path": "utils/account_funtionality.py", "file_name": "account_funtionality.py", "file_ext": "py", "file_size_in_byte": 1716, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "json.load", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "146113095", "text": "from typing import (Optional, Tuple, List, Dict)\nfrom . db import (Query, makeRow, getRow, count, updateRow)\nfrom . lib.menu import (menu, MenuOptions, ConfigOptions, giveOptions)\nfrom . lib.forms import (form, Form)\nfrom . lib.format import (box,\n ratioBar, \n color,\n prompt,\n col2,\n formatedTime,\n terminalBar)\n\n###############\n# Useful data #\n###############\n\n\nsourceRow: Dict[str, str] = {\n \"name\": \"TEXT NOT NULL PRIMARY KEY\",\n \"site\": \"text\",\n \"payment\": \"text\",\n \"tax\": \"text\",\n \"notes\": \"text\",\n \"created\": \"TEXT NOT NULL\",\n \"modified\": \"TEXT NOT NULL\"\n}\n\nsourceRules: List[str] = [key + \" \" + sourceRow[key] for key in sourceRow]\nsourceColumns: List[str] = [key for key in sourceRow]\n\n# Editable fields\nfields: List[str] = [\"name\", \"site\", \"payment\", \"tax\", \"notes\"]\n\n\n#############\n# Functions #\n#############\n\n\n# Will open menu with sources options\ndef menuSources() -> Optional[str]:\n\n # Declaring\n opts: MenuOptions\n cfgs: ConfigOptions\n l1: str\n l2: str\n msg: Optional[str]\n r: Optional[str]\n\n # Prepare menu\n opts = {\n \"a\": {\n \"col1\": \"Add source\",\n \"col2\": \"\",\n \"call\": addSource\n },\n \"l\": {\n \"col1\": \"List sources\",\n \"col2\": \"\",\n \"call\": listSources,\n },\n \"e\": {\n \"col1\": \"Edit source\",\n \"col2\": \"\",\n \"call\": editSource\n },\n\n }\n cfgs = {\"show\": [\"back\"]}\n\n # Prepare message\n l1 = color('blue', \"Sources Menu\")\n l2 = \"Number of sources: \" + color('yellow', str(count(\"sources\")))\n msg = l1 + '\\n\\n' + l2\n\n # Menu loop\n # Update the message according to result of action\n while True:\n r = menu(name=\"Sources\", msg=msg, opts=opts, cfgs=cfgs)\n if r is None:\n return None\n else:\n msg = r\n\n\n# Will edit a single entry/source\ndef editSource() -> str:\n\n # Declaring\n checkEmptyQuery: Query\n names: List[str]\n namesMsg: str\n name: str\n\n sourceQuery: Query\n sourceQueryMsg: str\n\n fieldsMsg: str\n field: str\n newValue: str\n\n _where: List[Tuple[str, str]]\n _field: Tuple[str, str]\n _mod: Tuple[str, str]\n\n # Check if there is at least one source to edit\n checkEmptyQuery = getRow(table=\"sources\", row=\"name\")\n if checkEmptyQuery == [None]:\n return color('red', \"Nothing to edit...\")\n\n # Decide witch source to edit\n names = [x[0] for x in checkEmptyQuery]\n namesMsg = \"Choose source to edit.\"\n name = checkEmptyQuery[giveOptions(msg=namesMsg, c1=names)][0]\n\n # Show source data\n sourceQuery = getRow(table=\"sources\", where=[(\"name\", name)])\n sourceQueryMsg = formatedSource(sourceQuery[0])\n print(box(sourceQueryMsg))\n\n # Decide witch field to edit\n fieldsMsg = \"Choose field to edit.\"\n targetField = fields[giveOptions(msg=fieldsMsg, c1=fields)]\n newValue = prompt(\"New value for '\" + targetField + \"'\", \": \")\n\n # Prepare command\n _where = [('name', name)]\n _field = (targetField, newValue)\n _mod = ('modified', formatedTime())\n\n # Execute change and update 'modfied' filed\n updateRow(table=\"sources\", field=_field, where=_where)\n updateRow(table=\"sources\", field=_mod, where=_where)\n\n # Output result message\n output = color('green', \"Field '\" + targetField + \"' of '\" + name + \"' edited.\")\n return output\n\n\n# Will check if the source is not already in use, case not return it\ndef getValidSource() -> str:\n\n # Declaring\n listForm: Form\n name: str\n query: Query\n\n # Loop til find valid source\n while True:\n\n # Prepare form\n listForm = {\n \"name\": [\"notEmpty\"]\n }\n name = form(listForm)[0]\n\n # Query after it\n query = getRow(table=\"sources\",\n row=\"name\",\n where=[(\"name\", name)]\n )\n\n # Check if valid\n if query != [None]:\n print(color('red', \"Name already in use. Choose another one.\"))\n else:\n return name\n\n\n# Do: Create new row in table sources\ndef addSource() -> str:\n\n # Declaring\n listForm: Form\n valueList: List[str]\n\n # Prepare form\n listForm = {\n \"name\": getValidSource(),\n \"site\": [],\n \"payment method\": [],\n \"tax\": [],\n \"notes\": [\"multiline\"],\n \"created\": formatedTime(),\n \"modified\": formatedTime()\n }\n valueList = form(listForm)\n\n # Create row and return success message\n makeRow(table=\"sources\", columns=sourceColumns, values=valueList)\n return color('green', \"Source added.\")\n\n\n# From source(tuple) return formated row(string)\ndef formatedSource(row) -> str:\n\n # Declaring\n name: str\n site: str\n paym: str\n taxx: str\n note: str\n crea: str\n modi: str\n\n doneJobsCount: int\n openJobsCount: int\n closeJobsCount: int\n\n size: int = 16\n output: List[str]\n\n # For stats\n doneJobsCount = count('jobs', [('source', row[0]),\n ('ingroup', 'done')])\n\n openJobsCount = count('jobs', [('source', row[0]),\n ('ingroup', 'open')])\n\n closedJobsCount = count('jobs', [('source', row[0]),\n ('ingroup', 'closed')])\n\n rati = ratioBar([(doneJobsCount, 'green'),\n (openJobsCount, 'yellow'),\n (closedJobsCount, 'red')]) + '\\n'\n\n name = col2(size, \"Source Name:\", row[0], c2Color='green')\n site = col2(size, \"Site:\", row[1], c2Color='green')\n dJbs = col2(size, \"Done jobs:\", str(doneJobsCount), c2Color='green')\n oJbs = col2(size, \"Open jobs:\", str(openJobsCount), c2Color='yellow')\n cJbs = col2(size, \"Closed jobs:\", str(closedJobsCount), c2Color='red')\n paym = col2(size, \"Payment method: \", row[2], c2Color='green')\n taxx = col2(size, \"Tax:\", row[3], c2Color='green')\n note = col2(size, \"Notes:\", row[4], c2Color='green')\n crea = col2(size, \"Created:\", row[5])\n modi = col2(size, \"Modified:\", row[6])\n\n output = [rati, name, site, dJbs, oJbs, cJbs, paym, taxx, note, crea, modi]\n\n # Return it with new line between them\n return '\\n'.join(output)\n\n\n# Return a formated string of all sources.\ndef listSources() -> str:\n\n # Declaring\n query: Query\n n: int\n row: Optional[tuple]\n acc: List[str] = []\n\n query = getRow(table=\"sources\")\n\n # Case nothing to show\n if query == [None]:\n return color('red', \"Nothing to list...\")\n\n # Print all options after format them\n acc = [formatedSource(row) for row in query]\n return (\"\\n\" + terminalBar('─')).join(acc)\n", "sub_path": "python/jobhandle/jobhandle/sources.py", "file_name": "sources.py", "file_ext": "py", "file_size_in_byte": 6829, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.Dict", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 32, "usage_type": "name"}, {"api_name": "lib.menu.MenuOptions", "line_number": 44, "usage_type": "name"}, {"api_name": "lib.menu.ConfigOptions", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "lib.format.color", "line_number": 73, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 74, "usage_type": "call"}, {"api_name": "db.count", "line_number": 74, "usage_type": "call"}, {"api_name": "lib.menu.menu", "line_number": 80, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 41, "usage_type": "name"}, {"api_name": "db.Query", "line_number": 91, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 92, "usage_type": "name"}, {"api_name": "db.Query", "line_number": 96, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 104, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 105, "usage_type": "name"}, {"api_name": "db.getRow", "line_number": 108, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 110, "usage_type": "call"}, {"api_name": "lib.menu.giveOptions", "line_number": 115, "usage_type": "call"}, {"api_name": "db.getRow", "line_number": 118, "usage_type": "call"}, {"api_name": "lib.format.box", "line_number": 120, "usage_type": "call"}, {"api_name": "lib.menu.giveOptions", "line_number": 124, "usage_type": "call"}, {"api_name": "lib.format.prompt", "line_number": 125, "usage_type": "call"}, {"api_name": "lib.format.formatedTime", "line_number": 130, "usage_type": "call"}, {"api_name": "db.updateRow", "line_number": 133, "usage_type": "call"}, {"api_name": "db.updateRow", "line_number": 134, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 137, "usage_type": "call"}, {"api_name": "lib.forms.Form", "line_number": 145, "usage_type": "name"}, {"api_name": "db.Query", "line_number": 147, "usage_type": "name"}, {"api_name": "lib.forms.form", "line_number": 156, "usage_type": "call"}, {"api_name": "db.getRow", "line_number": 159, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 166, "usage_type": "call"}, {"api_name": "lib.forms.Form", "line_number": 175, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 176, "usage_type": "name"}, {"api_name": "lib.format.formatedTime", "line_number": 185, "usage_type": "call"}, {"api_name": "lib.format.formatedTime", "line_number": 186, "usage_type": "call"}, {"api_name": "lib.forms.form", "line_number": 188, "usage_type": "call"}, {"api_name": "db.makeRow", "line_number": 191, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 192, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 212, "usage_type": "name"}, {"api_name": "db.count", "line_number": 215, "usage_type": "call"}, {"api_name": "db.count", "line_number": 218, "usage_type": "call"}, {"api_name": "db.count", "line_number": 221, "usage_type": "call"}, {"api_name": "lib.format.ratioBar", "line_number": 224, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 228, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 229, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 230, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 231, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 232, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 233, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 234, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 235, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 236, "usage_type": "call"}, {"api_name": "lib.format.col2", "line_number": 237, "usage_type": "call"}, {"api_name": "db.Query", "line_number": 249, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 251, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 252, "usage_type": "name"}, {"api_name": "db.getRow", "line_number": 254, "usage_type": "call"}, {"api_name": "lib.format.color", "line_number": 258, "usage_type": "call"}, {"api_name": "lib.format.terminalBar", "line_number": 262, "usage_type": "call"}]} +{"seq_id": "435565481", "text": "import json\nfrom urllib.request import urlopen\nfrom minecraft_model_reader import log\n\ntry:\n launcher_manifest = json.load(urlopen('https://launchermeta.mojang.com/mc/game/version_manifest.json', timeout=0.3))\nexcept:\n log.error('Failed to download the launcher manifest. This may cause problems if you have not used the program before. Make sure you are connected to the internet.')\n launcher_manifest = {\n \"latest\": {\n \"release\": None\n }\n }\n", "sub_path": "minecraft_model_reader/java/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 480, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.load", "line_number": 6, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 6, "usage_type": "call"}, {"api_name": "minecraft_model_reader.log.error", "line_number": 8, "usage_type": "call"}, {"api_name": "minecraft_model_reader.log", "line_number": 8, "usage_type": "name"}]} +{"seq_id": "259921724", "text": "#!/bin/env python36\n# filename: ssautolib.py\n# Author: lufei\n# Date: 20190829 10:00:03\n\n\nimport pkgutil\nimport sys\nimport importlib\nimport os\nimport inspect\n\ndef get_sub(pkg_name, sub_modules):\n '''get a list of all modules in pkg_name, sub_modules should be a empty list. '''\n try:\n pkg = importlib.import_module(pkg_name)\n for _, sub_name, ispkg in pkgutil.iter_modules(pkg.__path__):\n if ispkg:\n get_sub(pkg.__name__+'.'+sub_name, sub_modules)\n else:\n sub_modules.append(importlib.import_module(pkg.__name__+'.'+sub_name))\n\n except Exception as e:\n print(type(e).__name__, e)\n\ndef get_subclass(module, baseclass):\n '''get all sub classes of baseclass from module even those in sub modules, \nmodule is a package object, baseclass is the base class'''\n try:\n if hasattr(module, '__path__'):\n # module is a package object\n sub_modules = []\n get_sub(module.__name__, sub_modules) # get sub only accept strings.\n sub_class = []\n for mod in sub_modules:\n sub_class.append(get_tests(mod))\n return sub_class\n else:\n return [x for x in vars(module).values() if ssissubclass(x,baseclass)] \n except Exception as e:\n print(e)\n return []\n\ndef ssissubclass(a,b): \n '''tell if a is subclass of b'''\n try:\n return issubclass(a,b)\n except TypeError:\n return False\n\ndef get_module_names_by_path(path='.'):\n '''get a name list of all modules in path, none packages.'''\n if not os.path.isdir(path):\n print('No such directory: %s' % path, file=sys.stderr)\n return None\n\n module_names = []\n def _get_module_name(_path, _prefix):\n# print('-- _get_modeule_name(%s, %s)' %(_path, _prefix))\n# for debugging.\n for md in pkgutil.iter_modules(path=[_path], prefix=_prefix):\n# print('----',md) # for debugging\n if md[2]:\n _get_module_name(os.path.join(_path, md[1].split('.')[-1]), \n md[1]+'.')\n else:\n module_names.append(md[1])\n \n# _names.append(md[1])\n _get_module_name(path, '')\n return module_names\n\ndef get_modules_by_path(path='.'):\n '''get module-objects by given path, path should be a package path, which inside\nwith __init__.py'''\n if not os.path.isdir(path):\n print('No such directory: %s' % path, file=sys.stderr)\n return None\n\n pkg_path = os.path.join(path, '__init__.py')\n modules = []\n _pkg = 'package'\n \n module_names = get_module_names_by_path(path)\n try:\n spec = importlib.util.spec_from_file_location(_pkg, pkg_path)\n module = importlib.util.module_from_spec(spec)\n except Exception as e:\n print(type(e).__name__, ':', e,\n '\\nNot a valid package path: %s' % path, file=sys.stderr)\n return None\n sys.modules[_pkg] = module\n imported_pkg = importlib.import_module(_pkg)\n for module_name in module_names:\n full_module_name = _pkg + '.' + module_name\n try:\n modules.append(importlib.import_module(full_module_name, imported_pkg))\n except Exception as e:\n print(type(e).__name__, ':', e,\n '\\nCannot import %s' % module_name, file=sys.stderr)\n\n return modules\n\ndef get_module_by_path(name, path='.'):\n '''get module-object by given path and name '''\n if not os.path.isdir(path):\n print('No such directory: %s' % path, file=sys.stderr)\n return None\n\n pkg_path = os.path.join(path, '__init__.py')\n module = None\n _pkg = 'package'\n\n module_names = get_module_names_by_path(path)\n if name not in module_names:\n return module\n\n try:\n spec = importlib.util.spec_from_file_location(_pkg, pkg_path)\n module = importlib.util.module_from_spec(spec)\n except Exception as e:\n print(type(e).__name__, ':', e,\n '\\nNot a valid package path: %s' % path, file=sys.stderr)\n return module\n\n sys.modules[_pkg] = module\n imported_pkg = importlib.import_module(_pkg)\n full_module_name = _pkg + '.' + name\n try:\n module = importlib.import_module(full_module_name, imported_pkg)\n except Exception as e:\n print(type(e).__name__, ':', e,\n '\\nCannot import %s' % module_name, file=sys.stderr)\n return module\n\n\ndef get_subclasses_in_module(module_obj, class_obj):\n '''get all subclasses of class_obj in module_obj'''\n subclasses = []\n for i,j in inspect.getmembers(module_obj):\n if ssissubclass(j, class_obj):\n subclasses.append(j)\n return subclasses\n\n# NOT work well\n# in importlib.util.spec_from_file_location(module_name, path), module_name\n# is just a specified name\ndef get_subclass_by_module_name(module_name, class_obj, path='./__init__.py'):\n '''get list of sub classes of class_obj in module_name under path'''\n if os.path.isdir(path):\n path = os.path.join(path, '__init__.py')\n spec = importlib.util.spec_from_file_location(module_name, path)\n module_obj = importlib.util.module_from_spec(spec)\n return get_subclasses_in_module(module_obj, class_obj)\n\n", "sub_path": "ssautolib.py", "file_name": "ssautolib.py", "file_ext": "py", "file_size_in_byte": 4856, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "importlib.import_module", "line_number": 16, "usage_type": "call"}, {"api_name": "pkgutil.iter_modules", "line_number": 17, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 54, "usage_type": "attribute"}, {"api_name": "pkgutil.iter_modules", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "importlib.util.spec_from_file_location", "line_number": 86, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 86, "usage_type": "attribute"}, {"api_name": "importlib.util.module_from_spec", "line_number": 87, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 87, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 92, "usage_type": "attribute"}, {"api_name": "importlib.import_module", "line_number": 93, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 97, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 100, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 107, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path", "line_number": 110, "usage_type": "attribute"}, {"api_name": "importlib.util.spec_from_file_location", "line_number": 119, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 119, "usage_type": "attribute"}, {"api_name": "importlib.util.module_from_spec", "line_number": 120, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 120, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 123, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 126, "usage_type": "attribute"}, {"api_name": "importlib.import_module", "line_number": 127, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 130, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 133, "usage_type": "attribute"}, {"api_name": "inspect.getmembers", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "importlib.util.spec_from_file_location", "line_number": 152, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 152, "usage_type": "attribute"}, {"api_name": "importlib.util.module_from_spec", "line_number": 153, "usage_type": "call"}, {"api_name": "importlib.util", "line_number": 153, "usage_type": "attribute"}]} +{"seq_id": "43778909", "text": "from awacs import aws\nfrom troposphere import Parameter, Ref, Template, Equals, Condition, Not, AWS_ACCOUNT_ID\nfrom troposphere import guardduty, sns, events\n\nMASTER_ACCOUNT_ID = \"1234\"\nMEMBER_ACCOUNT_ID = \"5678\"\nMEMBER_ACCOUNT_EMAIL = \"user@example.com\"\n\nt = Template()\n\nt.add_description(\"GuardDuty example deployment for master and member accounts\")\n\nmember_invitation = t.add_parameter(Parameter(\n \"MemberInvitation\",\n Type=\"String\",\n Description=\"Invitation ID for member account, leave empty on master account\"\n))\n\nt.add_condition(\"IsMaster\", Equals(Ref(AWS_ACCOUNT_ID), MASTER_ACCOUNT_ID))\nt.add_condition(\"IsMember\", Not(Condition(\"IsMaster\")))\n\ndetector = t.add_resource(guardduty.Detector(\n \"Detector\",\n Enable=True\n))\n\nmaster = t.add_resource(guardduty.Master(\n \"Master\",\n Condition=\"IsMember\",\n DetectorId=Ref(detector),\n MasterId=MASTER_ACCOUNT_ID,\n InvitationId=Ref(member_invitation),\n))\n\n# You can create multiple members if you have multiple members accounts\nmember = t.add_resource(guardduty.Member(\n \"Member\",\n Condition=\"IsMaster\",\n Status=\"Invited\",\n MemberId=MEMBER_ACCOUNT_ID,\n Email=MEMBER_ACCOUNT_EMAIL,\n DetectorId=Ref(detector)\n))\n\nsnstopic = t.add_resource(sns.Topic(\n \"SNSTopic\",\n Condition=\"IsMaster\",\n Subscription=[\n # put any subscriptions here\n ]\n))\n\nevent = t.add_resource(events.Rule(\n \"EventsRule\",\n Condition=\"IsMaster\",\n EventPattern={\n \"source\": [\n \"aws.guardduty\"\n ]\n },\n State=\"ENABLED\",\n Targets=[\n events.Target(\n Arn=Ref(snstopic),\n Id=\"sns\",\n )\n ]\n))\n\n# Allow events to send notifications to SNS\nt.add_resource(sns.TopicPolicy(\n \"SNSTopicPolicy\",\n Condition=\"IsMaster\",\n PolicyDocument=aws.Policy(\n Statement=[\n aws.Statement(\n Effect=aws.Allow,\n Action=[\n aws.Action(\"sns\", \"Publish\"),\n ],\n Principal=aws.Principal(\"Service\", \"events.amazonaws.com\"),\n Resource=[Ref(snstopic)],\n ),\n ]\n ),\n Topics=[Ref(snstopic)]\n))\n\nprint(t.to_json())\n", "sub_path": "src/guardduty.py", "file_name": "guardduty.py", "file_ext": "py", "file_size_in_byte": 2177, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "troposphere.Template", "line_number": 9, "usage_type": "call"}, {"api_name": "troposphere.Parameter", "line_number": 13, "usage_type": "call"}, {"api_name": "troposphere.Equals", "line_number": 19, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 19, "usage_type": "call"}, {"api_name": "troposphere.AWS_ACCOUNT_ID", "line_number": 19, "usage_type": "argument"}, {"api_name": "troposphere.Not", "line_number": 20, "usage_type": "call"}, {"api_name": "troposphere.Condition", "line_number": 20, "usage_type": "call"}, {"api_name": "troposphere.guardduty.Detector", "line_number": 22, "usage_type": "call"}, {"api_name": "troposphere.guardduty", "line_number": 22, "usage_type": "name"}, {"api_name": "troposphere.guardduty.Master", "line_number": 27, "usage_type": "call"}, {"api_name": "troposphere.guardduty", "line_number": 27, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 30, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 32, "usage_type": "call"}, {"api_name": "troposphere.guardduty.Member", "line_number": 36, "usage_type": "call"}, {"api_name": "troposphere.guardduty", "line_number": 36, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 42, "usage_type": "call"}, {"api_name": "troposphere.sns.Topic", "line_number": 45, "usage_type": "call"}, {"api_name": "troposphere.sns", "line_number": 45, "usage_type": "name"}, {"api_name": "troposphere.events.Rule", "line_number": 53, "usage_type": "call"}, {"api_name": "troposphere.events", "line_number": 53, "usage_type": "name"}, {"api_name": "troposphere.events.Target", "line_number": 63, "usage_type": "call"}, {"api_name": "troposphere.events", "line_number": 63, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 64, "usage_type": "call"}, {"api_name": "troposphere.sns.TopicPolicy", "line_number": 71, "usage_type": "call"}, {"api_name": "troposphere.sns", "line_number": 71, "usage_type": "name"}, {"api_name": "awacs.aws.Policy", "line_number": 74, "usage_type": "call"}, {"api_name": "awacs.aws", "line_number": 74, "usage_type": "name"}, {"api_name": "awacs.aws.Statement", "line_number": 76, "usage_type": "call"}, {"api_name": "awacs.aws", "line_number": 76, "usage_type": "name"}, {"api_name": "awacs.aws.Allow", "line_number": 77, "usage_type": "attribute"}, {"api_name": "awacs.aws", "line_number": 77, "usage_type": "name"}, {"api_name": "awacs.aws.Action", "line_number": 79, "usage_type": "call"}, {"api_name": "awacs.aws", "line_number": 79, "usage_type": "name"}, {"api_name": "awacs.aws.Principal", "line_number": 81, "usage_type": "call"}, {"api_name": "awacs.aws", "line_number": 81, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 82, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 86, "usage_type": "call"}]} +{"seq_id": "197540528", "text": "# author: Leda Sari\n\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nimport librosa\n\n\nWINDOW_SIZE = 0.02\nWINDOW_STRIDE = 0.01\nWINDOW = 'hamming'\n\n\ndef check_characters(string, labels):\n for c in string:\n if c not in labels:\n return False\n return True\n\n\ndef analyze_transcripts(train_data_dir, ignore_space=False):\n char_labels = set()\n for i, speaker_folder in enumerate(os.listdir(train_data_dir)):\n if i % 10 == 0:\n print(i)\n for chapter_folder in os.listdir(f'{train_data_dir}/{speaker_folder}'):\n trans_file = f'{train_data_dir}/{speaker_folder}/{chapter_folder}/{speaker_folder}-{chapter_folder}.trans.txt'\n with open(trans_file, 'r') as f:\n for line in f:\n utt, trans = line.strip().split(' ', maxsplit=1)\n if ignore_space:\n char_labels = char_labels.union(set(trans.replace(\" \", \"\")))\n else:\n char_labels = char_labels.union(set(trans))\n \n output_labels = [\"_\"] + sorted(list(char_labels))\n output_label_dict = {c: i for i, c in enumerate(output_labels)}\n os.makedirs(\"data\", exist_ok=True)\n with open(\"data/labels.json\", 'w') as f:\n json.dump(output_label_dict, f, indent=4)\n \n return output_label_dict\n\n\ndef get_txt(data_dir, labels_dict, ignore_space=False):\n file_trans = []\n for i, speaker_folder in enumerate(os.listdir(data_dir)):\n if i % 20 == 0:\n print(f'{i}th speaker')\n if not speaker_folder.isdigit():\n continue\n for chapter_folder in os.listdir(f'{data_dir}/{speaker_folder}'):\n trans_file = f'{data_dir}/{speaker_folder}/{chapter_folder}/{speaker_folder}-{chapter_folder}.trans.txt'\n with open(trans_file, 'r') as f:\n for l in f:\n utt, trans = l.strip().split(' ', maxsplit=1)\n audio_name = f'{speaker_folder}/{chapter_folder}/{utt}.flac'\n audio_path = f'{data_dir}/{speaker_folder}/{chapter_folder}/{utt}.flac'\n assert os.path.isfile(audio_path)\n if check_characters(trans, labels_dict) and len(trans) > 10:\n if ignore_space:\n trans = trans.replace(\" \", \"\")\n trans_ids = [labels_dict[c] for c in trans]\n file_trans.append([audio_path, trans, trans_ids, f'speaker-{speaker_folder}'])\n\n df = pd.DataFrame(file_trans, columns=['file', 'trans', 'trans_ids', 'speaker'])\n return df\n\n\n\ndef load_audio(audio_path):\n sound, sample_rate = librosa.load(audio_path, sr=16000)\n duration = librosa.get_duration(filename=f\"{audio_path}\")\n \n if len(sound.shape) > 1:\n if sound.shape[1] == 1:\n sound = sound.squeeze()\n else:\n sound = sound.mean(axis=1) # multiple channels, average\n return sound, sample_rate, duration\n\ndef extract_spect_mvn(audio_path):\n y, sample_rate, duration = load_audio(audio_path)\n\n n_fft = int(sample_rate * WINDOW_SIZE)\n win_length = n_fft\n hop_length = int(sample_rate * WINDOW_STRIDE)\n # STFT\n D = librosa.stft(y, n_fft=n_fft, hop_length=hop_length,\n win_length=win_length, window=WINDOW)\n spect, phase = librosa.magphase(D)\n # S = log(S+1)\n spect = np.log1p(spect)\n # spect = torch.FloatTensor(spect)\n # if self.normalize:\n print(spect.shape)\n mean = np.mean(spect, 1, keepdims=True)\n std = np.std(spect, 1, keepdims=True)\n spect -= mean\n spect /= std\n return spect.T, duration\n\n\nif __name__ == \"__main__\":\n import sys\n data_dir = sys.argv[1]\n \n trans_dir = os.getcwd() + 'data'\n save_dir = os.getcwd() + \"/data/stft/\"\n os.makedirs(trans_dir, exist_ok=True)\n os.makedirs(save_dir, exist_ok=True)\n \n\n output_label_dict = analyze_transcripts(\"{}/train-clean-100\".format(data_dir))\n\n subset_list = [\"dev-clean\", \"test-clean\", \"dev-other\", \"test-other\", \"train-clean-100\"]\n for subset in subset_list:\n print(subset)\n df = get_txt(\"{}/{}\".format(data_dir, subset), output_label_dict)\n df.to_csv('data/trans_{}.csv'.format(subset))\n\n for subset in subset_list:\n df = pd.read_csv('data/trans_{}.csv'.format(subset))\n dataset= []\n for i, row in df.iterrows():\n S, duration = extract_spect_mvn(row[\"file\"])\n wave, extension = os.path.splitext(os.path.basename(row[\"file\"]))\n feat_name = \"{}_{:.3f}_{:.3f}.npy\".format(wave, 0, duration)\n save_path = os.path.join(save_dir, feat_name)\n np.save(save_path, S)\n\n row['features'] = save_path\n row[\"duration\"] = duration\n row.pop('Unnamed: 0')\n dataset.append(row)\n \n \n features_df = pd.DataFrame(dataset)\n features_df.to_csv(\"data/features_{}.csv\".format(subset))\n \n", "sub_path": "prep_data.py", "file_name": "prep_data.py", "file_ext": "py", "file_size_in_byte": 5019, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 24, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 27, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 39, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 41, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 48, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 67, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 73, "usage_type": "call"}, {"api_name": "librosa.get_duration", "line_number": 74, "usage_type": "call"}, {"api_name": "librosa.stft", "line_number": 90, "usage_type": "call"}, {"api_name": "librosa.magphase", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.log1p", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 99, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 107, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 109, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 110, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 111, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 112, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 124, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path", "line_number": 130, "usage_type": "attribute"}, {"api_name": "numpy.save", "line_number": 131, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 139, "usage_type": "call"}]} +{"seq_id": "127500285", "text": "from django.views.decorators.http import require_http_methods\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import redirect\nfrom django.utils.timezone import utc\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom django.apps import apps\n\nfrom problem.tools.decorators.request import auth\nfrom problem.tools import request_handler\nfrom problem.clients import models\nfrom problem.tools import strings\nfrom problem.tools import uploader\nfrom problem.tools import crypto\nfrom problem.tools import check\nfrom problem import common_data\n\nfrom celery.result import AsyncResult\n\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime\nfrom datetime import timedelta\n\nimport base64\n\n\ndef get_some_fields(clss, *args):\n fields = []\n try:\n for arg in args:\n fields.append(apps.get_model(\"clients\", clss)._meta.get_field(arg))\n except:\n pass\n return fields\n\ndef check_age(date):\n msg = ''\n if relativedelta(datetime.utcnow().replace(tzinfo=utc), date).years < 12:\n msg = \"Мы не работаем с такими молодыми клиентами\"\n if relativedelta(datetime.utcnow().replace(tzinfo=utc), date).years > 70:\n msg = errors.append(\"Мы бережем свои нервы\")\n return msg\n\ndef check_user(password, db_salt, db_pass, user_groups, group):\n res = True\n if not crypto.Hash(password + db_salt).getSHA512() == db_pass: res = False\n if not user_groups:\n res = False\n else:\n if not group in user_groups: res = False\n return res\n\n@auth(\"admins\", models.Users.objects, new_view_func=lambda: redirect('/admin/'))\ndef login(request):\n errors = []\n context = {}\n response = None\n if request.method == \"POST\":\n if not request.POST.get('login', ''):\n errors.append('Введите логин')\n if not request.POST.get('password', ''):\n errors.append('Введите пароль')\n if not errors:\n login = request.POST['login']\n password = request.POST['password']\n try:\n user = models.Users.objects.get(login=login)\n except ObjectDoesNotExist:\n errors.append('Неверный логин или пароль')\n else:\n db_salt = user.salt\n db_pass = user.password\n db_user_id = user.id\n user_groups = [key['name'] for key in user.groups.all().values()]\n if check_user(\n password,\n db_salt,\n db_pass,\n user_groups,\n 'admins'\n ):\n response = redirect('/admin/')\n request.session['user_id'] = db_user_id\n request.session['owned_by'] = 'admins'\n if request.POST.get('remember', '') == \"on\":\n remember_hash = crypto.Hash(\n strings.get_rand_string(20)\n ).getSHA512()\n response.set_cookie(\n 'remember_hash',\n remember_hash,\n httponly=True,\n expires=datetime.now() + timedelta(days=30)\n )\n user.remember_hash = remember_hash\n user.ip_addr = request_handler.get_client_ip(request)\n user.save()\n else:\n response.delete_cookie('remember_hash')\n user.remember_hash = ''\n user.ip_addr = request_handler.get_client_ip(request)\n user.save()\n else:\n errors.append('Неверный логин или пароль')\n context = {'errors': errors}\n if not response:\n return render(request, 'clients/clients__auth.html', context)\n else:\n return response\n\n@require_http_methods([\"POST\"])\ndef logout(request):\n user_id = request.session.get('user_id', None)\n if user_id:\n user = models.Users.objects.get(id=user_id)\n user.remember_hash = ''\n user.ip_addr = ''\n response = redirect('/')\n response.delete_cookie('remember_hash')\n response.delete_cookie('sessionid')\n return response\n\n@auth(\"admins\", models.Users.objects, lambda: redirect('/'))\ndef admin(request):\n media_url = settings.MEDIA_URL\n clients_qs = models.Clients.objects.all()\n clients_count = clients_qs.count()\n order_type = request.COOKIES.get('orderType')\n if order_type:\n order = order_type.split(\"-\")[0]\n order_direct = order_type.split(\"-\")[1]\n if (order_direct == \"up\"):\n clients_qs = clients_qs.order_by(order)\n elif (order_direct == \"down\"):\n clients_qs = clients_qs.order_by(\"-{}\".format(order))\n end_entry = common_data.pagination['page_limit']\n sliced_clients = clients_qs[:end_entry].values_list('pk', flat=True)\n clients_qs = clients_qs.filter(id__in=list(sliced_clients))\n clients_fields = get_some_fields(\"Clients\", \"name\", \"surname\", \"birthday\")\n context = {'clients': clients_qs,\n 'media_url': media_url,\n 'clients_fields': clients_fields,\n 'clients_count': clients_count}\n return render(request, 'clients/clients__admin.html', context)\n\n@auth(\"admins\", models.Users.objects, lambda: redirect('/'))\ndef clients_control(request, client_id=None):\n context = {}\n if request.method == \"POST\":\n errors = []\n fields = {}\n birthday = {}\n fields['name'] = request.POST.get('name')\n if not fields['name']:\n errors.append(\"заполните имя\")\n fields['surname'] = request.POST.get('surname')\n client_id = request.POST.get('id')\n if not fields['surname']:\n errors.append(\"заполните фамилию\")\n fields = {k: v.strip() for k, v in fields.items()}\n vote = request.POST.get('vote').strip()\n if vote:\n if not check.isfloat(vote):\n errors.append(\"оценка должна быть числом\")\n elif int(vote) < 0 or int(vote) > 10:\n errors.append(\"оценка должна быть 0 .. 10\")\n birthday['year'] = request.POST.get('year')\n birthday['month'] = request.POST.get('month')\n birthday['day'] = request.POST.get('day')\n birthday = {k: v.strip() for k, v in birthday.items()}\n dtime_str = \"{}-{}-{}\".format(\n birthday['year'],\n birthday['month'],\n birthday['day']\n )\n try:\n b_date = datetime.strptime(dtime_str, \"%Y-%m-%d\")\n b_date = b_date.replace(tzinfo=utc)\n age_error = check_age(b_date)\n if age_error:\n errors.append(age_error)\n except ValueError:\n errors.append(\"введите корректную дату\")\n else:\n fields['birthday'] = b_date\n photo = request.FILES.get('file')\n if photo:\n if not photo.content_type == \"image/jpeg\":\n errors.append(\"фото должно быть в jpeg формате\")\n else:\n fields['photo'] = photo\n if errors:\n context['errors'] = errors\n else:\n client = models.Clients.objects.update_or_create(\n pk=client_id,\n defaults=fields\n )[0]\n if vote:\n models.Votes.objects.update_or_create(\n pk=client.id,\n defaults={'rating': int(vote)}\n )\n return redirect('/')\n if client_id:\n try:\n client = models.Clients.objects.prefetch_related().get(pk=client_id)\n context['client'] = client\n except:\n return redirect('/')\n return render(request, 'clients/clients__control.html', context)\n\ndef clients_vote(request):\n media_url = settings.MEDIA_URL\n clients_qs = models.Clients.objects.prefetch_related().all()\n clients_qs = clients_qs.order_by(\"clients_votes_related__rating\").reverse()\n context = {\"clients\": clients_qs, \"media_url\": media_url}\n return render(request, 'clients/clients__vote.html', context)\n\n@auth(\"admins\", models.Users.objects, lambda: redirect('/'))\ndef clients_get_excel(request, task_id):\n response = HttpResponse(content_type='application/xls')\n response['Content-Disposition'] = 'attachment; filename=\"clients.xlsx\"'\n response['Content-Type'] = 'application/download'\n res = base64.standard_b64decode(AsyncResult(task_id).result.encode('utf-8'))\n response.write(res)\n return response\n", "sub_path": "problem/clients/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 8913, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.apps.apps.get_model", "line_number": 32, "usage_type": "call"}, {"api_name": "django.apps.apps", "line_number": 32, "usage_type": "name"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "name"}, {"api_name": "django.utils.timezone.utc", "line_number": 39, "usage_type": "name"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 41, "usage_type": "name"}, {"api_name": "django.utils.timezone.utc", "line_number": 41, "usage_type": "name"}, {"api_name": "problem.tools.crypto.Hash", "line_number": 47, "usage_type": "call"}, {"api_name": "problem.tools.crypto", "line_number": 47, "usage_type": "name"}, {"api_name": "problem.clients.models.Users.objects.get", "line_number": 68, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 68, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 68, "usage_type": "name"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 69, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 83, "usage_type": "call"}, {"api_name": "problem.tools.crypto.Hash", "line_number": 87, "usage_type": "call"}, {"api_name": "problem.tools.crypto", "line_number": 87, "usage_type": "name"}, {"api_name": "problem.tools.strings.get_rand_string", "line_number": 88, "usage_type": "call"}, {"api_name": "problem.tools.strings", "line_number": 88, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 94, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 94, "usage_type": "call"}, {"api_name": "problem.tools.request_handler.get_client_ip", "line_number": 97, "usage_type": "call"}, {"api_name": "problem.tools.request_handler", "line_number": 97, "usage_type": "name"}, {"api_name": "problem.tools.request_handler.get_client_ip", "line_number": 102, "usage_type": "call"}, {"api_name": "problem.tools.request_handler", "line_number": 102, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 108, "usage_type": "call"}, {"api_name": "problem.tools.decorators.request.auth", "line_number": 54, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 54, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 54, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 54, "usage_type": "call"}, {"api_name": "problem.clients.models.Users.objects.get", "line_number": 116, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 116, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 116, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 119, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_http_methods", "line_number": 112, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 126, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 126, "usage_type": "name"}, {"api_name": "problem.clients.models.Clients.objects.all", "line_number": 127, "usage_type": "call"}, {"api_name": "problem.clients.models.Clients", "line_number": 127, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 127, "usage_type": "name"}, {"api_name": "problem.common_data.pagination", "line_number": 137, "usage_type": "attribute"}, {"api_name": "problem.common_data", "line_number": 137, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 145, "usage_type": "call"}, {"api_name": "problem.tools.decorators.request.auth", "line_number": 124, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 124, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 124, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 124, "usage_type": "call"}, {"api_name": "problem.tools.check.isfloat", "line_number": 164, "usage_type": "call"}, {"api_name": "problem.tools.check", "line_number": 164, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 178, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 178, "usage_type": "name"}, {"api_name": "django.utils.timezone.utc", "line_number": 179, "usage_type": "name"}, {"api_name": "problem.clients.models.Clients.objects.update_or_create", "line_number": 196, "usage_type": "call"}, {"api_name": "problem.clients.models.Clients", "line_number": 196, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 196, "usage_type": "name"}, {"api_name": "problem.clients.models.Votes.objects.update_or_create", "line_number": 201, "usage_type": "call"}, {"api_name": "problem.clients.models.Votes", "line_number": 201, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 201, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 205, "usage_type": "call"}, {"api_name": "problem.clients.models.Clients.objects.prefetch_related", "line_number": 208, "usage_type": "call"}, {"api_name": "problem.clients.models.Clients", "line_number": 208, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 208, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 211, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 212, "usage_type": "call"}, {"api_name": "problem.tools.decorators.request.auth", "line_number": 147, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 147, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 147, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 147, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 215, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 215, "usage_type": "name"}, {"api_name": "problem.clients.models.Clients.objects.prefetch_related", "line_number": 216, "usage_type": "call"}, {"api_name": "problem.clients.models.Clients", "line_number": 216, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 216, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 219, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 223, "usage_type": "call"}, {"api_name": "base64.standard_b64decode", "line_number": 226, "usage_type": "call"}, {"api_name": "celery.result.AsyncResult", "line_number": 226, "usage_type": "call"}, {"api_name": "problem.tools.decorators.request.auth", "line_number": 221, "usage_type": "call"}, {"api_name": "problem.clients.models.Users", "line_number": 221, "usage_type": "attribute"}, {"api_name": "problem.clients.models", "line_number": 221, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 221, "usage_type": "call"}]} +{"seq_id": "138959795", "text": "'''\nCreated on Apr 6, 2017\n\n@author: BanhDzui\n'''\nfrom rules_mining.Apriori import Apriori\nfrom rules_mining.Generator import Generator\nfrom rules_mining.ItemsetDictionary import ItemsetDictionary\n\nfrom rules_mining.ItemsetFormatter import ItemsetFormatter\nfrom rules_mining.RuleFormatter import RuleFormatter\nfrom rules_mining.AssociationRule import AssociationRule\n\nfrom rules_mining.HashTable import HashTable\nfrom rules_mining.Helper import merge_itemsets, itemset_2_string\nfrom rules_mining.RulesCollection import RulesDictionary\n\nfrom objective_measures.Interestingness import ObjectiveMeasure as om\n\nimport numpy as np\nimport json\n\nclass NegativeRuleMiner(object): \n '''\n This class is used to generate and store a Naive Belief System \n by using the most confident association rules\n '''\n\n def __init__(self, filter_name, data_set):\n \n self.temp_folder = 'tmp/'\n \n self.itemset_tmp_file = self.temp_folder + 'miner.tmp.itemsets'\n self.rules_tmp_file = self.temp_folder + 'miner.tmp.rules'\n self.best_rules_file = self.temp_folder + 'miner.best_tmp.rules'\n \n self.interestingness_tmp_file = self.temp_folder +'miner.tmp.interestingness'\n self.probabilities_tmp_file = self.temp_folder +'miner.tmp.probabilities'\n \n self.filter_name = filter_name\n self.data_set = data_set\n \n self.nthreads = 4\n \n \n self.feature_tmp_file = self.temp_folder +'miner.tmp.features'\n self.non_redundant_rule_tmp_file = self.temp_folder +'miner.tmp.non_redundant_rules'\n self.non_redundant_rule_feature_tmp_file = self.temp_folder + 'miner.tmp.non_redundant_rules.features'\n \n \n '''\n Find all pairs of items such that one of them includes the other\n This function returns a dictionary. If (A includes B or B includes A) then they should not appear in same item-sets. \n '''\n def findInclusiveItemPairs(self, minsup, exclusive_item_filter):\n inclusive_items_dict = {}\n apriori_model = Apriori()\n \n L1 = apriori_model.generate_L1(self.data_set, minsup)\n freq_one_item_itemset_dict = L1.get_itemset_dictionary()\n freq_one_item_itemset_dict.ntransactions = self.data_set.size()\n \n L2 = HashTable()\n apriori_model.generate_Lk(minsup, L1, L2, k=2)\n freq_two_item_itemset_dict = L2.get_itemset_dictionary()\n freq_two_item_itemset_dict.ntransactions = self.data_set.size()\n \n nitems = len(freq_one_item_itemset_dict.itemsets)\n all_items = list(freq_one_item_itemset_dict.itemsets.keys())\n for i in range(nitems-1):\n first_item = all_items[i]\n nfirst = freq_one_item_itemset_dict.get_frequency(first_item[0])\n if exclusive_item_filter(first_item): continue\n \n for j in range(i+1, nitems):\n second_item = all_items[j]\n if exclusive_item_filter(second_item): continue\n \n merge_key = itemset_2_string(merge_itemsets(first_item, second_item))\n nboth = freq_two_item_itemset_dict.get_frequency(merge_key)\n if nboth == 0: continue\n \n nsecond = freq_one_item_itemset_dict(second_item[0])\n if nboth/nfirst >= 0.999 or nboth/nsecond >= 0.999:\n inclusive_items_dict[merge_key] = True\n return inclusive_items_dict\n \n \n '''\n Load generated frequent itemsets from file. \n This method must be called after generate_freq_itemsets is called\n '''\n def load_freq_itemset_dictionary(self):\n observations_dict = ItemsetDictionary(0)\n observations_dict.load_file(self.itemset_tmp_file)\n return observations_dict\n \n '''\n Load generated association rules from file. \n This method must be called after generate_association_rules is called\n '''\n def load_rule_dictionary(self):\n rules_dict = RulesDictionary()\n \n for i in range(self.nthreads):\n file_name = self.rules_tmp_file + '.' + str(i)\n rules_dict.load_file(file_name)\n \n return rules_dict\n\n \n '''\n Generate frequent itemsets from data-set\n '''\n def generate_freq_itemsets(self, min_sup_src, itemset_max_size):\n \n print ('generating frequent item-sets...')\n inclusive_items_filter = getattr(RuleFormatter, self.filter_name + 'Right')\n inclusive_items_dict = self.findInclusiveItemPairs(min_sup_src, inclusive_items_filter)\n \n apriori_model = Apriori(self.temp_folder)\n apriori_model.generate_freq_itemsets_w(self.data_set, \n min_sup_src*self.data_set.size(), \n self.nthreads, \n itemset_max_size, \n inclusive_items_dict, \n self.itemset_tmp_file)\n \n '''\n Generate association rules from data-set. This method must be called after generate_freq_itemsets(...) is called\n '''\n def generate_association_rules(self, min_conf):\n freq_itemsets_dict = self.load_freq_itemset_dictionary()\n \n print ('generating rules ....')\n itemset_formatter = getattr(ItemsetFormatter, self.filter_name)\n rule_formatter = getattr(RuleFormatter, self.filter_name)\n rule_generator = Generator(freq_itemsets_dict, min_conf, itemset_formatter, rule_formatter, self.nthreads)\n rule_generator.execute(self.rules_tmp_file)\n \n '''\n Generate association rules and select K patterns with highest confidence.\n ''' \n def generate_itemsets_and_rules(self, min_sup_src, min_conf, itemset_max_size = -1):\n self.generate_freq_itemsets(min_sup_src, itemset_max_size)\n self.generate_association_rules(min_conf)\n self.extract_feature_vectors_()\n \n '''\n Compute confidence for all association rules generated from data-set\n '''\n def compute_confidence(self, association_rules_list):\n observations_dict = self.load_freq_itemset_dictionary()\n \n rule_confidence_dict = {}\n for rule in association_rules_list:\n left, _, both = observations_dict.get_frequency_tuple(rule)\n rule_confidence_dict[rule.serialize()] = (both/left, both)\n return rule_confidence_dict\n\n '''\n Compute values of 31 interestingness measures for all association rules generated from data-set\n '''\n def compute_interestingnesses(self, output_file):\n print ('computing correlation among interestingness measures...')\n #measures = [om.confidence, om.lift]\n \n measures = [om.confidence, om.coverage, om.prevalence, om.recall, om.specificity, \n om.classificationError, om.lift, om.leverage, om.change_of_support, om.relative_risk, \n om.jaccard, om.certainty_factor, om.odd_ratio, om.yuleQ, om.yuleY, \n om.klosgen, om.conviction, om.weighting_dependency, \n om.collective_strength, om.jmeasure, \n om.one_way_support, om.two_ways_support, om.two_ways_support_variation, \n om.linear_coefficient, om.piatetsky_shapiro, om.loevinger,\n om.information_gain, om.sebag_schoenauner, om.least_contradiction, \n om.odd_multiplier, om.counter_example_rate, om.zhang]\n \n print('loading frequent item-sets....')\n freq_itemsets_dict = self.load_freq_itemset_dictionary()\n association_rules = self.load_association_rules()\n ntransactions = freq_itemsets_dict.ntransactions\n print ('computing interestingness for all rules ....')\n \n with open(output_file, 'w') as write_file:\n for rule in association_rules:\n interestingness = []\n lhs_frequency, rhs_frequency, both_frequency = freq_itemsets_dict.get_frequency_tuple(rule)\n \n for index in range(len(measures)):\n value = measures[index](lhs_frequency/ntransactions, \n rhs_frequency/ntransactions, \n both_frequency/ntransactions)\n interestingness.append(value)\n write_file.write(rule.serialize() + ';') \n write_file.write(';'.join([str(x) for x in interestingness]))\n write_file.write('\\n') \n \n '''\n Load features of non-redundant rules which are saved in temp files.\n This method returns a sparse feature matrix.\n '''\n def load_feature_vectors(self):\n \n data = []\n with open(self.non_redundant_rule_tmp_file, 'r') as feature_reader:\n for line in feature_reader:\n _, f_vector = json.loads(line.strip())\n data.append(f_vector)\n \n return np.array(data)\n \n '''\n Load non-redundant rules which are saved in temp files.\n This method returns a list of rules.\n '''\n def load_association_rules(self):\n association_rules_list = []\n with open(self.non_redundant_rule_tmp_file, 'r') as rules_reader:\n for line in rules_reader:\n rule_text, _ = json.loads(line.strip())\n association_rules_list.append(AssociationRule.string_2_rule(rule_text.strip()))\n return association_rules_list\n \n '''\n Load features of non-redundant rules which are saved in temp files\n This method return features under dictionary form in which key is rule and value is its features.\n '''\n def load_rules_features_as_dictionary(self):\n features_dict = {}\n with open(self.non_redundant_rule_tmp_file, 'r') as feature_reader:\n for line in feature_reader:\n rule_text, f_vector = json.loads(line.strip())\n features_dict[rule_text] = f_vector\n \n return features_dict\n\n \n '''\n Extract features for rules which are save in temp files.\n Result is saved into another temp file.\n '''\n \n def extract_feature_vectors_(self):\n #print ('Determine feature vector ....')\n \n measures = [om.support, om.confidence, om.coverage, om.prevalence, om.recall, om.specificity, \n om.classificationError, om.lift, om.leverage, om.change_of_support, om.relative_risk, \n om.jaccard, om.certainty_factor, om.odd_ratio, om.yuleQ, om.yuleY, \n om.klosgen, om.conviction, om.weighting_dependency, \n om.collective_strength, om.jmeasure, \n om.one_way_support, om.two_ways_support, om.two_ways_support_variation, \n om.linear_coefficient, om.piatetsky_shapiro, om.loevinger,\n om.information_gain, om.sebag_schoenauner, om.least_contradiction, \n om.odd_multiplier, om.counter_example_rate, om.zhang]\n \n #measures = [om.support, om.confidence, om.zhang]\n observations_dict = self.load_freq_itemset_dictionary()\n ntransactions = observations_dict.ntransactions\n \n features_writer = open(self.non_redundant_rule_tmp_file, 'w')\n for i in range(self.nthreads):\n input_file = self.rules_tmp_file + '.' + str(i)\n \n with open(input_file, 'r') as rules_reader:\n for line in rules_reader:\n \n rule = AssociationRule.string_2_rule(line.strip())\n \n f_vector = []\n lhs_frequency, rhs_frequency, both_frequency = observations_dict.get_frequency_tuple(rule)\n \n for index in range(len(measures)):\n value = measures[index](lhs_frequency/ntransactions, \n rhs_frequency/ntransactions, \n both_frequency/ntransactions)\n f_vector.append(value)\n \n f_vector.append(len(rule.left_items))\n #f_vector = rule.compute_probs(observations_dict)\n features_writer.write(json.dumps((rule.serialize(),f_vector)))\n features_writer.write('\\n')\n \n features_writer.close()\n ", "sub_path": "rules_mining/NegativeRuleMiner.py", "file_name": "NegativeRuleMiner.py", "file_ext": "py", "file_size_in_byte": 12596, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "rules_mining.Apriori.Apriori", "line_number": 57, "usage_type": "call"}, {"api_name": "rules_mining.HashTable.HashTable", "line_number": 63, "usage_type": "call"}, {"api_name": "rules_mining.Helper.itemset_2_string", "line_number": 79, "usage_type": "call"}, {"api_name": "rules_mining.Helper.merge_itemsets", "line_number": 79, "usage_type": "call"}, {"api_name": "rules_mining.ItemsetDictionary.ItemsetDictionary", "line_number": 94, "usage_type": "call"}, {"api_name": "rules_mining.RulesCollection.RulesDictionary", "line_number": 103, "usage_type": "call"}, {"api_name": "rules_mining.RuleFormatter.RuleFormatter", "line_number": 118, "usage_type": "argument"}, {"api_name": "rules_mining.Apriori.Apriori", "line_number": 121, "usage_type": "call"}, {"api_name": "rules_mining.ItemsetFormatter.ItemsetFormatter", "line_number": 136, "usage_type": "argument"}, {"api_name": "rules_mining.RuleFormatter.RuleFormatter", "line_number": 137, "usage_type": "argument"}, {"api_name": "rules_mining.Generator.Generator", "line_number": 138, "usage_type": "call"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.confidence", "line_number": 168, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 168, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.coverage", "line_number": 168, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.prevalence", "line_number": 168, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.recall", "line_number": 168, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.specificity", "line_number": 168, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.classificationError", "line_number": 169, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 169, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.lift", "line_number": 169, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.leverage", "line_number": 169, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.change_of_support", "line_number": 169, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.relative_risk", "line_number": 169, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.jaccard", "line_number": 170, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 170, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.certainty_factor", "line_number": 170, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.odd_ratio", "line_number": 170, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.yuleQ", "line_number": 170, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.yuleY", "line_number": 170, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.klosgen", "line_number": 171, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 171, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.conviction", "line_number": 171, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.weighting_dependency", "line_number": 171, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.collective_strength", "line_number": 172, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 172, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.jmeasure", "line_number": 172, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.one_way_support", "line_number": 173, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 173, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.two_ways_support", "line_number": 173, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.two_ways_support_variation", "line_number": 173, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.linear_coefficient", "line_number": 174, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 174, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.piatetsky_shapiro", "line_number": 174, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.loevinger", "line_number": 174, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.information_gain", "line_number": 175, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 175, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.sebag_schoenauner", "line_number": 175, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.least_contradiction", "line_number": 175, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.odd_multiplier", "line_number": 176, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 176, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.counter_example_rate", "line_number": 176, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.zhang", "line_number": 176, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 210, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 220, "usage_type": "call"}, {"api_name": "rules_mining.AssociationRule.AssociationRule.string_2_rule", "line_number": 221, "usage_type": "call"}, {"api_name": "rules_mining.AssociationRule.AssociationRule", "line_number": 221, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 232, "usage_type": "call"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.support", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 246, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.confidence", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.coverage", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.prevalence", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.recall", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.specificity", "line_number": 246, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.classificationError", "line_number": 247, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 247, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.lift", "line_number": 247, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.leverage", "line_number": 247, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.change_of_support", "line_number": 247, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.relative_risk", "line_number": 247, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.jaccard", "line_number": 248, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 248, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.certainty_factor", "line_number": 248, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.odd_ratio", "line_number": 248, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.yuleQ", "line_number": 248, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.yuleY", "line_number": 248, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.klosgen", "line_number": 249, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 249, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.conviction", "line_number": 249, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.weighting_dependency", "line_number": 249, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.collective_strength", "line_number": 250, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 250, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.jmeasure", "line_number": 250, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.one_way_support", "line_number": 251, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 251, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.two_ways_support", "line_number": 251, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.two_ways_support_variation", "line_number": 251, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.linear_coefficient", "line_number": 252, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 252, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.piatetsky_shapiro", "line_number": 252, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.loevinger", "line_number": 252, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.information_gain", "line_number": 253, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 253, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.sebag_schoenauner", "line_number": 253, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.least_contradiction", "line_number": 253, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.odd_multiplier", "line_number": 254, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure", "line_number": 254, "usage_type": "name"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.counter_example_rate", "line_number": 254, "usage_type": "attribute"}, {"api_name": "objective_measures.Interestingness.ObjectiveMeasure.zhang", "line_number": 254, "usage_type": "attribute"}, {"api_name": "rules_mining.AssociationRule.AssociationRule.string_2_rule", "line_number": 267, "usage_type": "call"}, {"api_name": "rules_mining.AssociationRule.AssociationRule", "line_number": 267, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 280, "usage_type": "call"}]} +{"seq_id": "427362717", "text": "#!/usr/bin/env python\n\n\"\"\"\n simple-example.py\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom rsub import *\nfrom matplotlib import pyplot as plt\nplt.show = show_plot\n\nimport argparse\nimport numpy as np\nimport networkx as nx\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\n\nimport heat\nfrom utils.build_graph import build_regular_structure\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--outpath', type=str, default='./simple-feats')\n parser.add_argument('--plot', action=\"store_true\")\n \n parser.add_argument('--seed', type=int, default=123)\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n \n args = parse_args()\n np.random.seed(args.seed)\n \n # --\n # Create graph\n \n G, colors = build_regular_structure(\n width_basis=15,\n basis_type=\"star\",\n nb_shapes=5,\n shape=[\"house\"],\n start=0,\n add_random_edges=0\n )\n \n W = nx.adjacency_matrix(G)\n W.eliminate_zeros()\n taus = [0.5, 0.6 , 0.7, 0.8, 0.9, 1.0, 1.1]\n \n # Apply kernel at every node\n signal = np.eye(W.shape[0])\n heat_kernel = heat.Heat(W=W, taus=taus)\n feats = heat_kernel.featurize(signal)\n \n print('simple-example.py: saving feats to %s.npy' % args.outpath)\n np.save(args.outpath, feats)\n \n # --\n # Cluster resulting features\n \n # Normalize features\n nfeats = feats - feats.mean(axis=0, keepdims=True)\n nfeats /= (1e-10 + nfeats.std(axis=0, keepdims=True))\n nfeats[np.isnan(nfeats)] = 0\n \n # Reduce dimension\n pca_feats = PCA(n_components=10).fit_transform(nfeats)\n \n # Cluster\n clus = KMeans(n_clusters=len(set(colors))).fit(pca_feats).labels_\n \n if args.plot:\n from matplotlib import pyplot as plt\n # Plot features in first 2 PCA dimensions\n jitter_pca_feats = pca_feats + np.random.uniform(0, 1, pca_feats.shape)\n _ = plt.scatter(jitter_pca_feats[:,0], jitter_pca_feats[:,1], alpha=0.25, c=clus, cmap='rainbow')\n plt.show()\n\n # Show roles on graph\n np.random.seed(1235)\n _ = nx.draw(G, pos=nx.spring_layout(G, iterations=200), \n node_color=clus, node_size=50, cmap='rainbow', ax=plt.figure().add_subplot(111))\n plt.show()\n", "sub_path": "examples/simple-example.py", "file_name": "simple-example.py", "file_ext": "py", "file_size_in_byte": 2293, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.show", "line_number": 11, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 35, "usage_type": "attribute"}, {"api_name": "utils.build_graph.build_regular_structure", "line_number": 40, "usage_type": "call"}, {"api_name": "networkx.adjacency_matrix", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 54, "usage_type": "call"}, {"api_name": "heat.Heat", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 67, "usage_type": "call"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 70, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 78, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 83, "usage_type": "attribute"}, {"api_name": "networkx.draw", "line_number": 84, "usage_type": "call"}, {"api_name": "networkx.spring_layout", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}]} +{"seq_id": "328937868", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 19 16:06:21 2019\n\n@author: aj611\n\"\"\"\n\n\n\"\"\"\ndef GrowImage(SampleImage, Image, WindowSize):\n while Image not filled to:\n progress = 0\n PixelList = GetUnfilledNeighbors(Image)\n for each pixel in PixelList do:\n Template = GetNeighborhoodWindow(Pixel)\n BestMatches = findMatches(Template, SampleImage)\n BestMatch = RandomPick(BestMatches)\n if(BestMatch.error < MaxErrThreoshold) then\n Pixel.value = BestMatch.value\n progress = 1\n end\n end\n if progress == 0:\n then MaxErrthreshold = MaxErrthreshold * 1.1\n end\n return Image\nend\n\ndef FindMatches(Template, SampleImage):\n ValidMask = 1s where Template is filles, 0s otherwise\n GaussMask = Gaussian2D(WindowsSize, Sigma)\n TotWeight = sum i, j GaussMask(i, j) * ValidMask(i, j)\n for i, j do:\n for ii, jj do:\n dist = (Template(ii, jj) - SampleImage(i - ii, j - jj))^2\n SSD(i, j) = SSD(i, j) + dist*ValidMask(ii, jj)*GaussMask(ii, jj)\n end\n SSD(i, j) = SSD(i, j) /TotWeight\n end\n PixelList - allpixels (i, j) where SSD(i, j) <= min(SSD)*(1 + ErrThreshold)\n return PixelList\nend\n\n\"\"\"\n\nimport numpy as np\nfrom skimage import io, morphology\nimport random as rd\nimport math as mt\nfrom matplotlib.image import imread\nimport matplotlib.pyplot as plt\n\nIMAGE_DIM_HEIGHT = 200\nIMAGE_DIM_WIDTH = 200\nMAX_PIXEL_VALUE = 255\nSEED_SIZE = 3\nWINDOW_SIZE = 21\nGAUSS_SIGMA = 1.4\nERR_THRESHOLD = 0.3\nMAX_ERR_THRESHOLD = 0.1\nTOTAL_PIXELS_IN_WINDOW = (WINDOW_SIZE)*(WINDOW_SIZE)\n\n#print(TOTAL_PIXELS_IN_WINDOW)\n\n\ndef find_matches(template, sample_image, valid_mask, gaussian_mask):\n #print(\"gaussian_mask\")\n #print(gaussian_mask)\n #print(\"valid mask\")\n #print(valid_mask)\n total_weight = np.sum(np.multiply(gaussian_mask, valid_mask))\n SSD = []\n center_pixel = []\n sample_image_row, sample_image_col = sample_image.shape\n pad_size = mt.floor(WINDOW_SIZE/2)\n #print(\"hi\")\n for i in range(pad_size, sample_image_row - pad_size - 1):\n for j in range(pad_size, sample_image_col - pad_size - 1):\n row_min = i - pad_size\n row_max = i + pad_size + 1\n col_min = j - pad_size\n col_max = j + pad_size + 1\n distance = (template - sample_image[row_min:row_max, col_min:col_max])**2\n #print(\"distance*gaussian_mask*valid_mask\")\n #print(distance*gaussian_mask*valid_mask)\n temp = np.sum(distance*gaussian_mask*valid_mask)\n temp = temp/total_weight\n SSD.append(temp)\n center_pixel.append(sample_image[i, j])\n \n #print(\"SSD\")\n #print(SSD)\n min_err = min(SSD)\n #print(\"min_err\")\n #print(min_err)\n best_match = []\n \n for i in range(len(SSD)):\n if SSD[i] <= min_err*(1 + ERR_THRESHOLD):\n best_match.append((SSD[i], center_pixel[i]))\n #print(\"hello\")\n #print(\"best_match len\")\n #print(len(best_match))\n return best_match\n'''\ndef find_matches(template, src_image, valid_mask, gauss_mask):\n total_weight = np.sum(np.multiply(gauss_mask, valid_mask))\n pad_size = mt.floor(WINDOW_SIZE/2)\n if total_weight == 0:\n print(\"Trouble\")\n\n ssd = []\n pixel_val = []\n src_row, src_col = np.shape(src_image)\n for i in range(pad_size, src_row-pad_size-1):\n for j in range(pad_size, src_col-pad_size-1):\n distance = (template - src_image[i-pad_size:i + pad_size + 1, j - pad_size:j + pad_size + 1]) ** 2\n ssd.append(np.sum(distance * gauss_mask * valid_mask) / total_weight)\n pixel_val.append(src_image[i, j])\n\n min_error = min(ssd)\n # print \"Min Err loop= \"+str(min_error)\n rPack=[]\n\n for i in range(len(ssd)):\n if ssd[i]<=min_error*(1+ERR_THRESHOLD):\n rPack.append((ssd[i], pixel_val[i]))\n\n # print len(rPack)\n if len(rPack)==0:\n print(template)\n return rPack \n''' \ndef find_matches_modified(template,image_window, valid_mask, gauss_mask, centre_pixels):\n pad_size = mt.floor(WINDOW_SIZE/2)\n template = np.reshape(template, TOTAL_PIXELS_IN_WINDOW)\n gauss_mask = np.reshape(gauss_mask, TOTAL_PIXELS_IN_WINDOW)\n valid_mask = np.reshape(valid_mask, TOTAL_PIXELS_IN_WINDOW)\n total_weight = np.sum(np.multiply(gauss_mask, valid_mask))\n distance = (image_window-template)**2\n ssd = np.sum((distance*gauss_mask*valid_mask) / total_weight, axis=1)\n min_error = min(ssd)\n # print \"Min err mat= \"+str(min_error)\n mid = ((2 * pad_size + 1)*(2 * pad_size + 1)) / 2;\n best_matches = []\n for i in range(len(ssd)):\n if ssd[i]<=min_error*(1+ERR_THRESHOLD):\n best_matches.append((ssd[i], centre_pixels[i]))\n\n #return [[err, image_window[i*WINDOW_SIZE + (mid - 1)]] for i, err in enumerate(ssd) if err <= min_error*(1+ERR_THRESHOLD)]\n return best_matches\n\n\ndef gaussian2D(window_size):\n m,n = [(ss-1.)/2. for ss in window_size]\n y,x = np.ogrid[-m:m+1,-n:n+1]\n h = np.exp( -(x*x + y*y) / (2.*GAUSS_SIGMA*GAUSS_SIGMA) )\n h[ h < np.finfo(h.dtype).eps*h.max() ] = 0\n sumh = h.sum()\n if sumh != 0:\n h /= sumh\n return h\n\ndef extract_all_frames(sample_image):\n pad_size = mt.floor(WINDOW_SIZE/2)\n possible_frames = []\n \n sample_image_row, sample_image_col = sample_image.shape\n # iterate over the entire sample image array and extratc all possible windows\n for i in range(pad_size, sample_image_row - pad_size - 1):\n for j in range(pad_size, sample_image_col - pad_size - 1):\n possible_frames.append(np.reshape(sample_image[i-pad_size:i + pad_size + 1, j - pad_size: j + pad_size + 1], (2 * pad_size + 1) ** 2))\n return np.double(possible_frames)\n\ndef extract_all_frames_centers(sample_image):\n pad_size = mt.floor(WINDOW_SIZE/2)\n possible_frames = []\n centers = []\n \n sample_image_row, sample_image_col = sample_image.shape\n # iterate over the entire sample image array and extratc all possible windows\n for i in range(pad_size, sample_image_row - pad_size - 1):\n for j in range(pad_size, sample_image_col - pad_size - 1):\n possible_frames.append(np.reshape(sample_image[i-pad_size:i + pad_size + 1, j - pad_size: j + pad_size + 1], (2 * pad_size + 1) ** 2))\n centers.append(sample_image[i, j])\n return np.double(possible_frames), np.double(centers)\n \n#print(\"reading image\")\nsample_image = imread(\"T5.gif\")\n#plt.imshow(sample_image)\n\n#plt.imshow(sample_image, cmap = \"gray\")\n#plt.gcf().clear()\n#print(\"printing image dimension\")\nsample_image_row, sample_image_col = sample_image.shape\n\n\n#print(\"normalizing image by dividing with max pixel value\")\nsample_image_normalized = sample_image/MAX_PIXEL_VALUE\n#sample_image_normalized = sample_image/1\n#print(sample_image_normalized)\n#print(\"printing modified image dimension\")\n#print(sample_image_normalized.shape)\n#img1 = io.imread(\"T2.gif\")\n#plt.imshow(sample_image_normalized, cmap = \"gray\")\n#plt.gcf().clear()\n#print(img1.format)\ntotal_pixels = IMAGE_DIM_HEIGHT*IMAGE_DIM_WIDTH\n#print(\"total pixels to be filled\")\n#print(total_pixels)\n\n# image will contain the final synthesized image\n#print(\"Initializing the empty image consisting of all 0s\")\nimage = np.zeros((IMAGE_DIM_HEIGHT, IMAGE_DIM_WIDTH))\n\n\n#print(\"Picking up a random 3x3 square patch from sample image\")\nrand_row = rd.randint(0, sample_image_row - SEED_SIZE)\nrand_col = rd.randint(0, sample_image_col - SEED_SIZE)\n\n#print(\"Creating the random seed from the original image\")\nseed = sample_image_normalized[rand_row: rand_row + SEED_SIZE, rand_col: rand_col + SEED_SIZE]\n#plt.imshow(seed, cmap = \"gray\")\n#plt.imshow(seed)\n\n#plt.gcf().clear() \n\n#print(\"Pasting the 3x3 square seed in center of this almost empty image from the sample image\")\nimage[mt.floor(IMAGE_DIM_HEIGHT/2) - 1: mt.floor(IMAGE_DIM_HEIGHT/2) + 2, \\\n mt.floor(IMAGE_DIM_WIDTH/2) - 1: mt.floor(IMAGE_DIM_WIDTH/2) + 2] \\\n = seed\n\n#print(\"pasting a 3x3 square patch of 1s in the filled_list\" )\nfilled_pixels = SEED_SIZE*SEED_SIZE\n#print(\"filled pixels\")\n#print(filled_pixels)\n\n\n# filled_list keeps track of the pixels already filled. We use it to extract the neighborhood each time\nfilled_list = np.zeros((IMAGE_DIM_HEIGHT, IMAGE_DIM_WIDTH))\n#print(\"Fixing the 3x3 square seed in center of this almost empty image\")\nfilled_list[mt.floor(IMAGE_DIM_HEIGHT/2) - 1: mt.floor(IMAGE_DIM_HEIGHT/2) + 2, \\\n mt.floor(IMAGE_DIM_WIDTH/2) - 1: mt.floor(IMAGE_DIM_WIDTH/2) + 2] \\\n = np.ones((SEED_SIZE, SEED_SIZE))\n\n #size of padding is half of the window size as we need to pad all four sides of the image matrix\npad_size = mt.floor(WINDOW_SIZE/2)\n# we need to zero pad both the sample image and image to take care of the pixels at the borders\nfilled_list_padded = np.lib.pad(filled_list, pad_size, 'constant', constant_values = 0)\nimage_padded = np.lib.pad(image, pad_size, 'constant', constant_values = 0) \n \nmax_error_threshold = MAX_ERR_THRESHOLD\n#print(\"hello\")\npossible_frames, possible_frames_centers = extract_all_frames_centers(sample_image_normalized)\n#possible_frames = extract_all_frames(sample_image_normalized)\n#print(\"hi\")\n\ngaussian_mask = gaussian2D((WINDOW_SIZE, WINDOW_SIZE))\n#print(\"gaussian_mask\")\n#print(gaussian_mask)\n#print(gaussian_mask.shape)\n#plt.imshow(image, cmap = \"gray\")\n\nwhile filled_pixels < total_pixels:\n#while filled_pixels < 10:\n #print(\"filled pixels\")\n #print(filled_pixels)\n #plt.imshow(seed)\n progress = 0\n potential_pixel_row = []\n potential_pixel_col = []\n filled_list_neighbors = morphology.binary_dilation(filled_list)\n potential_pixel_row, potential_pixel_col = np.nonzero(filled_list_neighbors - filled_list)\n \n #print(\"potential_pixel_row\")\n #print(potential_pixel_row)\n #print(\"potential_pixel_col\")\n #print(potential_pixel_col)\n \n #print(\"building the actual neighbors by picking a pixel from potential pixels\" )\n filled_neighbors = []\n \n for i in range(len(potential_pixel_row)):\n pixel_row = potential_pixel_row[i]\n pixel_col = potential_pixel_col[i]\n #print(i)\n #print(\"the neighborhood consists of window size of pixels with the specific pixel at the center\")\n row_min = pixel_row - mt.floor(WINDOW_SIZE/2)\n row_max = pixel_row + mt.floor(WINDOW_SIZE/2) + 1\n col_min = pixel_col - mt.floor(WINDOW_SIZE/2)\n col_max = pixel_col + mt.floor(WINDOW_SIZE/2) + 1\n \n #print(\"For each potential pixel we check how many pixels are already filled in its window\")\n #print(\"this is done by counting the number of 1s in its window\")\n filled_neighbors.append(np.sum(filled_list[row_min:row_max, col_min:col_max]))\n \n # sorting this filled_neighbors in descending order i.e. the first argument gives the pixel\n # for which number of filled neighbors in the windows i maximum\n # this pixel is picked up to be grown because we want to minimize the loss in guessing neighborhood\n \n descending_filled_num = (-1) * np.array(filled_neighbors, dtype = \"int\")\n #print(filled_neighbors)\n #print(descending_filled_num)\n #print(\"Number of neighbors\")\n #print(len(descending_filled_num))\n #we need the indices where the number of neighbors filled is maximum\n descending_filled_num_indices = np.argsort(descending_filled_num)\n print(descending_filled_num_indices)\n \n #we need to iterate over the sorted list (key, value) pair like and pick the list elements\n #print(\"outside\")\n for x, i in enumerate(descending_filled_num_indices):\n print(\"x\")\n print(x)\n print(\"i\")\n print(i)\n # get the row, column of the selected pixel \n #use this to calculate the row_min, row_max in padded image\n sel_pix_row = potential_pixel_row[i]\n sel_pix_col = potential_pixel_col[i]\n \n # calculating the min and max of both row and columns of the region to be synthesized\n # because of the padding the nth index in original matrix is (n+pad_size) index in padded matrix\n padded_row_min = pad_size + potential_pixel_row[i] - pad_size\n padded_row_max = pad_size + potential_pixel_row[i] + pad_size + 1\n padded_col_min = pad_size + potential_pixel_col[i] - pad_size\n padded_col_max = pad_size + potential_pixel_col[i] + pad_size + 1\n \n best_matches = find_matches_modified(image_padded[padded_row_min: padded_row_max, padded_col_min: padded_col_max], \\\n possible_frames,filled_list_padded[padded_row_min: padded_row_max, padded_col_min: padded_col_max],\\\n gaussian_mask, possible_frames_centers) \n '''\n best_matches = find_matches(image_padded[padded_row_min: padded_row_max, padded_col_min: padded_col_max], \\\n possible_frames,filled_list_padded[padded_row_min: padded_row_max, padded_col_min: padded_col_max],\\\n gaussian_mask)\n '''\n #print(len(descending_filled_num_indices))\n #print(\"here\")\n #print(x)\n \n #print(\"len(best_matches)\")\n #print(len(best_matches))\n \n random_match = rd.randint(0, len(best_matches) - 1)\n #print(\"random_match\")\n #print(random_match)\n if best_matches[random_match][0] <= MAX_ERR_THRESHOLD:\n image_padded[pad_size + sel_pix_row][pad_size + sel_pix_col] = best_matches[random_match][1]\n image[sel_pix_row][sel_pix_col] = best_matches[random_match][1]\n filled_list_padded[pad_size + sel_pix_row][pad_size + sel_pix_col] = 1\n filled_list[sel_pix_row][sel_pix_col]=1\n \n filled_pixels = filled_pixels + 1\n progress = 1\n #print(\"inside\")\n #plt.imshow(image)\n if progress == 0:\n max_error_threshold = max_error_threshold * 1.1\n \nio.imsave(\"t5_win13_sigma0.8.jpeg\", image)\n#image = image * MAX_PIXEL_VALUE\n#plt.imshow(image, cmap = \"gray\")\n#plt.imshow(\"t1_new.gif\", cmap = \"gray\")\nplt.imshow(image)\n", "sub_path": "texture_synthesis.py", "file_name": "texture_synthesis.py", "file_ext": "py", "file_size_in_byte": 14269, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.sum", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 72, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 87, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.ogrid", "line_number": 157, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.finfo", "line_number": 159, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.double", "line_number": 174, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.double", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.image.imread", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 219, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 220, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 230, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 241, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 243, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 245, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.lib.pad", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.lib", "line_number": 250, "usage_type": "attribute"}, {"api_name": "numpy.lib.pad", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.lib", "line_number": 251, "usage_type": "attribute"}, {"api_name": "skimage.morphology.binary_dilation", "line_number": 273, "usage_type": "call"}, {"api_name": "skimage.morphology", "line_number": 273, "usage_type": "name"}, {"api_name": "numpy.nonzero", "line_number": 274, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 289, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 290, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 291, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 308, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 345, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 361, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 361, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 365, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 365, "usage_type": "name"}]} +{"seq_id": "271484767", "text": "# Owner(s): [\"module: codegen\"]\n\nimport torch\nfrom torch.testing._internal.common_utils import TestCase, run_tests, skipIfTorchDynamo, TEST_WITH_TORCHDYNAMO\nfrom torch.testing._internal.logging_tensor import LoggingTensor, LoggingTensorReentrant, capture_logs\nfrom torch.utils._pytree import tree_map\nfrom torch.fx.experimental.proxy_tensor import make_fx\n\nimport unittest\nimport logging\n\ndef are_aliased(x, y):\n if x._base is None and y._base is None:\n return False\n if x._base is not None and y._base is None:\n return x._base is y\n if x._base is None and y._base is not None:\n return y._base is x\n return x._base is y._base\n\n# Just for testing: a logging tensor that also transforms out-of-place ops into inplace ops.\n# That way even if the outer wrapper is functionalized, the inner wrapper will also need functionalization.\nclass InplaceLoggingTensor(LoggingTensorReentrant):\n @staticmethod\n def __new__(cls, e):\n r = torch.Tensor._make_wrapper_subclass(cls, e.shape, dtype=e.dtype, requires_grad=False)\n r.elem = e\n return r\n\n __torch_function__ = torch._C._disabled_torch_function_impl\n\n def __str__(self):\n return f'InplaceLoggingTensor({self.elem})'\n\n @classmethod\n def __torch_dispatch__(cls, func, types, args=(), kwargs=None):\n def unwrap(e):\n if isinstance(e, InplaceLoggingTensor):\n return e.elem\n else:\n return e\n\n def wrap(e):\n if isinstance(e, torch.Tensor):\n return InplaceLoggingTensor(e)\n else:\n return e\n f = func\n # this subclass converts all `add()` ops into `add_()` ops\n if f is torch.ops.aten.add.Tensor:\n f = torch.ops.aten.add_.Tensor\n\n with cls.context():\n rs = tree_map(wrap, f(*tree_map(unwrap, args), **tree_map(unwrap, kwargs)))\n # after running the (potentially transformed) op,\n # log the original op that we saw.\n logging.getLogger(\"LoggingTensor\").info(f\"{func.__module__}.{func.__name__}\", args, kwargs, rs)\n return rs\n\n\n\n@unittest.skipIf(TEST_WITH_TORCHDYNAMO, \"https://github.com/pytorch/pytorch/issues/81457\")\nclass TestFunctionalization(TestCase):\n # We can unify testing and use functionalize() here instead\n # if/when functorch moves into core.\n def _functionalize(self, f, *, reapply_views: bool):\n def wrapped(a):\n input_functional = torch._to_functional_tensor(a)\n torch._enable_functionalization(reapply_views=reapply_views)\n try:\n out = f(input_functional)\n finally:\n torch._disable_functionalization()\n torch._sync(input_functional)\n tree_map(torch._sync, out)\n out_unwrapped = tree_map(torch._from_functional_tensor, out)\n return out_unwrapped\n\n return wrapped\n\n def get_logs(self, func, inpt, *, reapply_views=False):\n traced_f = make_fx(self._functionalize(func, reapply_views=reapply_views))(inpt)\n return traced_f.code\n\n def assert_functionalization(self, func, inpt, *, reapply_views=False):\n input_clone = inpt.clone()\n input_clone2 = inpt.clone()\n input_functional = torch._to_functional_tensor(input_clone2)\n\n # Compare outputs (and mutated inputs), with and without functionalization.\n out_ref = func(inpt)\n\n torch._enable_functionalization(reapply_views=reapply_views)\n try:\n out_functional = func(input_functional)\n finally:\n torch._disable_functionalization()\n\n # We need to sync the input tensors first, in case there are any queued mutations left.\n torch._sync(input_functional)\n self.assertEqual(inpt, torch._from_functional_tensor(input_functional)) # input mutations should still occur\n\n # Handle tests with multi-tensor outputs\n if isinstance(out_ref, tuple) and isinstance(out_functional, tuple):\n out_refs, out_functionals = list(out_ref), list(out_functional)\n else:\n out_refs, out_functionals = [out_ref], [out_functional]\n\n for out_ref_, out_functional_ in zip(out_refs, out_functionals):\n self.assertEqual(out_ref_.size(), out_functional_.size())\n torch._sync(out_functional_)\n out_functional_unwrapped = torch._from_functional_tensor(out_functional_)\n self.assertEqual(out_ref_, out_functional_unwrapped)\n\n def test_save_for_backwards_segfault(self):\n inp = torch._to_functional_tensor(LoggingTensor(torch.randn(2, 2))).requires_grad_(True)\n inp.exp()\n\n def test_multiple_views_of_same_base(self):\n def f(x):\n y = x.view(-1)\n z = x.view(-1)\n x.add_(1)\n # y should have been updated.\n y2 = y + 1\n # z should have been updated too.\n z2 = z + 1\n return z2\n self.assert_functionalization(f, torch.ones(4))\n\n def test_simple(self):\n def f(x):\n # simple test: 1 view op, 1 inplace op\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n y.add_(tmp)\n z = x * x\n return y\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [4, 2]); a_1 = None\n add_tensor = torch.ops.aten.add.Tensor(view_copy_default, fill_scalar); view_copy_default = fill_scalar = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(add_tensor, [4, 2])\n mul_tensor = torch.ops.aten.mul.Tensor(view_copy_default_1, view_copy_default_1); view_copy_default_1 = None\n return add_tensor\n \"\"\")\n\n def test_simple_out(self):\n def f(x):\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n # the out= tensor will get resized, since it has size=0 to start.\n z = torch.empty(())\n torch.add(y, tmp, out=z)\n w = z * z\n return w\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [4, 2]); a_1 = None\n empty_1 = torch.ops.aten.empty.SymInt([], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n add_tensor = torch.ops.aten.add.Tensor(view_copy_default, fill_scalar); view_copy_default = fill_scalar = None\n mul_tensor = torch.ops.aten.mul.Tensor(add_tensor, add_tensor); add_tensor = None\n return mul_tensor\n \"\"\")\n\n def test_multi_out(self):\n def f(x):\n # aminmax.out returns a tuple of tensors.\n # functionalization should properly handle the tuple.\n out_min = torch.empty(4)\n out_max = torch.empty(4)\n torch.aminmax(x, dim=0, out=(out_max, out_min))\n return out_max\n self.assert_functionalization(f, torch.arange(8, dtype=torch.float32))\n logs = self.get_logs(f, torch.arange(8, dtype=torch.float32))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.SymInt([4], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n empty_1 = torch.ops.aten.empty.SymInt([4], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n aminmax_default = torch.ops.aten.aminmax.default(a_1, dim = 0); a_1 = None\n getitem = aminmax_default[0]\n getitem_1 = aminmax_default[1]; aminmax_default = None\n return getitem\n \"\"\")\n\n def test_tensor_ctr(self):\n def f(x):\n y = torch.tensor((1, 2, 3))\n z = y.view(-1)\n z.add_(1)\n return y\n self.assert_functionalization(f, torch.arange(3, dtype=torch.float32))\n\n def test_inplace_on_non_view(self):\n def f(x):\n # test for the case where we functionalize an inplace op on the other tensor - not a view.\n # This is worth checking because the tensor will have an empty ViewMeta stack, which needs to be special cased.\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n x.add_(tmp)\n return y\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [4, 2])\n add_tensor = torch.ops.aten.add.Tensor(a_1, fill_scalar); a_1 = fill_scalar = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(add_tensor, [4, 2]); add_tensor = None\n return view_copy_default_1\n \"\"\")\n\n # Some ops that are mutable are neither inplace nor out= ops.\n # They also need special handling.\n def test_mutable_op_not_inplace_or_other(self):\n def f(x):\n return torch._fused_moving_avg_obs_fq_helper(x, x, x, x, x, x, x, 1.0, 0, 1, 0)\n\n logs = self.get_logs(f, torch.ones(1))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n _fused_moving_avg_obs_fq_helper_functional_default = torch.ops.aten._fused_moving_avg_obs_fq_helper_functional.default(a_1, a_1, a_1, a_1, a_1, a_1, a_1, 1.0, 0, 1, 0); a_1 = None\n getitem = _fused_moving_avg_obs_fq_helper_functional_default[0]\n getitem_1 = _fused_moving_avg_obs_fq_helper_functional_default[1]\n getitem_2 = _fused_moving_avg_obs_fq_helper_functional_default[2]\n getitem_3 = _fused_moving_avg_obs_fq_helper_functional_default[3]\n getitem_4 = _fused_moving_avg_obs_fq_helper_functional_default[4]\n getitem_5 = _fused_moving_avg_obs_fq_helper_functional_default[5]; _fused_moving_avg_obs_fq_helper_functional_default = None\n return (getitem, getitem_1)\n \"\"\") # noqa: B950\n\n def test_as_strided(self):\n def f(x):\n y = x.as_strided((2,), (2,), 1)\n y.add_(1)\n return x\n self.assert_functionalization(f, torch.ones(9))\n logs = self.get_logs(f, torch.ones(9))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n as_strided_copy_default = torch.ops.aten.as_strided_copy.default(a_1, [2], [2], 1)\n add_tensor = torch.ops.aten.add.Tensor(as_strided_copy_default, 1); as_strided_copy_default = None\n as_strided_scatter_default = torch.ops.aten.as_strided_scatter.default(a_1, add_tensor, [2], [2], 1); a_1 = add_tensor = None\n return as_strided_scatter_default\n \"\"\")\n\n def test_tensor_list_composite(self):\n def f(x):\n # Test an op with TensorList input\n y = torch.block_diag(x, x)\n return y\n self.assert_functionalization(f, torch.ones(2, 2))\n logs = self.get_logs(f, torch.ones(2, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n block_diag_default = torch.ops.aten.block_diag.default([a_1, a_1]); a_1 = None\n return block_diag_default\n \"\"\")\n\n def test_cat(self):\n def f(x):\n out = torch.empty(0)\n torch.cat((x,), out=out)\n return out\n self.assert_functionalization(f, torch.ones(2, 2))\n logs = self.get_logs(f, torch.ones(2, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.SymInt([0], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n cat_default = torch.ops.aten.cat.default([a_1]); a_1 = None\n return cat_default\n \"\"\")\n\n def test_diagonal(self):\n def f(x):\n # test: view ops that take a subset of the original tensor (select/diagonal)\n tmp = torch.ones(2)\n y = x.diagonal()\n y.add_(tmp)\n z = x * x\n return z\n self.assert_functionalization(f, torch.ones(2, 2))\n logs = self.get_logs(f, torch.ones(2, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(a_1)\n add_tensor = torch.ops.aten.add.Tensor(diagonal_copy_default, fill_scalar); diagonal_copy_default = fill_scalar = None\n diagonal_scatter_default = torch.ops.aten.diagonal_scatter.default(a_1, add_tensor); a_1 = add_tensor = None\n mul_tensor = torch.ops.aten.mul.Tensor(diagonal_scatter_default, diagonal_scatter_default); diagonal_scatter_default = None\n return mul_tensor\n \"\"\")\n\n def test_diagonal_mutated_input(self):\n def f(x):\n # simple test: there are pending updates afterwards, which the test syncs manually\n tmp = torch.ones(2)\n y = x.diagonal()\n y.add_(tmp)\n return x\n x = torch.ones(2, 2)\n self.assert_functionalization(f, x)\n\n def test_split(self):\n def f(x):\n # test: view ops that return multiple tensors (split)\n tmp = torch.ones(2)\n y1, y2 = x.split(2)\n y3 = y2.diagonal()\n y3.add_(tmp)\n z = x * x\n return y3\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n split_copy_tensor = torch.ops.aten.split_copy.Tensor(a_1, 2)\n getitem = split_copy_tensor[0]\n getitem_1 = split_copy_tensor[1]; split_copy_tensor = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(getitem_1); getitem_1 = None\n add_tensor = torch.ops.aten.add.Tensor(diagonal_copy_default, fill_scalar); diagonal_copy_default = fill_scalar = None\n split_copy_tensor_1 = torch.ops.aten.split_copy.Tensor(a_1, 2)\n getitem_2 = split_copy_tensor_1[0]\n getitem_3 = split_copy_tensor_1[1]; split_copy_tensor_1 = None\n diagonal_scatter_default = torch.ops.aten.diagonal_scatter.default(getitem_3, add_tensor); getitem_3 = None\n slice_scatter_default = torch.ops.aten.slice_scatter.default(a_1, diagonal_scatter_default, 0, 2, 4); a_1 = diagonal_scatter_default = None\n mul_tensor = torch.ops.aten.mul.Tensor(slice_scatter_default, slice_scatter_default); slice_scatter_default = None\n return add_tensor\n \"\"\") # noqa: B950\n\n def test_view_inplace(self):\n def f(x):\n # test: view + inplace op (transpose_)\n tmp = torch.ones(4)\n x.transpose_(1, 0)\n y = x[0]\n y.add_(tmp)\n return x\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n transpose_copy_int = torch.ops.aten.transpose_copy.int(a_1, 1, 0)\n select_copy_int = torch.ops.aten.select_copy.int(transpose_copy_int, 0, 0); transpose_copy_int = None\n add_tensor = torch.ops.aten.add.Tensor(select_copy_int, fill_scalar); select_copy_int = fill_scalar = None\n transpose_copy_int_1 = torch.ops.aten.transpose_copy.int(a_1, 1, 0); a_1 = None\n select_scatter_default = torch.ops.aten.select_scatter.default(transpose_copy_int_1, add_tensor, 0, 0); transpose_copy_int_1 = add_tensor = None\n transpose_copy_int_2 = torch.ops.aten.transpose_copy.int(select_scatter_default, 1, 0); select_scatter_default = None\n transpose_copy_int_3 = torch.ops.aten.transpose_copy.int(transpose_copy_int_2, 1, 0); transpose_copy_int_2 = None\n return transpose_copy_int_3\n \"\"\") # noqa: B950\n\n def test_optional_tensor_list(self):\n def f(x):\n # test: an operator that takes in a List[Optional[Tensor]] argument\n # (index_put)\n y = x.view(8)\n indices = torch.arange(4)\n values = torch.arange(4, dtype=y.dtype)\n y.index_put_((indices,), values, accumulate=False)\n return y\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [8]); a_1 = None\n empty = torch.ops.aten.empty.memory_format([0], dtype = torch.int64, layout = torch.strided, device = device(type='cpu'), pin_memory = False)\n arange = torch.ops.aten.arange.start_step(0, 4, 1, dtype = torch.int64, layout = torch.strided, device = device(type='cpu'))\n empty_1 = torch.ops.aten.empty.memory_format([0], dtype = torch.float32, layout = torch.strided, device = device(type='cpu'), pin_memory = False)\n arange_1 = torch.ops.aten.arange.start_step(0, 4, 1, dtype = torch.float32, layout = torch.strided, device = device(type='cpu'))\n index_put_default = torch.ops.aten.index_put.default(view_copy_default, [arange], arange_1); view_copy_default = arange = arange_1 = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(index_put_default, [4, 2])\n return index_put_default\n \"\"\") # noqa: B950\n\n def test_scalars(self):\n def f(x):\n # test: the pass can handle scalar inputs properly\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n y.add_(1)\n z = 2 * y\n z.div_(1)\n return z\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [4, 2]); a_1 = None\n add_tensor = torch.ops.aten.add.Tensor(view_copy_default, 1); view_copy_default = None\n mul_tensor = torch.ops.aten.mul.Tensor(add_tensor, 2)\n div_tensor = torch.ops.aten.div.Tensor(mul_tensor, 1); mul_tensor = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(add_tensor, [4, 2]); add_tensor = None\n return div_tensor\n \"\"\")\n\n @skipIfTorchDynamo(\"Test does not work with TorchDynamo\")\n def test_metadata_change(self):\n def f(x):\n # ops like ge_() are allowed to change the dtype of the input.\n # functionalization should pick up on that.\n return x.ge_(0)\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n ge_scalar = torch.ops.aten.ge.Scalar(a_1, 0); a_1 = None\n _to_copy_default = torch.ops.aten._to_copy.default(ge_scalar, dtype = torch.float32, layout = torch.strided); ge_scalar = None\n _tensor_constant0 = self._tensor_constant0\n return _tensor_constant0\n \"\"\")\n\n def test_only_one_view(self):\n def f(x):\n # This tests that we don't have any unnecessary views in the trace.\n # If the input wasn't mutated, we don't need to regenerate it,\n # so there should be a total of 1 op in the output trace.\n return x.view(4, 2)\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n view_copy_default = torch.ops.aten.view_copy.default(a_1, [4, 2]); a_1 = None\n return view_copy_default\n \"\"\")\n\n def test_everything(self):\n def f(x):\n # test: everything\n tmp = torch.ones(2, 2)\n x2 = x + x\n y = x2.view(8)\n z0 = y.reshape(2, 4)\n z1 = z0.transpose(1, 0)\n z1.unsqueeze_(0)\n z1.squeeze_()\n z2, z3 = z1.split(2)\n z2.add_(tmp)\n z4 = z0[0] + z2.reshape(4)\n return z2\n self.assert_functionalization(f, torch.ones(4, 2))\n logs = self.get_logs(f, torch.ones(4, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n add_tensor = torch.ops.aten.add.Tensor(a_1, a_1); a_1 = None\n view_copy_default = torch.ops.aten.view_copy.default(add_tensor, [8])\n _reshape_alias_copy_default = torch.ops.aten._reshape_alias_copy.default(view_copy_default, [2, 4], [4, 1]); view_copy_default = None\n transpose_copy_int = torch.ops.aten.transpose_copy.int(_reshape_alias_copy_default, 1, 0)\n unsqueeze_copy_default = torch.ops.aten.unsqueeze_copy.default(transpose_copy_int, 0); transpose_copy_int = None\n squeeze_copy_default = torch.ops.aten.squeeze_copy.default(unsqueeze_copy_default); unsqueeze_copy_default = None\n split_copy_tensor = torch.ops.aten.split_copy.Tensor(squeeze_copy_default, 2); squeeze_copy_default = None\n getitem = split_copy_tensor[0]\n getitem_1 = split_copy_tensor[1]; split_copy_tensor = None\n add_tensor_1 = torch.ops.aten.add.Tensor(getitem, fill_scalar); getitem = fill_scalar = None\n select_copy_int = torch.ops.aten.select_copy.int(_reshape_alias_copy_default, 0, 0); _reshape_alias_copy_default = None\n clone_default = torch.ops.aten.clone.default(add_tensor_1, memory_format = torch.contiguous_format)\n _unsafe_view_default = torch.ops.aten._unsafe_view.default(clone_default, [4]); clone_default = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(add_tensor, [8]); add_tensor = None\n _reshape_alias_copy_default_1 = torch.ops.aten._reshape_alias_copy.default(view_copy_default_1, [2, 4], [4, 1]); view_copy_default_1 = None\n transpose_copy_int_1 = torch.ops.aten.transpose_copy.int(_reshape_alias_copy_default_1, 1, 0); _reshape_alias_copy_default_1 = None\n unsqueeze_copy_default_1 = torch.ops.aten.unsqueeze_copy.default(transpose_copy_int_1, 0); transpose_copy_int_1 = None\n squeeze_copy_default_1 = torch.ops.aten.squeeze_copy.default(unsqueeze_copy_default_1); unsqueeze_copy_default_1 = None\n slice_scatter_default = torch.ops.aten.slice_scatter.default(squeeze_copy_default_1, add_tensor_1, 0, 0, 2); squeeze_copy_default_1 = None\n unsqueeze_copy_default_2 = torch.ops.aten.unsqueeze_copy.default(slice_scatter_default, 0); slice_scatter_default = None\n squeeze_copy_dim = torch.ops.aten.squeeze_copy.dim(unsqueeze_copy_default_2, 0); unsqueeze_copy_default_2 = None\n transpose_copy_int_2 = torch.ops.aten.transpose_copy.int(squeeze_copy_dim, 1, 0); squeeze_copy_dim = None\n _reshape_alias_copy_default_2 = torch.ops.aten._reshape_alias_copy.default(transpose_copy_int_2, [8], [1]); transpose_copy_int_2 = None\n view_copy_default_2 = torch.ops.aten.view_copy.default(_reshape_alias_copy_default_2, [4, 2]); _reshape_alias_copy_default_2 = None\n view_copy_default_3 = torch.ops.aten.view_copy.default(view_copy_default_2, [8]); view_copy_default_2 = None\n _reshape_alias_copy_default_3 = torch.ops.aten._reshape_alias_copy.default(view_copy_default_3, [2, 4], [4, 1]); view_copy_default_3 = None\n select_copy_int_1 = torch.ops.aten.select_copy.int(_reshape_alias_copy_default_3, 0, 0); _reshape_alias_copy_default_3 = None\n add_tensor_2 = torch.ops.aten.add.Tensor(select_copy_int_1, _unsafe_view_default); select_copy_int_1 = _unsafe_view_default = None\n return add_tensor_1\n \"\"\") # noqa: B950\n\n def test_reapply_views_simple(self):\n def f(x):\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n y.add_(tmp)\n z = x * x\n return y\n self.assert_functionalization(f, torch.ones(4, 2), reapply_views=True)\n logs = self.get_logs(f, torch.ones(4, 2), reapply_views=True)\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([4, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n fill_scalar = torch.ops.aten.fill.Scalar(empty, 1.0); empty = None\n view_default = torch.ops.aten.view.default(a_1, [4, 2]); a_1 = None\n add_tensor = torch.ops.aten.add.Tensor(view_default, fill_scalar); view_default = fill_scalar = None\n view_default_1 = torch.ops.aten.view.default(add_tensor, [4, 2])\n mul_tensor = torch.ops.aten.mul.Tensor(view_default_1, view_default_1); view_default_1 = None\n return add_tensor\n \"\"\")\n\n def test_aliases_maintained_after_pass_when_reapplying_views(self):\n def f(x):\n tmp = torch.ones(4, 2)\n y = x.view(4, 2)\n z = x.view(4, 2)\n y.add_(tmp)\n return y, z\n\n input_functional = torch._to_functional_tensor(torch.ones(4, 2))\n torch._enable_functionalization(reapply_views=True)\n try:\n y, z = f(input_functional)\n torch._sync(y)\n torch._sync(z)\n finally:\n torch._disable_functionalization()\n\n # y and z are aliases inside of the function, and that aliasing relationship should be maintained.\n _y = torch._from_functional_tensor(y)\n _z = torch._from_functional_tensor(z)\n self.assertTrue(are_aliased(_y, _z))\n\n # copy_() gets its own test, because it is special cased in functionalization.\n # self.copy_(src) decomposes into src.to(self).expand_as(self).\n def test_copy_(self):\n def f(x):\n tmp = torch.zeros(2, 2)\n # NOTE: LoggingTensor isn't a mode, which means that the diagonal call\n # will not be logged. This is fine for testing.\n tmp_slice = tmp.diagonal()\n y = tmp_slice.copy_(x)\n z = y.add_(x)\n return z\n\n # Test 1: copy_() with same dtype and shape\n # to() is a composite op that noops when the dtype/shape match, so nothing gets logged.\n # self.assert_functionalization(f, torch.ones(2))\n logs = self.get_logs(f, torch.ones(2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n zero_default = torch.ops.aten.zero.default(empty); empty = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(zero_default)\n diagonal_copy_default_1 = torch.ops.aten.diagonal_copy.default(zero_default); zero_default = None\n copy_default = torch.ops.aten.copy.default(diagonal_copy_default_1, a_1); diagonal_copy_default_1 = None\n add_tensor = torch.ops.aten.add.Tensor(copy_default, a_1); copy_default = a_1 = None\n return add_tensor\n \"\"\")\n\n # Test 2: copy_() with same dtype, different shape\n self.assert_functionalization(f, torch.ones(1))\n logs = self.get_logs(f, torch.ones(1))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n zero_default = torch.ops.aten.zero.default(empty); empty = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(zero_default)\n diagonal_copy_default_1 = torch.ops.aten.diagonal_copy.default(zero_default); zero_default = None\n copy_default = torch.ops.aten.copy.default(diagonal_copy_default_1, a_1); diagonal_copy_default_1 = None\n add_tensor = torch.ops.aten.add.Tensor(copy_default, a_1); copy_default = a_1 = None\n return add_tensor\n \"\"\")\n\n # Test 3: copy_() with different dtype, same shape\n self.assert_functionalization(f, torch.ones(2, dtype=torch.long))\n logs = self.get_logs(f, torch.ones(2, dtype=torch.long))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n zero_default = torch.ops.aten.zero.default(empty); empty = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(zero_default)\n diagonal_copy_default_1 = torch.ops.aten.diagonal_copy.default(zero_default); zero_default = None\n copy_default = torch.ops.aten.copy.default(diagonal_copy_default_1, a_1); diagonal_copy_default_1 = None\n add_tensor = torch.ops.aten.add.Tensor(copy_default, a_1); copy_default = a_1 = None\n return add_tensor\n \"\"\")\n\n # Test 4: copy_() with different dtype, different shape\n self.assert_functionalization(f, torch.ones(1, dtype=torch.long))\n logs = self.get_logs(f, torch.ones(1, dtype=torch.long))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n empty = torch.ops.aten.empty.memory_format([2, 2], dtype = torch.float32, device = device(type='cpu'), pin_memory = False)\n zero_default = torch.ops.aten.zero.default(empty); empty = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(zero_default)\n diagonal_copy_default_1 = torch.ops.aten.diagonal_copy.default(zero_default); zero_default = None\n copy_default = torch.ops.aten.copy.default(diagonal_copy_default_1, a_1); diagonal_copy_default_1 = None\n add_tensor = torch.ops.aten.add.Tensor(copy_default, a_1); copy_default = a_1 = None\n return add_tensor\n \"\"\")\n\n def test_expand_symint(self):\n # Once some existing SymInt bugs are ironed out, we should update\n # this test to plumb FakeSymbolicTensors through it\n def f(x):\n return x.expand(x.size(0), x.size(1))\n\n self.assert_functionalization(f, torch.ones(2, 2))\n logs = self.get_logs(f, torch.ones(2, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n expand_copy_sym_int = torch.ops.aten.expand_copy.SymInt(a_1, [2, 2]); a_1 = None\n return expand_copy_sym_int\n \"\"\")\n\n def test_fill_(self):\n def f(x):\n y = x + x\n z = y.diagonal()\n z.fill_(0)\n return y\n\n self.assert_functionalization(f, torch.ones(2, 2))\n logs = self.get_logs(f, torch.ones(2, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n add_tensor = torch.ops.aten.add.Tensor(a_1, a_1); a_1 = None\n diagonal_copy_default = torch.ops.aten.diagonal_copy.default(add_tensor)\n fill_scalar = torch.ops.aten.fill.Scalar(diagonal_copy_default, 0); diagonal_copy_default = None\n diagonal_scatter_default = torch.ops.aten.diagonal_scatter.default(add_tensor, fill_scalar); add_tensor = fill_scalar = None\n return diagonal_scatter_default\n \"\"\")\n\n def test_resize_smaller(self):\n def f(w):\n # Resizing to a smaller size doesn't affect storage\n x = w + 1\n y = x.view(4, 4)\n y.resize_(3, 3)\n y2 = y.view(-1)\n y2.add_(1)\n z = y + 1\n return z\n\n self.assert_functionalization(f, torch.ones(8, 2))\n logs = self.get_logs(f, torch.ones(8, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n add_tensor = torch.ops.aten.add.Tensor(a_1, 1); a_1 = None\n view_copy_default = torch.ops.aten.view_copy.default(add_tensor, [4, 4])\n resize_default = torch.ops.aten.resize.default(view_copy_default, [3, 3])\n as_strided_copy_default = torch.ops.aten.as_strided_copy.default(view_copy_default, [3, 3], [3, 1]); view_copy_default = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(as_strided_copy_default, [-1]); as_strided_copy_default = None\n add_tensor_1 = torch.ops.aten.add.Tensor(view_copy_default_1, 1); view_copy_default_1 = None\n view_copy_default_2 = torch.ops.aten.view_copy.default(add_tensor, [4, 4]); add_tensor = None\n as_strided_copy_default_1 = torch.ops.aten.as_strided_copy.default(view_copy_default_2, [3, 3], [3, 1])\n view_copy_default_3 = torch.ops.aten.view_copy.default(add_tensor_1, [3, 3]); add_tensor_1 = None\n as_strided_scatter_default = torch.ops.aten.as_strided_scatter.default(view_copy_default_2, view_copy_default_3, [3, 3], [3, 1]); view_copy_default_2 = view_copy_default_3 = None\n view_copy_default_4 = torch.ops.aten.view_copy.default(as_strided_scatter_default, [8, 2]); as_strided_scatter_default = None\n view_copy_default_5 = torch.ops.aten.view_copy.default(view_copy_default_4, [4, 4]); view_copy_default_4 = None\n as_strided_copy_default_2 = torch.ops.aten.as_strided_copy.default(view_copy_default_5, [3, 3], [3, 1]); view_copy_default_5 = None\n add_tensor_2 = torch.ops.aten.add.Tensor(as_strided_copy_default_2, 1); as_strided_copy_default_2 = None\n return add_tensor_2\n \"\"\") # noqa: B950\n\n def test_resize_larger_valid(self):\n def f(x):\n y = x + 1\n # resizing a tensor to a larger size is only currently allowed\n # if the tensor-to-resize is not a view / has no outstanding views.\n # See Note [resize_() in functionalization pass]\n y.resize_(5, 5)\n y2 = y.view(25)\n # Do a mutation to ensure that aliases of the output of resize_()\n # propagate mutations correctly.\n # I'm using fill_ specifically because I want to guarantee that\n # none of the output has uninitialized memory at the end\n # (since these tests compare the data output against a reference impl)\n y2.fill_(1)\n out = y + 1\n return y, out\n\n self.assert_functionalization(f, torch.ones(8, 2))\n logs = self.get_logs(f, torch.ones(8, 2))\n self.assertExpectedInline(logs, \"\"\"\\\n\n\n\ndef forward(self, a_1):\n add_tensor = torch.ops.aten.add.Tensor(a_1, 1); a_1 = None\n resize_default = torch.ops.aten.resize.default(add_tensor, [5, 5]); add_tensor = None\n view_copy_default = torch.ops.aten.view_copy.default(resize_default, [25]); resize_default = None\n fill_scalar = torch.ops.aten.fill.Scalar(view_copy_default, 1); view_copy_default = None\n view_copy_default_1 = torch.ops.aten.view_copy.default(fill_scalar, [5, 5]); fill_scalar = None\n add_tensor_1 = torch.ops.aten.add.Tensor(view_copy_default_1, 1)\n return (view_copy_default_1, add_tensor_1)\n \"\"\")\n\n def test_resize_larger_invalid(self):\n def f(x):\n y = x + 1\n z = y.view(4, 4)\n # resizing a tensor to a larger size is only currently allowed\n # if the tensor-to-resize is not a view / has no outstanding views.\n # See Note [resize_() in functionalization pass]\n # This should fail\n z.resize_(5, 5)\n z2 = z.view(25)\n z2.fill_(1)\n out = z + 1\n return y, out\n\n with self.assertRaisesRegex(\n RuntimeError,\n r'Attempted to resize a view tensor to a larger size. This is not allowed in the functionalization pass'):\n self.assert_functionalization(f, torch.ones(8, 2))\n\n def test_nested_functions_propagate_updates(self):\n def g(x):\n # Create a view of x\n y = x[0]\n y.add_(1)\n # The view, y, gets deallocated at the end of this function\n\n def f(x):\n # Calling g(x) should mutate x\n g(x)\n # We expect x to be synced here, even though the alias created in g() has been deallocated!\n y = x + x\n return y\n\n self.assert_functionalization(f, torch.ones(2, 2))\n\n def test_mixed_wrappers_valid(self):\n def f(x, y):\n z = x + y\n z.add_(1)\n return z\n\n x1_not_functional = LoggingTensor(torch.ones(4))\n x2_functional = torch._to_functional_tensor(LoggingTensor(torch.ones(4)))\n\n with capture_logs() as logs:\n y = f(x1_not_functional, x2_functional)\n\n # Make sure that functionalization ran the \"+\" kernel\n # with a functional + non-functional tensor, and wrapped the output appropriately.\n self.assertExpectedInline('\\n'.join(logs), \"\"\"\\\n$2 = torch._ops.aten.add.Tensor($0, $1)\n$3 = torch._ops.aten.add.Tensor($2, 1)\"\"\")\n\n def test_mixed_wrappers_invalid(self):\n x1_not_functional = torch.ones(4)\n x2_functional = torch._to_functional_tensor(torch.ones(4))\n\n # When dealing with mixed functional + non functional tensors,\n # normal_tensor.add_(functional_tensor) is not valid\n # because normal_tensor would need to be \"promoted\" to a functional tensor.\n with self.assertRaises(RuntimeError):\n x1_not_functional.add_(x2_functional)\n\nif __name__ == '__main__':\n run_tests()\n", "sub_path": "test/test_functionalization.py", "file_name": "test_functionalization.py", "file_ext": "py", "file_size_in_byte": 37760, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "torch.testing._internal.logging_tensor.LoggingTensorReentrant", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.Tensor._make_wrapper_subclass", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 26, "usage_type": "attribute"}, {"api_name": "torch._C", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.ops", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.ops", "line_number": 51, "usage_type": "attribute"}, {"api_name": "torch.utils._pytree.tree_map", "line_number": 54, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.testing._internal.common_utils.TestCase", "line_number": 63, "usage_type": "name"}, {"api_name": "torch._to_functional_tensor", "line_number": 68, "usage_type": "call"}, {"api_name": "torch._enable_functionalization", "line_number": 69, "usage_type": "call"}, {"api_name": "torch._disable_functionalization", "line_number": 73, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.utils._pytree.tree_map", "line_number": 75, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 75, "usage_type": "attribute"}, {"api_name": "torch.utils._pytree.tree_map", "line_number": 76, "usage_type": "call"}, {"api_name": "torch._from_functional_tensor", "line_number": 76, "usage_type": "attribute"}, {"api_name": "torch.fx.experimental.proxy_tensor.make_fx", "line_number": 82, "usage_type": "call"}, {"api_name": "torch._to_functional_tensor", "line_number": 88, "usage_type": "call"}, {"api_name": "torch._enable_functionalization", "line_number": 93, "usage_type": "call"}, {"api_name": "torch._disable_functionalization", "line_number": 97, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 100, "usage_type": "call"}, {"api_name": "torch._from_functional_tensor", "line_number": 101, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 111, "usage_type": "call"}, {"api_name": "torch._from_functional_tensor", "line_number": 112, "usage_type": "call"}, {"api_name": "torch._to_functional_tensor", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.testing._internal.logging_tensor.LoggingTensor", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.empty", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.add", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 165, "usage_type": "call"}, {"api_name": "torch.empty", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.empty", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.aminmax", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 188, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 188, "usage_type": "attribute"}, {"api_name": "torch.arange", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 189, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 209, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 220, "usage_type": "call"}, {"api_name": "torch._fused_moving_avg_obs_fq_helper", "line_number": 238, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 240, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 261, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 262, "usage_type": "call"}, {"api_name": "torch.block_diag", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 279, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 280, "usage_type": "call"}, {"api_name": "torch.empty", "line_number": 292, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 293, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 295, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 296, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 315, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 316, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 334, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 338, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 344, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 350, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 351, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 376, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 381, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 382, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 405, "usage_type": "call"}, {"api_name": "torch.arange", "line_number": 406, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 410, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 429, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 435, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 436, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 458, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 459, "usage_type": "call"}, {"api_name": "torch.testing._internal.common_utils.skipIfTorchDynamo", "line_number": 452, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 477, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 490, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 501, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 502, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 543, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 548, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 549, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 566, "usage_type": "call"}, {"api_name": "torch._to_functional_tensor", "line_number": 572, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 572, "usage_type": "call"}, {"api_name": "torch._enable_functionalization", "line_number": 573, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 576, "usage_type": "call"}, {"api_name": "torch._sync", "line_number": 577, "usage_type": "call"}, {"api_name": "torch._disable_functionalization", "line_number": 579, "usage_type": "call"}, {"api_name": "torch._from_functional_tensor", "line_number": 582, "usage_type": "call"}, {"api_name": "torch._from_functional_tensor", "line_number": 583, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 590, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 601, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 617, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 618, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 634, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 634, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 635, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 635, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 651, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 651, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 652, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 652, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 673, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 674, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 691, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 692, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 716, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 717, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 757, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 758, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 790, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 806, "usage_type": "call"}, {"api_name": "torch.testing._internal.logging_tensor.LoggingTensor", "line_number": 814, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 814, "usage_type": "call"}, {"api_name": "torch._to_functional_tensor", "line_number": 815, "usage_type": "call"}, {"api_name": "torch.testing._internal.logging_tensor.LoggingTensor", "line_number": 815, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 815, "usage_type": "call"}, {"api_name": "torch.testing._internal.logging_tensor.capture_logs", "line_number": 817, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 827, "usage_type": "call"}, {"api_name": "torch._to_functional_tensor", "line_number": 828, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 828, "usage_type": "call"}, {"api_name": "unittest.skipIf", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.testing._internal.common_utils.TEST_WITH_TORCHDYNAMO", "line_number": 62, "usage_type": "argument"}, {"api_name": "torch.testing._internal.common_utils.run_tests", "line_number": 837, "usage_type": "call"}]} +{"seq_id": "412157048", "text": "import datetime\nfrom datetime import timedelta\n\nclass ProxyModel(object):\n def __init__(self,proxy_dict):\n proxy = proxy_dict['data'][0]\n self.proxy_url = \"https://\" + proxy['ip'] + \":\" + str(proxy['port'])\n expire_time_str = proxy['expire_time']\n # \"expire_time\":\"2019-05-11 22:22:46\"}\n self.expire_time = datetime.datetime.strptime(expire_time_str,'%Y-%m-%d %H:%M:%S')\n self.is_blacked = False\n\n @property\n def is_expiring(self):\n now = datetime.datetime.now()\n if (self.expire_time - now) <= timedelta(seconds=5):\n return True\n else:\n return False\n", "sub_path": "爬虫课件代码/06Scrapy框架/讲课代码/06猎聘网爬虫/zhaopin/zhaopin/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 645, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "488520733", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright 2011 Sybren A. Stüvel \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# https://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\"\"\"Python compatibility wrappers.\"\"\"\n\nfrom __future__ import absolute_import\n\nimport itertools\nimport sys\nfrom struct import pack\n\nMAX_INT = sys.maxsize\nMAX_INT64 = (1 << 63) - 1\nMAX_INT32 = (1 << 31) - 1\nMAX_INT16 = (1 << 15) - 1\n\nPY2 = sys.version_info[0] == 2\n\n# Determine the word size of the processor.\nif MAX_INT == MAX_INT64:\n # 64-bit processor.\n MACHINE_WORD_SIZE = 64\nelif MAX_INT == MAX_INT32:\n # 32-bit processor.\n MACHINE_WORD_SIZE = 32\nelse:\n # Else we just assume 64-bit processor keeping up with modern times.\n MACHINE_WORD_SIZE = 64\n\nif PY2:\n integer_types = (int, long)\n range = xrange\n zip = itertools.izip\nelse:\n integer_types = (int, )\n range = range\n zip = zip\n\n\ndef write_to_stdout(data):\n \"\"\"Writes bytes to stdout\n\n :type data: bytes\n \"\"\"\n if PY2:\n sys.stdout.write(data)\n else:\n # On Py3 we must use the buffer interface to write bytes.\n sys.stdout.buffer.write(data)\n\n\ndef is_bytes(obj):\n \"\"\"\n Determines whether the given value is a byte string.\n\n :param obj:\n The value to test.\n :returns:\n ``True`` if ``value`` is a byte string; ``False`` otherwise.\n \"\"\"\n return isinstance(obj, bytes)\n\n\ndef is_integer(obj):\n \"\"\"\n Determines whether the given value is an integer.\n\n :param obj:\n The value to test.\n :returns:\n ``True`` if ``value`` is an integer; ``False`` otherwise.\n \"\"\"\n return isinstance(obj, integer_types)\n\n\ndef byte(num):\n \"\"\"\n Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)\n representation.\n\n Use it as a replacement for ``chr`` where you are expecting a byte\n because this will work on all current versions of Python::\n\n :param num:\n An unsigned integer between 0 and 255 (both inclusive).\n :returns:\n A single byte.\n \"\"\"\n return pack(\"B\", num)\n\n\ndef xor_bytes(b1, b2):\n \"\"\"\n Returns the bitwise XOR result between two bytes objects, b1 ^ b2.\n\n Bitwise XOR operation is commutative, so order of parameters doesn't\n generate different results. If parameters have different length, extra\n length of the largest one is ignored.\n\n :param b1:\n First bytes object.\n :param b2:\n Second bytes object.\n :returns:\n Bytes object, result of XOR operation.\n \"\"\"\n if PY2:\n return ''.join(byte(ord(x) ^ ord(y)) for x, y in zip(b1, b2))\n\n return bytes(x ^ y for x, y in zip(b1, b2))\n\n\ndef get_word_alignment(num, force_arch=64,\n _machine_word_size=MACHINE_WORD_SIZE):\n \"\"\"\n Returns alignment details for the given number based on the platform\n Python is running on.\n\n :param num:\n Unsigned integral number.\n :param force_arch:\n If you don't want to use 64-bit unsigned chunks, set this to\n anything other than 64. 32-bit chunks will be preferred then.\n Default 64 will be used when on a 64-bit machine.\n :param _machine_word_size:\n (Internal) The machine word size used for alignment.\n :returns:\n 4-tuple::\n\n (word_bits, word_bytes,\n max_uint, packing_format_type)\n \"\"\"\n max_uint64 = 0xffffffffffffffff\n max_uint32 = 0xffffffff\n max_uint16 = 0xffff\n max_uint8 = 0xff\n\n if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32:\n # 64-bit unsigned integer.\n return 64, 8, max_uint64, \"Q\"\n elif num > max_uint16:\n # 32-bit unsigned integer\n return 32, 4, max_uint32, \"L\"\n elif num > max_uint8:\n # 16-bit unsigned integer.\n return 16, 2, max_uint16, \"H\"\n else:\n # 8-bit unsigned integer.\n return 8, 1, max_uint8, \"B\"\n", "sub_path": "courses/machine_learning/deepdive2/structured/labs/serving/application/lib/rsa/_compat.py", "file_name": "_compat.py", "file_ext": "py", "file_size_in_byte": 4345, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.maxsize", "line_number": 25, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 30, "usage_type": "attribute"}, {"api_name": "itertools.izip", "line_number": 46, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 59, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 59, "usage_type": "attribute"}, {"api_name": "sys.stdout.buffer.write", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 62, "usage_type": "attribute"}, {"api_name": "struct.pack", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "517730451", "text": "import requests\nfrom requests.auth import HTTPBasicAuth\n\nimport operator\nimport os,sys,inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0,parentdir) \n\nfrom connio.rest import Client\nfrom connio.base.exceptions import ConnioRestException\n\nfrom six import u\nimport json\nfrom threading import Timer\n\ndef _teal(words):\n return u(\"\\033[36m\\033[49m%s\\033[0m\") % words\ndef _blue(words):\n return u(\"\\033[34m\\033[49m%s\\033[0m\") % words\n\nHOST = \"https://api.connio.cloud\"\n\napikeyID = ''\nsecret = ''\n\ndef preaggregate():\n try:\n client = Client(username=apikeyID, \n password=secret)\n\n sortedDevList = sorted(client.account.devices.list(), key = operator.itemgetter('date_created'))\n for dev in sortedDevList:\n print(_blue('Preaggregating device {}'.format(dev.name)))\n url = \"{0}/v3/data/devices/{1}/methods/preaggregate\".format(HOST, dev.name)\n\n payload = { 'value': '' }\n res = requests.post(url, auth=HTTPBasicAuth(client.username, client.password), json=payload, verify=True)\n\n # For successful API call, response code will be 200 (OK)\n # if(not res.ok):\n # res.raise_for_status()\n\n except ConnioRestException as ce:\n print(ce)\n\n print(_teal('Preaggregation session is complete'))\n\n#\n#\n#\ndef timeout():\n print(\"Preaggregating\")\n preaggregate()\n\nif __name__ == '__main__':\n print(_teal('Preaggregation started...'))\n\n # Default Dalgakiran\n apikeyID = os.environ.get('CONNIO_PREAGGREGATE_ACCOUNT_KEYID', '_key_500600814475760930')\n secret = os.environ.get('CONNIO_PREAGGREGATE_ACCOUNT_KEYSECRET', '0b51ab06dc554165bda3db495eb00737')\n\n preaggregate()\n\n # duration is in seconds\n mytimer = Timer(3600, timeout)\n mytimer.start()", "sub_path": "examples/dk-preagg.py", "file_name": "dk-preagg.py", "file_ext": "py", "file_size_in_byte": 1895, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 6, "usage_type": "call"}, {"api_name": "inspect.getfile", "line_number": 6, "usage_type": "call"}, {"api_name": "inspect.currentframe", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "six.u", "line_number": 18, "usage_type": "call"}, {"api_name": "six.u", "line_number": 20, "usage_type": "call"}, {"api_name": "connio.rest.Client", "line_number": 29, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 32, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 38, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 38, "usage_type": "call"}, {"api_name": "connio.base.exceptions.ConnioRestException", "line_number": 44, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 60, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 61, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 61, "usage_type": "attribute"}, {"api_name": "threading.Timer", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "508114787", "text": "from oauthlib.oauth2 import BackendApplicationClient \nfrom oauthlib.oauth2.rfc6749.errors import (InsecureTransportError,\n TokenExpiredError)\nfrom requests_oauthlib import OAuth2Session\nfrom requests.auth import HTTPBasicAuth\nfrom pathlib import Path\nfrom datetime import datetime\nimport json\nimport sys\nimport logging\n\nclass FitbitApi:\n def __init__(self, account_email, client_id, client_secret):\n if \"@\" not in account_email:\n raise ValueError(account_email + ' does not look like an email')\n self.client_id = client_id\n self.client_secret = client_secret\n\n self.scope = [\"activity\", \"heartrate\", \"location\", \"nutrition\", \"profile\", \"settings\", \"sleep\", \"social\", \"weight\"]\n self.redirect_uri = 'https://127.0.0.1:8080/'\n\n self.token_url = 'https://api.fitbit.com/oauth2/token'\n self.auth_url = 'https://www.fitbit.com/oauth2/authorize'\n self.url = 'https://api.fitbit.com/1'\n\n # For some dumb reason, Fitbit's api requires you use basic auth headers when fetching a token.\n self.auth = HTTPBasicAuth(self.client_id, self.client_secret)\n \n self.token_file = Path(\"tokens/%s.json\" % account_email)\n if self.token_file.is_file():\n logging.debug(\"Loading existing token\")\n self.load_token()\n self.load_api()\n else:\n self.api = OAuth2Session(client_id=self.client_id, redirect_uri=self.redirect_uri, scope=self.scope)\n authorization_url, state = self.api.authorization_url(self.auth_url)\n\n print('Please go to %s and authorize access.' % authorization_url)\n import webbrowser\n chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --incognito'\n webbrowser.get(chrome_path).open_new(authorization_url)\n authorization_response = input('Enter the full callback URL: ')\n self.token = self.api.fetch_token(token_url=self.token_url, auth=self.auth, authorization_response=authorization_response)\n self.dump_token()\n\n def load_api(self):\n self.api = OAuth2Session(client_id=self.client_id, token=self.token, scope=self.scope)\n\n def load_token(self):\n with open(self.token_file) as json_file: \n self.token = json.load(json_file)\n\n def dump_token(self):\n with open(self.token_file, 'w') as outfile: \n json.dump(self.token, outfile)\n\n def access_token(self):\n return self.token['access_token']\n\n def refresh_token(self):\n return self.token['refresh_token']\n\n def do_refresh_token(self):\n self.token = self.api.refresh_token(self.token_url, refresh_token=self.refresh_token(), auth=self.auth)\n self.dump_token()\n\n def date_string(self, date):\n if isinstance(date, datetime):\n return date.date().isoformat()\n elif isinstance(date, date):\n return date.isoformat()\n else:\n return date\n\n # A list of all the urls can be found in api.py of the python-fitbit module\n\n def sleep_goal(self):\n return self.get('/user/-/sleep/goal.json')\n\n # def sleep(self, date):\n # return self.get(f'/user/-/sleep/date/{self.date_string(date)}.json')\n # def sleep(self, date, detail_level):\n # return self.intraday_time_series(resouce='sleep', date=date, detail_level=detail_level)\n # return self.get(f'/user/-/sleep/date/{self.date_string(date)}/1d/{detail_level}.json')\n def sleep(self, date):\n return self.get(f'/user/-/sleep/date/{self.date_string(date)}.json')\n\n def day_activities(self, date):\n return self.intraday_time_series('activities', date)\n # return self.get(f'/user/-/activities/date/{self.date_string(date)}.json')\n\n def activities(self, date):\n return self.get(f'/user/-/activities/list.json?beforeDate={self.date_string(date)}&offset=0&limit=20&sort=desc')\n\n def steps(self, date):\n return self.intraday_time_series('activities/steps', date)\n\n def hrv(self, date):\n return self.intraday_time_series('activities/heart', date)\n # return self.get(f'/user/-/activities/heart/date/{self.date_string(date)}/1d/1sec.json')\n\n def intraday_time_series(self, resource, date, detail_level='1min', start_time=None, end_time=None):\n url = \"/user/-/{resource}/date/{date}/1d/{detail_level}\".format(\n resource=resource,\n date=self.date_string(date),\n detail_level=detail_level\n )\n # Check that the time range is valid\n time_test = lambda t: not (t is None or isinstance(t, str) and not t)\n time_map = list(map(time_test, [start_time, end_time]))\n if not all(time_map) and any(time_map):\n raise TypeError('You must provide both the end and start time or neither')\n\n if all(time_map):\n url = url + '/time'\n for time in [start_time, end_time]:\n time_str = time\n if not isinstance(time_str, str):\n time_str = time.strftime('%H:%M')\n url = url + ('/%s' % (time_str))\n\n url = url + '.json'\n\n return self.get(url)\n\n def get(self, path):\n # It would sure be nice to use requests-oauthlib's automatic token refresh callbacks!\n # But that doesn't work because Fitbit requires auth. So we need to catch TokenExpiredError\n # and bounce if needed\n try:\n r = self.api.get(self.url + path)\n if r.ok:\n return r.json()\n else:\n logging.error(f\"Fitbit API error fetching {self.url + path}: {repr(r.text)}\")\n except TokenExpiredError as e:\n logging.error(\"Unexpected error:\", sys.exc_info()[0])\n self.do_refresh_token()\n self.load_api()\n return self.api.get(self.url + path).json()\n\n\n", "sub_path": "fitbit_api.py", "file_name": "fitbit_api.py", "file_ext": "py", "file_size_in_byte": 5931, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "requests.auth.HTTPBasicAuth", "line_number": 27, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 31, "usage_type": "call"}, {"api_name": "requests_oauthlib.OAuth2Session", "line_number": 35, "usage_type": "call"}, {"api_name": "webbrowser.get", "line_number": 41, "usage_type": "call"}, {"api_name": "requests_oauthlib.OAuth2Session", "line_number": 47, "usage_type": "call"}, {"api_name": "json.load", "line_number": 51, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 68, "usage_type": "argument"}, {"api_name": "logging.error", "line_number": 135, "usage_type": "call"}, {"api_name": "oauthlib.oauth2.rfc6749.errors.TokenExpiredError", "line_number": 136, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 137, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 137, "usage_type": "call"}]} +{"seq_id": "17371151", "text": "from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom sqlalchemy.pool import NullPool\nimport os\n\n'''engine = create_engine('sqlite:///test.sqlite3')\nSession = sessionmaker(bind=engine)\n\nBase.metadata.create_all(engine)'''\n\nBase = declarative_base()\n\n\nclass Database(object):\n def __init__(self, connection_string=os.environ['DATABASE_URL']):\n try:\n #self.engine = create_engine(connection_string, poolclass=NullPool)\n Base.metadata.create_all(self.engine)\n self.Session = sessionmaker(bind=self.engine)\n self.session = self.Session()\n\n except:\n connection_string = os.environ['TEST_DATABASE_URL']\n self.engine = create_engine(connection_string, poolclass=NullPool,\n connect_args={'check_same_thread': False})\n Base.metadata.create_all(self.engine)\n self.Session = sessionmaker(bind=self.engine)\n self.session = self.Session()\n", "sub_path": "src/database.py", "file_name": "database.py", "file_ext": "py", "file_size_in_byte": 1081, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 12, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 20, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 24, "usage_type": "attribute"}, {"api_name": "sqlalchemy.create_engine", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.pool.NullPool", "line_number": 25, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "582126694", "text": "from typing import Awaitable, Callable, ParamSpec, TypeAlias, TypeVar\n\nfrom wordlette.labels import LabelCollection\nfrom wordlette.utilities.bevy_auto_inject import BevyAutoInject\nfrom wordlette.utilities.class_instance_dispatch import ClassOrInstanceDispatch\nfrom .listener import EventListener\n\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\nListener: TypeAlias = Callable[P, Awaitable[R]]\n\n\nclass Eventable(BevyAutoInject):\n __event_listeners__: set[EventListener]\n _listeners: LabelCollection[Listener]\n\n def __init__(self):\n self._register_listeners()\n\n async def dispatch(self, *payload_args, **labels):\n for listener in self._listeners.get(**labels):\n await listener(*payload_args)\n\n @ClassOrInstanceDispatch\n @classmethod\n def on(cls, **labels) -> Callable[[Listener], EventListener]:\n def register(func: Listener) -> EventListener:\n return EventListener(cls, func, **labels)\n\n return register\n\n @on.add_method\n def on(self, listener: Listener, **labels):\n self._listeners.add(listener, **labels)\n\n def _register_listeners(self):\n self._listeners = LabelCollection[Listener]()\n for listener in getattr(self, \"__event_listeners__\", set()):\n listener.register(self.bevy, self)\n", "sub_path": "wordlette/events/eventable.py", "file_name": "eventable.py", "file_ext": "py", "file_size_in_byte": 1303, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "typing.TypeVar", "line_number": 9, "usage_type": "call"}, {"api_name": "typing.ParamSpec", "line_number": 10, "usage_type": "call"}, {"api_name": "typing.TypeVar", "line_number": 11, "usage_type": "call"}, {"api_name": "typing.TypeAlias", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Awaitable", "line_number": 13, "usage_type": "name"}, {"api_name": "wordlette.utilities.bevy_auto_inject.BevyAutoInject", "line_number": 16, "usage_type": "name"}, {"api_name": "listener.EventListener", "line_number": 17, "usage_type": "name"}, {"api_name": "wordlette.labels.LabelCollection", "line_number": 18, "usage_type": "name"}, {"api_name": "listener.EventListener", "line_number": 31, "usage_type": "call"}, {"api_name": "listener.EventListener", "line_number": 30, "usage_type": "name"}, {"api_name": "wordlette.utilities.class_instance_dispatch.ClassOrInstanceDispatch", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 29, "usage_type": "name"}, {"api_name": "listener.EventListener", "line_number": 29, "usage_type": "name"}, {"api_name": "wordlette.labels.LabelCollection", "line_number": 40, "usage_type": "name"}, {"api_name": "listener.register", "line_number": 42, "usage_type": "call"}]} +{"seq_id": "590024173", "text": "#! /usr/bin/env python\n\nimport json\nimport sys\n\ngeoOuter = {\n 'type': 'FeatureCollection',\n 'features': []\n}\n\ndef makeFeature(trip, flight):\n return {\n 'type': 'Feature',\n 'properties': {\n 'trip': trip['name'],\n 'carrier': flight['carrier'],\n 'src': flight['src']['name'],\n 'dst': flight['dst']['name']\n },\n 'geometry': {\n 'type': 'LineString',\n 'coordinates': [\n flight['src']['coords'],\n flight['dst']['coords']\n ]\n }\n }\n\nwith open(sys.argv[1], 'r') as tripfile:\n trips = json.load(tripfile)\n\n\nfor trip in trips['trips']:\n for flight in trip['flights']:\n geoOuter['features'].append(makeFeature(trip, flight))\n\nprint(json.dumps(geoOuter, indent=4))\n", "sub_path": "convertgeo.py", "file_name": "convertgeo.py", "file_ext": "py", "file_size_in_byte": 818, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 29, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "221757245", "text": "\nfrom datetime import date\nimport datetime\nimport math\n\n# last_period = date(2022,10,5)\n# cycle = 30\n\n\ndef Prediction(last_period, cycle):\n cycle = datetime.timedelta(days=cycle)\n due = last_period + cycle\n return due\n\ndef All_Predictions(last_period, cycle):\n today = date.today()\n gap = today - last_period\n print(gap)\n gapp = str(gap).split(' ')[0]\n gapp = int(gapp)\n print(gapp)\n gap = math.floor(gapp/30)\n print(gap)\n if gap<1:\n if gapp= treshold:\n return 1\n return 0\n\n# def update_cell_sql(cell, new_value):\n# cell = new_value\n\n\ndef process_dict_from_proba(dict_data, update_db_proba=True, data_api=None):\n \"\"\"\n Обработчик входного словаря. Расчет вероятности\n \"\"\"\n \n comment = None\n #Проверка правильности формирования запроса\n if dict_data == {}:\n comment = \"No found required keys: 'question', 'answer'.\"\n elif \"question\" not in dict_data.keys():\n comment = \"No found required key: 'question.\"\n elif \"answer\" not in dict_data.keys():\n comment = \"No found required key: 'answer'.\"\n \n dict_data[\"log\"] = {\"comment\":comment}\n if comment != None:\n return\n\n #Проверка api ключа\n if data_api is None:\n data_api = db.session.query(ApiInformation).get(dict_data[\"key_api\"])\n if data_api is None:\n dict_data[\"log\"][\"comment\"] = \"No correct api_key, or unauthorized user\"\n return\n elif data_api.counts_proba_left == 0:\n dict_data[\"log\"][\"comment\"] = \"No available query probability\"\n return\n\n question = dict_data[\"question\"]\n answer = dict_data[\"answer\"]\n if \"treshold\" not in dict_data.keys():\n dict_data[\"treshold\"] = 0.5\n treshold = dict_data[\"treshold\"]\n\n dict_data[\"log\"][\"comment\"] = \"OK\"\n proba = []\n class_ = []\n #Определение максимального числа строк в запросе\n #question список, answer список \n if isinstance(question,list) and isinstance(answer,list):\n max_len = len(question)\n type_ = 1\n #question строка, answer список\n elif not isinstance(question,list) and isinstance(answer,list):\n max_len = len(answer)\n type_ = 2\n #question список, answer строка\n elif isinstance(question,list) and not isinstance(answer,list):\n max_len = len(question)\n type_ = 3\n #question строка, answer строка\n else:\n max_len = 1\n type_ = 4\n \n if update_db_proba:\n len_seq = min(max_len, data_api.counts_proba_left)\n else:\n len_seq = max_len\n \n if type_ == 1:\n for i, q in enumerate(question[:len_seq]):\n proba.append(MODEL.predict(q, answer[i]))\n class_.append(predict_class(proba[-1], treshold=treshold))\n elif type_ == 2:\n for i, a in enumerate(answer[:len_seq]):\n proba.append(MODEL.predict(question, a))\n class_.append(predict_class(proba[-1], treshold=treshold))\n elif type_ == 3:\n for i, q in enumerate(question[:len_seq]):\n proba.append(MODEL.predict(q, answer))\n class_.append(predict_class(proba[-1], treshold=treshold))\n else:\n proba = MODEL.predict(question, answer)\n class_ = predict_class(proba, treshold=treshold)\n\n if len_seq != max_len: dict_data[\"log\"][\"comment\"] = \\\n \"Some requests were processed. No available query probability\"\n\n dict_data[\"proba\"] = proba\n dict_data[\"class\"] = class_\n \n if update_db_proba:\n #Запись изменений в базу данных\n data_api.counts_proba_left -= len_seq\n db.session.add(data_api)\n db.session.commit()\n\n dict_data[\"log\"][\"count_available_query\"] = {\"probabylity\":data_api.counts_proba_left,\n \"link\":data_api.counts_link_left,\n \"interpretation\":data_api.counts_interpr_left\n }\n \n\ndef process_dict_from_link(dict_data, update_db_link=True):\n \"\"\"\n Обработчик входного словаря. Расчет вероятности по ссылке на сайт\n \"\"\"\n \n if dict_data == {} or (\"link\" not in dict_data.keys()):\n dict_data[\"log\"] = {\"comment\":\"No found required key: 'link'.\"}\n return\n dict_data[\"log\"] = {}\n\n #Проверка api ключа\n data_api = db.session.query(ApiInformation).get(dict_data[\"key_api\"])\n if data_api is None:\n dict_data[\"log\"][\"comment\"] = \"No correct api_key, or unauthorized user\"\n return\n elif data_api.counts_link_left == 0:\n dict_data[\"log\"][\"comment\"] = \"No available query probability\"\n return\n\n if \"type_parser\" not in dict_data.keys():\n dict_data[\"type_parser\"] = \"answers_mail.ru\"\n \n if dict_data[\"type_parser\"] == \"answers_mail.ru\":\n data_link = parce_data_from_link_answers_mail_ru(dict_data[\"link\"])\n if data_link[\"code\"] < 0:\n dict_data[\"log\"][\"comment\"] = data_link[\"comment\"]\n return\n\n if \"treshold\" not in dict_data.keys():\n dict_data[\"treshold\"] = 0.5\n treshold = dict_data[\"treshold\"]\n\n dict_data[\"question\"] = data_link[\"question\"]\n dict_data[\"answer\"] = data_link[\"answer\"]\n dict_data[\"treshold\"] = treshold\n\n process_dict_from_proba(dict_data, update_db_proba=False, data_api=data_api)\n \n #Запись изменений в базу данных\n data_api.counts_link_left -= 1\n db.session.add(data_api)\n db.session.commit()\n\n dict_data[\"log\"][\"count_available_query\"] = {\"probabylity\":data_api.counts_proba_left,\n \"link\":data_api.counts_link_left,\n \"interpretation\":data_api.counts_interpr_left\n }\n\ndef process_dict_from_interpretation(dict_data):\n \"\"\"\n Обработчик входного словаря. Интерпретация\n \"\"\"\n comment = None\n #Проверка правильности формирования запроса\n if dict_data == {}:\n comment = \"No found required keys: 'question', 'answer'.\"\n elif \"question\" not in dict_data.keys():\n comment = \"No found required key: 'question.\"\n elif \"answer\" not in dict_data.keys():\n comment = \"No found required key: 'answer'.\"\n \n dict_data[\"log\"] = {\"comment\":comment}\n if comment != None:\n return\n\n dict_data[\"log\"] = {}\n #Проверка api ключа\n data_api = db.session.query(ApiInformation).get(dict_data[\"key_api\"])\n if data_api is None:\n dict_data[\"log\"][\"comment\"] = \"No correct api_key, or unauthorized user\"\n return\n elif data_api.counts_interpr_left == 0:\n dict_data[\"log\"][\"comment\"] = \"No available query interpretation\"\n return\n\n neg, pos = interpretation_short(dict_data[\"question\"], dict_data[\"answer\"], dict_data[\"n_max_top\"])\n\n for key, value in neg.items():\n neg[key] = round(value,3)\n for key, value in pos.items():\n pos[key] = round(value,3)\n\n dict_data[\"negative_contribution\"] = neg\n dict_data[\"positive_contribution\"] = pos\n\n #Запись изменений в базу данных\n data_api.counts_interpr_left -= 1\n db.session.add(data_api)\n db.session.commit()\n\n dict_data[\"log\"][\"count_available_query\"] = {\"probabylity\":data_api.counts_proba_left,\n \"link\":data_api.counts_link_left,\n \"interpretation\":data_api.counts_interpr_left\n }\n\n\ndef preprocess_link_answers_mail_ru(link_to_site):\n \"\"\"\n Обработчик входной ссылки на сайт Mail.ru\n \"\"\"\n if link_to_site is None:\n return None\n elif link_to_site.isdigit():\n return 'https://otvet.mail.ru/question/'+link_to_site\n return link_to_site\n\ndef parce_data_from_link_answers_mail_ru(link_to_site):\n output = {}\n output[\"question\"] = None\n output[\"answer\"] = None\n link = preprocess_link_answers_mail_ru(link_to_site)\n if link is None:\n output[\"code\"] = -3\n output[\"comment\"] = \"\"\n return output\n data = get_question_answers(link)\n if isinstance(data, tuple):\n output[\"question\"] = data[0]\n output[\"answer\"] = data[1]\n if data[1] == []:\n output[\"code\"] = -1\n output[\"comment\"] = \"For {} is no answers\".format(link)\n return output\n output[\"code\"] = 0\n output[\"comment\"] = \"Found question and answers\"\n else:\n output[\"code\"] = -2\n output[\"comment\"] = \"Url is incorrect format\"\n return output\n return output\n\"\"\"\nMain pages\n\"\"\"\n@app_web.route(\"/\", methods=['GET', 'POST']) \ndef index():\n return render_template(\"index.html\")\n\n@app_web.route(\"/q_a/\", methods=['GET', 'POST']) \ndef q_a():\n global FLAG_TABLE_HISTORY\n result = {}\n result[\"proba\"] = \"\"\n result[\"smile\"] = get_list_pictures()\n if request.method == \"POST\":\n FLAG_TABLE_HISTORY = 1\n result[\"question\"] = request.form.get(\"question\")\n result[\"answer\"] = request.form.get(\"answer\")\n result[\"proba\"] = MODEL.predict(result[\"question\"],result[\"answer\"])\n result[\"smile\"] = get_list_pictures(result[\"proba\"])\n TABLE_HISTORY.add_row([result[\"question\"], result[\"answer\"], result[\"proba\"], datetime.today().strftime(\"%Y-%m-%d_%H.%M.%S\")])\n TABLE_HISTORY.save_html(path='app/templates/table_history.html')\n return render_template(\"index_question_answer.html\", result=result)\n\n@app_web.route(\"/link/\", methods=['GET', 'POST']) \ndef link():\n global LINK_COMMENT\n global FLAG_TABLE_LINK\n global FLAG_TABLE_HISTORY\n link_to_site = preprocess_link_answers_mail_ru(request.args.get(\"link_to_site\"))\n print(link_to_site)\n data = parce_data_from_link_answers_mail_ru(link_to_site)\n if data[\"code\"] == -3:\n return render_template(\"index_link.html\")\n LINK_COMMENT = data[\"comment\"]\n FLAG_TABLE_LINK = data[\"code\"]\n\n if data[\"code\"] < 0:\n return render_template(\"index_link.html\")\n FLAG_TABLE_HISTORY = 1\n TABLE.clear_table()\n for answer in data[\"answer\"]:\n proba = MODEL.predict(data[\"question\"], answer)\n TABLE.add_row([data[\"question\"], answer, proba])\n TABLE_HISTORY.add_row([data[\"question\"], answer, proba, datetime.today().strftime(\"%Y-%m-%d_%H.%M.%S\")])\n TABLE.save_html(path='app/templates/table.html')\n TABLE_HISTORY.save_html(path='app/templates/table_history.html')\n return render_template(\"index_link.html\")\n\n@app_web.route(\"/interpretation/\", methods=['GET', 'POST']) \ndef interpr():\n result = {}\n result[\"question\"] = \"\"\n result[\"answer\"] = \"\"\n if request.method == \"POST\":\n result[\"question\"] = request.form.get(\"question\")\n result[\"answer\"] = request.form.get(\"answer\")\n interpretation(result[\"question\"], result[\"answer\"])\n return render_template(\"index_interpretation.html\", result=result)\n\n@app_web.route(\"/service/\", methods=['GET', 'POST']) \ndef service():\n return render_template(\"index_service.html\")\n\n@app_web.route(\"/history/\", methods=['GET', 'POST']) \ndef history():\n return render_template(\"index_history.html\")\n\n\"\"\"\nCatch Querry\n\"\"\"\n@app_web.route(\"/catch_query_interpretation/\", methods=['GET', 'POST']) \ndef catch_interpretation():\n if request.method == \"POST\":\n data = request.get_json()\n interpretation(data[\"question\"], data[\"answer\"])\n res = make_response(\"ok\")\n return res\n\n@app_web.route(\"/get_proba/\", methods=['POST']) \ndef catch_proba():\n data = request.get_json()\n process_dict_from_proba(data)\n return jsonify(data)\n\n@app_web.route(\"/get_link/\", methods=['POST']) \ndef catch_link():\n data = request.get_json()\n process_dict_from_link(data)\n return jsonify(data)\n\n@app_web.route(\"/get_interpretation/\", methods=['POST']) \ndef get_interpretation():\n data = request.get_json()\n process_dict_from_interpretation(data)\n return jsonify(data)\n\n@app_web.route(\"/get_user_api_status/\", methods=['POST']) \ndef query_left():\n data = request.get_json()\n data_api = db.session.query(ApiInformation).get(data[\"key_api\"])\n data[\"tarif\"] = data_api.tarif\n data[\"counts_proba_left\"] = data_api.counts_proba_left\n data[\"counts_link_left\"] = data_api.counts_link_left\n data[\"counts_interpr_left\"] = data_api.counts_interpr_left\n return jsonify(data)\n\n\"\"\"\nOther Querry\n\"\"\"\n@app_web.route(\"/output_frame_interpretation/\", methods=['GET', 'POST']) \ndef frame_interpretation():\n result = {}\n result[\"question\"] = \"\"\n result[\"answer\"] = \"\"\n if request.method == \"POST\":\n result = request.get_json()\n return render_template(\"form_interpretation.html\", result=result)\n\n@app_web.route(\"/single_plot/\", methods=['GET']) \ndef single_plot():\n return render_template(\"single_plot.html\")\n\n@app_web.route(\"/table_top/\", methods=['GET']) \ndef table_top():\n global TABLE_INTERP_TOP\n return TABLE_INTERP_TOP.get_html(table_id=\"table_top\", class_table=\"table_top\")\n\n@app_web.route(\"/draw_pos/\", methods=['GET']) \ndef draw_pos():\n return render_template(\"Позитивный.html\")\n\n@app_web.route(\"/top_pos/\", methods=['GET']) \ndef top_pos():\n return render_template(\"table_interpretation_top_pos.html\")\n\n@app_web.route(\"/top_neg/\", methods=['GET']) \ndef top_neg():\n return render_template(\"table_interpretation_top_neg.html\")\n\n@app_web.route(\"/form_interpretation/\", methods=['GET', 'POST']) \ndef form_interpretation():\n return render_template(\"single_plot.html\")\n\n@app_web.route(\"/table_proba/\", methods=['GET', 'POST']) \ndef table_proba():\n global FLAG_TABLE_LINK\n if FLAG_TABLE_LINK < 0:\n return render_template(\"empty.html\", text = LINK_COMMENT)\n return render_template(\"table.html\")\n \n@app_web.route(\"/table_history/\", methods=['GET', 'POST']) \ndef table_history():\n global FLAG_TABLE_HISTORY\n if not FLAG_TABLE_HISTORY:\n return render_template(\"empty.html\", text = \"Ещё нет истории запросов\")\n return render_template(\"table_history.html\")\n\n@app_web.route(\"/table_interpretation/\", methods=['GET', 'POST']) \ndef table_interpretation():\n global TABLE_INTERP\n return TABLE_INTERP.get_html(table_id=\"table_interp\")", "sub_path": "app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 15113, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "app.db.session.query", "line_number": 61, "usage_type": "call"}, {"api_name": "app.ApiInformation", "line_number": 61, "usage_type": "argument"}, {"api_name": "app.db.session", "line_number": 61, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 61, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 103, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 103, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 107, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 107, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 111, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 111, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 114, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 114, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 126, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 126, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 126, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 127, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 127, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 127, "usage_type": "name"}, {"api_name": "app.db.session.query", "line_number": 146, "usage_type": "call"}, {"api_name": "app.ApiInformation", "line_number": 146, "usage_type": "argument"}, {"api_name": "app.db.session", "line_number": 146, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 146, "usage_type": "name"}, {"api_name": "app.db.session.add", "line_number": 175, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 175, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 175, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 176, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 176, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 176, "usage_type": "name"}, {"api_name": "app.db.session.query", "line_number": 202, "usage_type": "call"}, {"api_name": "app.ApiInformation", "line_number": 202, "usage_type": "argument"}, {"api_name": "app.db.session", "line_number": 202, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 202, "usage_type": "name"}, {"api_name": "app.interpretation_short", "line_number": 210, "usage_type": "call"}, {"api_name": "app.db.session.add", "line_number": 222, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 222, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 222, "usage_type": "name"}, {"api_name": "app.db.session.commit", "line_number": 223, "usage_type": "call"}, {"api_name": "app.db.session", "line_number": 223, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 223, "usage_type": "name"}, {"api_name": "app.get_question_answers", "line_number": 250, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 270, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 268, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 268, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 278, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 278, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 280, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 280, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 280, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 281, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 281, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 281, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 282, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 282, "usage_type": "name"}, {"api_name": "app.TABLE_HISTORY.add_row", "line_number": 284, "usage_type": "call"}, {"api_name": "app.TABLE_HISTORY", "line_number": 284, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 284, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 284, "usage_type": "name"}, {"api_name": "app.TABLE_HISTORY.save_html", "line_number": 285, "usage_type": "call"}, {"api_name": "app.TABLE_HISTORY", "line_number": 285, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 286, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 272, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 272, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 293, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 293, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 293, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 297, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 302, "usage_type": "call"}, {"api_name": "app.TABLE.clear_table", "line_number": 304, "usage_type": "call"}, {"api_name": "app.TABLE", "line_number": 304, "usage_type": "name"}, {"api_name": "app.MODEL.predict", "line_number": 306, "usage_type": "call"}, {"api_name": "app.MODEL", "line_number": 306, "usage_type": "name"}, {"api_name": "app.TABLE.add_row", "line_number": 307, "usage_type": "call"}, {"api_name": "app.TABLE", "line_number": 307, "usage_type": "name"}, {"api_name": "app.TABLE_HISTORY.add_row", "line_number": 308, "usage_type": "call"}, {"api_name": "app.TABLE_HISTORY", "line_number": 308, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 308, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 308, "usage_type": "name"}, {"api_name": "app.TABLE.save_html", "line_number": 309, "usage_type": "call"}, {"api_name": "app.TABLE", "line_number": 309, "usage_type": "name"}, {"api_name": "app.TABLE_HISTORY.save_html", "line_number": 310, "usage_type": "call"}, {"api_name": "app.TABLE_HISTORY", "line_number": 310, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 311, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 288, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 288, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 318, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 318, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 319, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 319, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 319, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 320, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 320, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 320, "usage_type": "name"}, {"api_name": "app.interpretation", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 322, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 313, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 313, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 326, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 324, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 324, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 330, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 328, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 328, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 337, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 337, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 338, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 338, "usage_type": "name"}, {"api_name": "app.interpretation", "line_number": 339, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 340, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 335, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 335, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 345, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 345, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 347, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 343, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 343, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 351, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 351, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 353, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 349, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 349, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 357, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 357, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 359, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 355, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 355, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 363, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 363, "usage_type": "name"}, {"api_name": "app.db.session.query", "line_number": 364, "usage_type": "call"}, {"api_name": "app.ApiInformation", "line_number": 364, "usage_type": "argument"}, {"api_name": "app.db.session", "line_number": 364, "usage_type": "attribute"}, {"api_name": "app.db", "line_number": 364, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 369, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 361, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 361, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 379, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 379, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 380, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 380, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 381, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 374, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 374, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 385, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 383, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 383, "usage_type": "name"}, {"api_name": "app.TABLE_INTERP_TOP.get_html", "line_number": 390, "usage_type": "call"}, {"api_name": "app.TABLE_INTERP_TOP", "line_number": 390, "usage_type": "name"}, {"api_name": "app.app_web.route", "line_number": 387, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 387, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 394, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 392, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 392, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 398, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 396, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 396, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 402, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 400, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 400, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 406, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 404, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 404, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 412, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 413, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 408, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 408, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 419, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 420, "usage_type": "call"}, {"api_name": "app.app_web.route", "line_number": 415, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 415, "usage_type": "name"}, {"api_name": "app.TABLE_INTERP.get_html", "line_number": 425, "usage_type": "call"}, {"api_name": "app.TABLE_INTERP", "line_number": 425, "usage_type": "name"}, {"api_name": "app.app_web.route", "line_number": 422, "usage_type": "call"}, {"api_name": "app.app_web", "line_number": 422, "usage_type": "name"}]} +{"seq_id": "426567769", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 5 13:39:06 2019\n\n@author: TONG\n\"\"\"\n#This notebook introduced a few techniques to handle a regression problem.\n#\n#Mean Squared Error (MSE) is a common loss function used for regression problems (different than classification problems).\n#Similarly, evaluation metrics used for regression differ from classification. A common regression metric is Mean Absolute Error (MAE).\n#When input data features have values with different ranges, each feature should be scaled independently.\n#If there is not much training data, prefer a small network with few hidden layers to avoid overfitting.\n#Early stopping is a useful technique to prevent overfitting.\n\n\nfrom __future__ import absolute_import, division, print_function\n\nimport pathlib\n\nimport pandas as pd\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nprint(tf.__version__)\n\n# =============================================================================\n# Getting file and importing using pandas\n# =============================================================================\ndataset_path = keras.utils.get_file(\"auto-mpg.data\", \"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\")\nprint(dataset_path)\n\ncolumn_names = ['MPG','Cylinders','Displacement','Horsepower','Weight',\n 'Acceleration', 'Model Year', 'Origin'] \nraw_dataset = pd.read_csv(dataset_path, names=column_names,\n na_values = \"?\", comment='\\t',\n sep=\" \", skipinitialspace=True)\n\ndataset = raw_dataset.copy() #copy() method copies the data using shallow copy ie. the original data will be unaffected by any changes to the oopied data, and vice versa\nprint(dataset.tail()) #shows the last 5 data in the dataset\n\n#Check for unknown values\ndataset.isna().sum()\n#Drop rows with unknown values\ndataset = dataset.dropna()\n\n#Convert \"Origin\" column to numeric\norigin = dataset.pop('Origin') #remove the origin column and change to numbers\ndataset['USA'] = (origin == 1)*1.0 #adds an zero USA column where, at indices where the in the popped column origin==1, changes the value in that cell to 1\ndataset['Europe'] = (origin == 2)*1.0\ndataset['Japan'] = (origin == 3)*1.0\ndataset.tail()\n\n\n# =============================================================================\n# TRAINING \n# =============================================================================\ntrain_dataset = dataset.sample(frac=0.8,random_state=0) #samples data,0.8 for training, 0.2 for testing, random_state is the seed for number generator for repeatability\ntest_dataset = dataset.drop(train_dataset.index) #removes columns or rows( in this case remove rows with the specified indices)\n\n#pairplot\nsns.pairplot(train_dataset[[\"MPG\", \"Cylinders\", \"Displacement\", \"Weight\"]], diag_kind=\"kde\") # looks at data distribution\n\n#descriptive statistics describe()\ntrain_stats = train_dataset.describe()\ntrain_stats.pop(\"MPG\")\ntrain_stats = train_stats.transpose()\ntrain_stats\n\n#separate labels(the label that will be used for prediction) from the dataset\ntrain_labels = train_dataset.pop('MPG')\ntest_labels = test_dataset.pop('MPG')\n#MPG is a measure of fuel efficiency\n\n#NORMALIZATION\n#As the descriptive statistics show that there is a distinctive variation in the feature value ranges,\n#the data should be normalized (optional)\n#here we normalize using (x-mean)/std\ndef norm(x):\n return (x - train_stats['mean']) / train_stats['std']\nnormed_train_data = norm(train_dataset)\nnormed_test_data = norm(test_dataset)\n\n#BUILDING MODEL\ndef build_model():\n model = keras.Sequential([\n #3 layers\n #1. two dense layers - first layer taking in inputs of nine datapoints\n #2. single node output returning a continuous value\n layers.Dense(64, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]),\n layers.Dense(64, activation=tf.nn.relu),\n layers.Dense(1)\n ])\n optimizer = tf.train.RMSPropOptimizer(0.001)\n model.compile(loss='mse',\n optimizer=optimizer,\n metrics=['mae', 'mse'])\n return model\n\nmodel = build_model()\n\n#TRAINING \n# ***Display training progress by printing a single dot for each completed epoch\nclass PrintDot(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\nEPOCHS = 1000\n\nhistory = model.fit(\n normed_train_data, train_labels,\n epochs=EPOCHS, validation_split = 0.2, verbose=0,\n callbacks=[PrintDot()]) #callback method(what to print)\n\n#visualize training progress\nhist = pd.DataFrame(history.history)\nhist['epoch'] = history.epoch\nhist.tail()\n\nimport matplotlib.pyplot as plt\n\ndef plot_history(history):\n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Abs Error [MPG]')\n plt.plot(hist['epoch'], hist['mean_absolute_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_absolute_error'],\n label = 'Val Error')\n plt.legend()\n plt.ylim([0,5])\n \n plt.figure()\n plt.xlabel('Epoch')\n plt.ylabel('Mean Square Error [$MPG^2$]')\n plt.plot(hist['epoch'], hist['mean_squared_error'],\n label='Train Error')\n plt.plot(hist['epoch'], hist['val_mean_squared_error'],\n label = 'Val Error')\n plt.legend()\n plt.ylim([0,20])\n\nplot_history(history)\n\n\nmodel = build_model()\n\n# from the graphs we see that error stops decreasing after 1000+ runs\n# using callback that tests training condition for every epoch\n# if no improvement is shown after a few epochs, then stop training\n# The patience parameter is the amount of epochs to check for improvement\nearly_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=50)\n\nhistory = model.fit(normed_train_data, train_labels, epochs=EPOCHS,\n validation_split = 0.2, verbose=0, callbacks=[early_stop, PrintDot()])\n\nplot_history(history)\n\n\n# =============================================================================\n# USING THE TEST SET\n# =============================================================================\nloss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=0)\n\nprint(\"Testing set Mean Abs Error: {:5.2f} MPG\".format(mae))\n\n\ntest_predictions = model.predict(normed_test_data).flatten()\n\nplt.scatter(test_labels, test_predictions)\nplt.xlabel('True Values [MPG]')\nplt.ylabel('Predictions [MPG]')\nplt.axis('equal')\nplt.axis('square')\nplt.xlim([0,plt.xlim()[1]])\nplt.ylim([0,plt.ylim()[1]])\n_ = plt.plot([-100, 100], [-100, 100]) #if true=predicted, points should follow a straight line from -100,-100 to 100,100\n\n# histogram of difference between predicted and true labels\nerror = test_predictions - test_labels\nplt.hist(error, bins = 25)\nplt.xlabel(\"Prediction Error [MPG]\")\n_ = plt.ylabel(\"Count\")\n\n\n\n", "sub_path": "Desktop/tensorflow/tuto3regression.py", "file_name": "tuto3regression.py", "file_ext": "py", "file_size_in_byte": 6793, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "tensorflow.__version__", "line_number": 26, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.utils.get_file", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras.utils", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 31, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 36, "usage_type": "call"}, {"api_name": "seaborn.pairplot", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.keras.Sequential", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 87, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 91, "usage_type": "name"}, {"api_name": "tensorflow.nn", "line_number": 91, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 92, "usage_type": "name"}, {"api_name": "tensorflow.nn", "line_number": 92, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 93, "usage_type": "name"}, {"api_name": "tensorflow.train.RMSPropOptimizer", "line_number": 95, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 95, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.callbacks", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 105, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "tensorflow.keras.callbacks.EarlyStopping", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks", "line_number": 154, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}]} +{"seq_id": "129826193", "text": "from selenium import webdriver\nimport information\n\n#Start Browser at Amazon.com\ndriver = webdriver.Firefox()\ndriver.get(\"https://fake-it.to/\")\ndriver.maximize_window()\n\n#Find Name Value [x]\nname_element = driver.find_elements_by_xpath(\"/html/body/div[2]/div[2]/div[1]/div[1]/table[1]/tbody/tr[1]/td\")\nname_list = [x.text for x in name_element]\ninformation.name = name_list[0]\n#print(information.name)\n\n#Vor- und Nachname [x]\ninformation.name_vor = str(information.name).split(\" \")[0]\ninformation.name_nach = str(information.name).split(\" \")[1]\n#print(information.name_vor)\n#print(information.name_nach)\n\n#Straße + H-Nummer [x]\nstraße_element = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/table[1]/tbody/tr[2]/td')\nstraße_list = [x.text for x in straße_element]\ninformation.straße = straße_list[0]\n#print(information.straße)\n\n#Stadt [x]\nstadt_element = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/table[1]/tbody/tr[3]/td')\nstadt_list = [x.text for x in stadt_element]\ninformation.stadt = stadt_list[0]\n#print(information.stadt)\n\n#Postleitzahl + Stadtname [x]\ninformation.postz = str(information.stadt).split(\" \")[0]\ninformation.stadtname = str(information.stadt).split(\" \")[1]\n#print(information.postz)\n#print(information.stadtname)\n\n#Telefon [x]\ntelefon_element = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/table[1]/tbody/tr[4]/td')\ntelefon_list = [x.text for x in telefon_element]\ninformation.telefon = telefon_list[0]\n#print(information.telefon)\n\n#Geburtsdatum [ ]\n\n\n#IBAN [x]\niban_element = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/table[4]/tbody/tr[4]/td/div/div[1]')\niban_list = [x.text for x in iban_element]\ninformation.iban = iban_list[0]\ninformation.iban = information.iban.split(\"\\n\")[0]\n#print(information.iban)\n\n#BIC [ ]\ndriver.close()\n\nprint(information.name)\nprint(information.name_vor)\nprint(information.name_nach)\nprint(information.straße)\nprint(information.stadtname)\nprint(information.postz)\nprint(information.telefon)\nprint(information.iban)", "sub_path": "textget_test.py", "file_name": "textget_test.py", "file_ext": "py", "file_size_in_byte": 2085, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "selenium.webdriver.Firefox", "line_number": 5, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 5, "usage_type": "name"}, {"api_name": "information.name", "line_number": 12, "usage_type": "attribute"}, {"api_name": "information.name_vor", "line_number": 16, "usage_type": "attribute"}, {"api_name": "information.name", "line_number": 16, "usage_type": "attribute"}, {"api_name": "information.name_nach", "line_number": 17, "usage_type": "attribute"}, {"api_name": "information.name", "line_number": 17, "usage_type": "attribute"}, {"api_name": "information.straße", "line_number": 24, "usage_type": "attribute"}, {"api_name": "information.stadt", "line_number": 30, "usage_type": "attribute"}, {"api_name": "information.postz", "line_number": 34, "usage_type": "attribute"}, {"api_name": "information.stadt", "line_number": 34, "usage_type": "attribute"}, {"api_name": "information.stadtname", "line_number": 35, "usage_type": "attribute"}, {"api_name": "information.stadt", "line_number": 35, "usage_type": "attribute"}, {"api_name": "information.telefon", "line_number": 42, "usage_type": "attribute"}, {"api_name": "information.iban", "line_number": 51, "usage_type": "attribute"}, {"api_name": "information.iban", "line_number": 52, "usage_type": "attribute"}, {"api_name": "information.iban.split", "line_number": 52, "usage_type": "call"}, {"api_name": "information.name", "line_number": 58, "usage_type": "attribute"}, {"api_name": "information.name_vor", "line_number": 59, "usage_type": "attribute"}, {"api_name": "information.name_nach", "line_number": 60, "usage_type": "attribute"}, {"api_name": "information.straße", "line_number": 61, "usage_type": "attribute"}, {"api_name": "information.stadtname", "line_number": 62, "usage_type": "attribute"}, {"api_name": "information.postz", "line_number": 63, "usage_type": "attribute"}, {"api_name": "information.telefon", "line_number": 64, "usage_type": "attribute"}, {"api_name": "information.iban", "line_number": 65, "usage_type": "attribute"}]} +{"seq_id": "77607819", "text": "import os\nimport sys\nimport io\nfrom flask import Flask, redirect, render_template, request, send_from_directory, url_for, jsonify\nimport requests\nimport shutil\nimport numpy as np\nimport cv2\nimport warnings\nfrom PIL import Image\nimport tensorflow as tf\nimport keras\nfrom keras import backend as K\nimport base64\nfrom mrcnn import utils\nfrom mrcnn import visualize\nfrom mrcnn.visualize import display_images\nimport mrcnn.model as modellib\nfrom mrcnn.model import log\nfrom trash import trash\nimport json\n\n\nK.clear_session()\n\nfrom tensorflow.python.keras.backend import set_session\n\nsess = tf.compat.v1.Session()\ngraph = tf.compat.v1.get_default_graph()\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\napp = Flask(__name__)\n# Directory to save logs and trained model\n# MODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# # Path to Trash trained weights\n# TRASH_WEIGHTS_PATH = \"weights/mask_rcnn_trash_0200_030519_large.h5\"\n\n# config = trash.TrashConfig()\n# class InferenceConfig(config.__class__):\n# # Run detection on one image at a time\n# GPU_COUNT = 1\n# IMAGES_PER_GPU = 1\n\n# config = InferenceConfig()\n# # config.display()\n\n# DEVICE = \"/cpu:0\"\n# TEST_MODE = \"inference\"\n\n# #loading model\n# set_session(sess)\n# model = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n\n# print(\"model loaded!\")\n\n# #loading weights\n# weights_path = os.path.join(ROOT_DIR, TRASH_WEIGHTS_PATH)\n# model.load_weights(weights_path, by_name=True)\n# model.keras_model._make_predict_function()\n# print(\"weights loaded!\")\n\n# @app.route('/predict', methods = ['GET', 'POST'])\n# def get_trash():\n# # image_url = \"https://firebasestorage.googleapis.com/v0/b/litterally-asean.appspot.com/o/down.png?alt=media&token=d723cb68-ac15-4e70-8bc1-190352311131\"\n# image_url = request.data.decode('utf-8')\n# r = requests.get(image_url)\n\n# if r.status_code == 200:\n# image = Image.open(io.BytesIO(r.content))\n# # image.save('uploads/temp.png')\n# image = np.array(image)\n# image = image[:,:,:3]\n# print(image.shape)\n# global sess\n# global graph\n# with graph.as_default():\n# set_session(sess)\n# results = model.detect([image], verbose=1)\n# print(results)\n \n# data = dict()\n# # data['rois'] = np.array2string(results[0]['rois'], precision=2, separator=',')\n# data['rois'] = json.dumps(results[0]['rois'].tolist())\n# # data['class_ids'] = np.array2string(results[0]['class_ids'], precision=2, separator=',')\n# data['class_ids'] = json.dumps(results[0]['class_ids'].tolist())\n# # data['scores'] = np.array2string(results[0]['scores'], precision=2, separator=',')\n# data['scores'] = json.dumps(results[0]['scores'].tolist())\n# return jsonify(data)\n# else:\n# data = dict()\n# data['error'] = \"error downloading image!\"\n\ndef reconstruct(pb_path):\n if not os.path.isfile(pb_path):\n print(\"Error: %s not found\" % pb_path)\n\n print(\"Reconstructing Tensorflow model\")\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.compat.v1.GraphDef()\n with tf.io.gfile.GFile(pb_path, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n print(\"Success!\")\n return detection_graph\n\ndef image2tensor(image):\n # npim = image2np(image)\n return np.expand_dims(image, axis=0)\n\ndef detect(detection_graph, test_image):\n with detection_graph.as_default():\n gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.01)\n with tf.compat.v1.Session(graph=detection_graph,config=tf.compat.v1.ConfigProto(gpu_options=gpu_options)) as sess:\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n # image = Image.open(test_image_path)\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image2tensor(test_image)}\n )\n \n return boxes, scores, classes, num\n\n@app.route('/classify', methods = ['GET', 'POST'])\ndef trash_classification():\n image_url = request.data.decode(\"utf-8\")\n r = requests.get(image_url)\n\n if r.status_code == 200:\n image = Image.open(io.BytesIO(r.content))\n image = np.array(image)\n image = image[:,:,:3]\n\n ANNOTATIONS_FILE = './taco_ssd_weights/annotations.json'\n\n with open(ANNOTATIONS_FILE) as json_file:\n data = json.load(json_file)\n \n categories = data['categories']\n classes = []\n for i in range(len(categories)):\n classes.append(categories[i]['name'])\n\n detection_graph = reconstruct(\"./taco_ssd_weights/ssd_mobilenet_v2_taco_2018_03_29.pb\")\n b, s, c, n = detect(detection_graph, image)\n\n class_names = []\n scores = []\n\n for i in range(int(n[0])):\n class_names.append(classes[int(c[0][i]) - 1])\n scores.append(str(s[0][i]))\n print(class_names)\n print(scores)\n\n op = dict()\n op['trash_classes'] = json.dumps(class_names)\n op['confidence'] = json.dumps(scores)\n return jsonify(op)\n else:\n op = dict()\n op['error'] = \"error loading image file!\"\n return jsonify(op)\n\n\nif __name__ == '__main__':\n app.run(debug=False, threaded=True)", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 5972, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "keras.backend.clear_session", "line_number": 24, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 24, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.get_default_graph", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 29, "usage_type": "attribute"}, {"api_name": "warnings.filterwarnings", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path", "line_number": 97, "usage_type": "attribute"}, {"api_name": "tensorflow.Graph", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.GraphDef", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.io.gfile.GFile", "line_number": 104, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.import_graph_def", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.GPUOptions", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 117, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 118, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 118, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.ConfigProto", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.request.data.decode", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 135, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 135, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 136, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 139, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 139, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 140, "usage_type": "call"}, {"api_name": "json.load", "line_number": 146, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 166, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 167, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 168, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 172, "usage_type": "call"}]} +{"seq_id": "233071740", "text": "import abc\nimport io\nimport re\nimport json\nimport yaml\nimport requests\nfrom collections import OrderedDict, defaultdict\n\nfrom django.core import exceptions\nfrom django.utils.module_loading import import_string\nimport tabulator\n\nfrom .. import utils\nfrom ..ingest_settings import UPLOAD_SETTINGS\n\n\n###########################################\n# Helper functions to manage validators\n###########################################\ndef validators():\n \"\"\"\n Generates Validator instances based on settings.py:UPLOAD_SETTINGS['VALIDATORS']\n\n :return: Iterator of Validator instances\n\n \"\"\"\n for (filename, validator_type) in UPLOAD_SETTINGS[\"VALIDATORS\"].items():\n validator = import_string(validator_type)(\n name=validator_type, filename=filename\n )\n yield validator\n\n\ndef apply_validators_to(source, content_type):\n\n overall_result = {}\n for validator in validators():\n validation_results = validator.validate(source, content_type)\n overall_result = ValidatorOutput.combine(overall_result, validation_results)\n return overall_result\n\n\n###########################################\n# Exception\n###########################################\nclass UnsupportedException(Exception):\n pass\n\n\nclass UnsupportedContentTypeException(UnsupportedException):\n def __init__(self, content_type, validator_name):\n super(UnsupportedContentTypeException, self).__init__(\n \"Content type {} is not supported by {}\".format(\n content_type, validator_name\n )\n )\n self.content_type = content_type\n self.validator_name = validator_name\n\n\n###########################################\n# Validator Output\n###########################################\nclass ValidatorOutput:\n \"\"\"\n This class will be used to create a standard validator output. Validator should make use of this class\n to generate the standard validator output and its other functionalities to combine output if using more\n than one validator at a time\n \"\"\"\n\n def __init__(self, rows_in_dict, headers=[]):\n \"\"\"\n Init - Initiate objects to generate output later\n\n Parameters:\n rows_in_dict - a list of rows of the source. Each row is a dictionary that consist of the row data.\n Each row dictionary consists of `row_number` which is integer, and `row_data` which is\n an ordered dictionary the data (key - header/field name, value - data of that field)\n headers - (optional) a list of field names in the source (if relevant, i.e. tabular data)\n \"\"\"\n self.rows_in_dict = rows_in_dict\n self.headers = headers\n self.row_errors = defaultdict(list)\n self.whole_table_errors = []\n\n def create_error(self, severity, code, message, fields):\n \"\"\"\n Create standardized error dictionary\n\n Parameters:\n severity - severity of this error, right now \"Error\" or \"Warning\"\n code - error code\n message - error message that describe what the error is\n fields - a list of all the field names that are associated with this error\n\n Returns:\n Dictionary with the following items: severity, code, message, fields\n \"\"\"\n error = {}\n error[\"severity\"] = severity\n error[\"code\"] = code\n error[\"message\"] = message\n error[\"fields\"] = fields\n\n return error\n\n def add_row_error(self, row_number, severity, code, message, fields):\n \"\"\"\n Add row specific error to the list of row errors\n\n Parameters:\n row_number - the number indicate which row this error belongs\n severity - severity of this error, right now \"Error\" or \"Warning\"\n code - error code\n message - error message that describe what the error is\n fields - a list of all the field names that are associated with this error\n\n Returns:\n None\n \"\"\"\n error = self.create_error(severity, code, message, fields)\n\n self.row_errors[row_number].append(error)\n\n def add_whole_table_error(self, severity, code, message, fields):\n \"\"\"\n Add error that applies to the whole table to the list of whole table errors\n\n Parameters:\n severity - severity of this error, right now \"Error\" or \"Warning\"\n code - error code\n message - error message that describe what the error is\n fields - a list of all the field names that are associated with this error\n\n Returns:\n None\n \"\"\"\n error = self.create_error(severity, code, message, fields)\n\n self.whole_table_errors.append(error)\n\n def create_rows(self):\n \"\"\"\n Create a list of row dictionary to indicates the errors it has\n\n Parameters:\n None\n\n Returns:\n A list of row dictionary\n - row dictionary consists of the following items:\n - row_number - a number to indicate the row\n - errors - a list of error dictionaries for this row\n - error - each error should match the specification from `create_error`\n - data - a dictionary of key (field name) / value (data for that field) pairs\n \"\"\"\n result = []\n\n # Right now if we are using JsonschemaValidator, the rows_in_dict is a raw source and it will always be a list\n # of JSON object. See validate method in JsonschemaValidator when instantiating the ValidatorOutput. This is\n # different than the expected rows_in_dict described in the ValidatorOutput.__init__ method, where each object\n # of the list include a tuple of row_number and row_data. So by doing the `enumerate`, it will mimic that\n # behaviors. It also means that when using JsonschemaValidator, the row number starts at 0.\n\n # @TODO: Need to revisit this to see if this is the best way to do this\n rows = (\n self.rows_in_dict.items()\n if isinstance(self.rows_in_dict, dict)\n else enumerate(self.rows_in_dict)\n )\n for (row_number, row_data) in rows:\n result.append(\n {\n \"row_number\": row_number,\n \"errors\": self.row_errors.get(row_number, []),\n \"data\": row_data,\n }\n )\n\n return result\n\n def get_output(self):\n \"\"\"\n Generate the validation output based on stored values\n\n Parameters:\n None\n\n Returns:\n A dictionary with the following items:\n - tables - a list of table object\n - table - a dictionary with the following items:\n - headers - a list of field names for the data\n - whole_table_errors - a list of errors that are related to the entire table\n - rows - a dictionary generated from `create_rows`. See specification there.\n - valid_row_count - an integer indicates the number of valid rows in the data\n - invalid_row_count - an integer indicates the number of invalid rows in the data\n - valid - boolean to indicates whether the data is valid or not\n \"\"\"\n table = {}\n table[\"headers\"] = self.headers\n table[\"whole_table_errors\"] = self.whole_table_errors\n table[\"rows\"] = self.create_rows()\n table[\"valid_row_count\"] = [(not row[\"errors\"]) for row in table[\"rows\"]].count(\n True\n )\n table[\"invalid_row_count\"] = len(table[\"rows\"]) - table[\"valid_row_count\"]\n\n # This needs to evaluate again at some point if this is even possible to run validator for more than\n # one table other than using GoodTables, the old code didn't allow more than one table, so should we\n # even need a list of tables?\n result = {}\n result[\"tables\"] = [table]\n result[\"valid\"] = (table[\"invalid_row_count\"] == 0) and not table[\n \"whole_table_errors\"\n ]\n\n return result\n\n @staticmethod\n def combine(output1, output2):\n \"\"\"\n Combine two validation outputs together. This function expects validation outputs that follows\n the specification indicated in `get_output`\n\n Parameters:\n output1 - validation output that follows the spec in `get_output`\n output2 - validation output that follows the spec in `get_output`\n\n Returns:\n A dictionary with the same specification as `get_output` output\n \"\"\"\n if not output1:\n return output2\n elif not output2:\n return output1\n\n table = {}\n table[\"headers\"] = output1[\"tables\"][0][\"headers\"]\n table[\"whole_table_errors\"] = (\n output1[\"tables\"][0][\"whole_table_errors\"]\n + output2[\"tables\"][0][\"whole_table_errors\"]\n )\n table[\"rows\"] = []\n\n # Will assume output1 and output2 have the same number of rows, else you will get unexpected behaviors\n for (row_number, row) in enumerate(output1[\"tables\"][0][\"rows\"]):\n table[\"rows\"].append(\n {\n \"row_number\": row[\"row_number\"],\n \"errors\": row[\"errors\"]\n + output2[\"tables\"][0][\"rows\"][row_number][\"errors\"],\n \"data\": row[\"data\"],\n }\n )\n\n table[\"valid_row_count\"] = [(not row[\"errors\"]) for row in table[\"rows\"]].count(\n True\n )\n table[\"invalid_row_count\"] = len(table[\"rows\"]) - table[\"valid_row_count\"]\n\n result = {}\n result[\"tables\"] = [table]\n result[\"valid\"] = (table[\"invalid_row_count\"] == 0) and not table[\n \"whole_table_errors\"\n ]\n\n return result\n\n\n# Inherit this `Validator` class to create a new validator. Note that\n# the `validate` method must return a dictionary corresponding to the\n# structure of `ValidatorOutput.get_output`.\n#\n# You may also toggle the SUPPORTS_HEADER_OVERRIDE (ignore any\n# configured headers) and INVERT_LOGIC (apply a `not` operation to the\n# results) boolean options.\nclass Validator(abc.ABC):\n\n SUPPORTS_HEADER_OVERRIDE = False\n INVERT_LOGIC = False\n\n url_pattern = re.compile(r\"^\\w{3,5}://\")\n\n def invert_if_needed(self, value):\n \"\"\"\n Inverts a boolean, iff `self.INVERT_LOGIC`\n\n :param value: Boolean value to invert (or not)\n :return: Boolean\n \"\"\"\n\n if self.INVERT_LOGIC:\n return not value\n else:\n return value\n\n def __init__(self, name, filename):\n \"\"\"\n\n :param name: Name of the validator class\n :param filename: Name of file to load validation rules from\n\n \"\"\"\n self.name = name\n self.filename = filename\n self.validator = self.get_validator_contents()\n\n if isinstance(UPLOAD_SETTINGS[\"STREAM_ARGS\"][\"headers\"], list) and (\n not self.SUPPORTS_HEADER_OVERRIDE\n ):\n raise exceptions.ImproperlyConfigured(\n \"Listing ['STREAM_ARGS']['headers'] not supported by this validator (\"\n + type(self).__name__\n + \")\"\n )\n\n def load_file(self):\n with open(self.filename) as infile:\n if self.filename.endswith(\".yml\") or self.filename.endswith(\".yaml\"):\n return yaml.safe_load(infile)\n else:\n return json.load(infile)\n\n def get_validator_contents(self):\n \"\"\"Return validator filename, or URL contents in case of URLs\"\"\"\n\n if self.filename:\n if self.url_pattern.search(self.filename):\n resp = requests.get(self.filename)\n if resp.ok:\n if self.filename.endswith(\"yml\") or self.filename.endswith(\".yaml\"):\n return yaml.safe_load(resp.text)\n return resp.json()\n else:\n raise exceptions.ImproperlyConfigured(\n \"validator {} {} returned {}\".format(\n self.name, self.filename, resp.status\n )\n )\n else:\n return self.load_file()\n return self.filename\n\n @staticmethod\n def rows_from_source(raw_source):\n source = raw_source.copy()\n try:\n f_source = io.BytesIO(source[\"source\"])\n byteslike = True\n except (TypeError, AttributeError, KeyError):\n byteslike = False\n\n if byteslike:\n source[\"source\"] = f_source\n stream = tabulator.Stream(**source, encoding=\"utf-8\")\n else:\n stream = tabulator.Stream(source, headers=1, encoding=\"utf-8\")\n\n stream.open()\n\n # This will get the first row\n try:\n hs = next(stream.iter(extended=True))[1]\n # nothing in the stream\n except StopIteration:\n hs = []\n # Reset the pointer to the beginning\n stream.reset()\n o_headers = utils.get_ordered_headers(hs)\n\n result = OrderedDict()\n for (row_num, headers, vals) in stream.iter(extended=True):\n data = dict(zip(headers, vals))\n o_data = OrderedDict((h, data.get(h, \"\")) for h in o_headers)\n result[row_num] = o_data\n\n return (o_headers, result)\n\n @abc.abstractmethod\n def validate(self, source, content_type):\n \"\"\"\n Validate the data from source and return a standard validation output\n\n Parameters:\n source - raw source\n\n Returns:\n A dictionary object that follows the specification of `ValidatorOutput.get_output`\n \"\"\"\n", "sub_path": "data_ingest/validators/validator.py", "file_name": "validator.py", "file_ext": "py", "file_size_in_byte": 13651, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "ingest_settings.UPLOAD_SETTINGS", "line_number": 27, "usage_type": "name"}, {"api_name": "django.utils.module_loading.import_string", "line_number": 28, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 83, "usage_type": "call"}, {"api_name": "abc.ABC", "line_number": 278, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 283, "usage_type": "call"}, {"api_name": "ingest_settings.UPLOAD_SETTINGS", "line_number": 309, "usage_type": "name"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 312, "usage_type": "call"}, {"api_name": "django.core.exceptions", "line_number": 312, "usage_type": "name"}, {"api_name": "yaml.safe_load", "line_number": 321, "usage_type": "call"}, {"api_name": "json.load", "line_number": 323, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 330, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 333, "usage_type": "call"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 336, "usage_type": "call"}, {"api_name": "django.core.exceptions", "line_number": 336, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 349, "usage_type": "call"}, {"api_name": "tabulator.Stream", "line_number": 356, "usage_type": "call"}, {"api_name": "tabulator.Stream", "line_number": 358, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 372, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 375, "usage_type": "call"}, {"api_name": "abc.abstractmethod", "line_number": 380, "usage_type": "attribute"}]} +{"seq_id": "19133750", "text": "#coding: utf-8\nimport logging\nfrom threading import Thread\n\nfrom ldap import SCOPE_BASE\nfrom seafevents.ldap_syncer.ldap_conn import LdapConn\nfrom seafevents.ldap_syncer.utils import bytes2str, add_group_uuid_pair\n\nfrom seaserv import get_group_dn_pairs\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef migrate_dn_pairs(settings):\n grp_dn_pairs = get_group_dn_pairs()\n if grp_dn_pairs is None:\n logger.warning('get group dn pairs from db failed when migrate dn pairs.')\n return\n\n grp_dn_pairs.reverse()\n for grp_dn_pair in grp_dn_pairs:\n for config in settings.ldap_configs:\n search_filter = '(objectClass=*)'\n ldap_conn = LdapConn(config.host, config.user_dn, config.passwd, config.follow_referrals)\n ldap_conn.create_conn()\n if not ldap_conn.conn:\n logger.warning('connect ldap server [%s] failed.' % config.user_dn)\n return\n\n if config.use_page_result:\n results = ldap_conn.paged_search(grp_dn_pair.dn, SCOPE_BASE,\n search_filter,\n [config.group_uuid_attr])\n else:\n results = ldap_conn.search(grp_dn_pair.dn, SCOPE_BASE,\n search_filter,\n [config.group_uuid_attr])\n ldap_conn.unbind_conn()\n results = bytes2str(results)\n\n if not results:\n continue\n else:\n uuid = results[0][1][config.group_uuid_attr][0]\n add_group_uuid_pair(grp_dn_pair.group_id, uuid)\n\n\nclass LdapSync(Thread):\n def __init__(self, settings):\n Thread.__init__(self)\n self.settings = settings\n\n def run(self):\n if self.settings.enable_group_sync:\n migrate_dn_pairs(settings=self.settings)\n self.start_sync()\n self.show_sync_result()\n\n def show_sync_result(self):\n pass\n\n def start_sync(self):\n data_ldap = self.get_data_from_ldap()\n if data_ldap is None:\n return\n\n data_db = self.get_data_from_db()\n if data_db is None:\n return\n\n self.sync_data(data_db, data_ldap)\n\n def get_data_from_db(self):\n return None\n\n def get_data_from_ldap(self):\n ret = {}\n\n for config in self.settings.ldap_configs:\n cur_ret = self.get_data_from_ldap_by_server(config)\n # If get data from one server failed, then the result is failed\n if cur_ret is None:\n return None\n for key in cur_ret.keys():\n if key not in ret:\n ret[key] = cur_ret[key]\n ret[key].config = config\n\n return ret\n\n def get_data_from_ldap_by_server(self, config):\n return None\n\n def sync_data(self, data_db, data_ldap):\n pass\n", "sub_path": "python/seafevents/ldap_syncer/ldap_sync.py", "file_name": "ldap_sync.py", "file_ext": "py", "file_size_in_byte": 2951, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "seaserv.get_group_dn_pairs", "line_number": 16, "usage_type": "call"}, {"api_name": "seafevents.ldap_syncer.ldap_conn.LdapConn", "line_number": 25, "usage_type": "call"}, {"api_name": "ldap.SCOPE_BASE", "line_number": 32, "usage_type": "argument"}, {"api_name": "ldap.SCOPE_BASE", "line_number": 36, "usage_type": "argument"}, {"api_name": "seafevents.ldap_syncer.utils.bytes2str", "line_number": 40, "usage_type": "call"}, {"api_name": "seafevents.ldap_syncer.utils.add_group_uuid_pair", "line_number": 46, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 49, "usage_type": "name"}, {"api_name": "threading.Thread.__init__", "line_number": 51, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "21426582", "text": "import cv2\nimport numpy as np\n\ndst_size = (256, 512)\nscreen1 = cv2.resize(cv2.imread(r'image_1.png'), dst_size)\nscreen2 = cv2.resize(cv2.imread(r'image_2.jpeg'), dst_size)\n\n# diff = abs(screen1.astype(float) - screen2.astype(float)).astype(np.uint8)\n\nerr = np.sum((screen1.astype(float) - screen2.astype(float)) ** 2)\nerr /= float(screen1.shape[0] * screen1.shape[1])\n\nprint(err)\n\n# cat_image = np.concatenate([screen1, screen2, diff], axis=1)\n\n# cv2.imwrite('screeen_cat.png', cat_image)", "sub_path": "test5.py", "file_name": "test5.py", "file_ext": "py", "file_size_in_byte": 488, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "cv2.resize", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "229098520", "text": "from __future__ import print_function, division\n\nimport argparse\nimport os\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nfrom torchvision import datasets, transforms\n\nfrom utils import parse_model_name\nfrom utils import parse_milestones\n\nfrom resnetv2 import ResNetV2\nfrom resnetv2_acc0 import ResNetV2Acc0\nfrom resnetv2_acc1 import ResNetV2Acc1\nfrom resnetv2_acc2 import ResNetV2Acc2\n\nmodel_dict = {\n 'resnetv2': ResNetV2,\n 'resnetv2acc0': ResNetV2Acc0,\n 'resnetv2acc1': ResNetV2Acc1,\n 'resnetv2acc2': ResNetV2Acc2,\n 'resnetv2acc3': ResNetV2Acc3\n}\n\n# Training settings\nparser = argparse.ArgumentParser(description='Accelerated ResNet')\nparser.add_argument('--data-path', type=str, default='/home/x-czh/data_set', metavar='PATH',\n help='data path (default: /home/x-czh/data_set)')\nparser.add_argument('--num-classes', type=int, choices=[10, 100], default=10, metavar='N',\n help='choose between 10/100')\nparser.add_argument('--model', type=str, default='resnetv2-20', metavar='MODEL',\n help='model architecture (default: resnetv2-20)')\nparser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--milestones', type=str, default='0', metavar='M',\n help='milestones to adjust learning rate, ints split by \"-\" (default: \"0\")')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight-decay', type=float, default=1e-4, metavar='W',\n help='weight decay (default: 1e-4)')\nparser.add_argument('--workers', type=int, default=2, metavar='N',\n help='number of data loading workers (default: 2)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--resume', action='store_true', default=False,\n help='resume from latest checkpoint')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n\n# model specific\nparser.add_argument('--final-survival-prob', type=float, default=0.5, metavar='N')\nparser.add_argument('--threshold', type=float, default=0.7, metavar='N')\n\ndef get_data_loader(args):\n kwargs = {'num_workers': args.workers, 'pin_memory': True} if args.cuda else {}\n\n if not os.path.isdir(args.data_path):\n os.makedirs(args.data_path)\n\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.4914, 0.4822, 0.4465),\n std=(0.2023, 0.1994, 0.2010))\n ])\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.4914, 0.4822, 0.4465),\n std=(0.2023, 0.1994, 0.2010))\n ])\n\n if args.num_classes == 10:\n trainset = datasets.CIFAR10(root=args.data_path, train=True,\n transform=transform_train, download=True)\n testset = datasets.CIFAR10(root=args.data_path, train=False,\n transform=transform_test, download=True)\n else:\n trainset = datasets.CIFAR100(root=args.data_path, train=True,\n transform=transform_train, download=True)\n testset = datasets.CIFAR100(root=args.data_path, train=False,\n transform=transform_test, download=True)\n\n train_loader = torch.utils.data.DataLoader(\n dataset=trainset,\n batch_size=args.batch_size,\n shuffle=True,\n **kwargs\n )\n test_loader = torch.utils.data.DataLoader(\n dataset=testset,\n batch_size=args.test_batch_size,\n shuffle=True,\n **kwargs\n )\n\n return train_loader, test_loader\n\ndef get_model(args):\n if args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load('./checkpoint/ckpt.pth')\n model = checkpoint['model']\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n else:\n print('==> Building model..')\n arch, depth = parse_model_name(args.model, model_dict)\n if depth != 0:\n model = model_dict[arch](depth=depth, num_classes=args.num_classes)\n else:\n model = model_dict[arch](num_classes=args.num_classes)\n best_acc = 0\n start_epoch = 1\n\n if args.cuda:\n model.cuda()\n model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n cudnn.benchmark = True\n\n return model, best_acc, start_epoch\n\ndef get_criterion(args):\n criterion = nn.CrossEntropyLoss()\n if args.cuda:\n criterion.cuda()\n return criterion\n\ndef get_optimizer(args, model):\n optimizer = optim.SGD(\n params=model.parameters(),\n lr=args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay\n )\n return optimizer\n\nif __name__ == '__main__':\n args = parser.parse_args()\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n\n # Set the seed for generating random numbers\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n # Set training configurations\n train_loader, test_loader = get_data_loader(args)\n model, best_acc, start_epoch = get_model(args)\n criterion = get_criterion(args)\n optimizer = get_optimizer(args, model)\n lr = args.lr\n milestones = parse_milestones(args.milestones)\n train = model.module.get_train_method() if args.cuda else model.get_train_method()\n\n # Train and record progress\n train(args, train_loader, test_loader, model,\n criterion, optimizer, lr, milestones, best_acc, start_epoch)\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 6742, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "resnetv2.ResNetV2", "line_number": 23, "usage_type": "name"}, {"api_name": "resnetv2_acc0.ResNetV2Acc0", "line_number": 24, "usage_type": "name"}, {"api_name": "resnetv2_acc1.ResNetV2Acc1", "line_number": 25, "usage_type": "name"}, {"api_name": "resnetv2_acc2.ResNetV2Acc2", "line_number": 26, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 71, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 73, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 73, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomCrop", "line_number": 74, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 74, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 75, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 75, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 76, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 76, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 77, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 77, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 80, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 80, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 81, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 81, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 82, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 82, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 87, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 87, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 89, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 89, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 92, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 92, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR100", "line_number": 94, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 97, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 103, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path", "line_number": 116, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 117, "usage_type": "call"}, {"api_name": "utils.parse_model_name", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.nn.DataParallel", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 133, "usage_type": "attribute"}, {"api_name": "torch.cuda.device_count", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 133, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 134, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 134, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 139, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 145, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 155, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 160, "usage_type": "attribute"}, {"api_name": "utils.parse_milestones", "line_number": 168, "usage_type": "call"}]} +{"seq_id": "436413451", "text": "# (C) Copyright IBM Corp. 2019, 2020, 2021, 2022.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom argparse import ArgumentParser\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom simulai.io import Reshaper\nfrom simulai.math.differentiation import CollocationDerivative\nfrom simulai.math.integration import RK4\nfrom simulai.metrics import L2Norm\nfrom simulai.normalization import UnitaryNormalization\nfrom simulai.regression import DenseNetwork\nfrom simulai.rom import POD\nfrom simulai.simulation import Pipeline\n\n\ndef time_nonlinear_system(X, Y, T):\n omega_t = 3 * np.pi\n\n # Generic function U = (x**2)*cos(omega_t*t*y) + (t**2)*x*y\n U = (X**2) * np.cos(omega_t * T * Y) + (T**2) * X * Y\n # Time derivative of U\n U_t = -omega_t * Y * np.sin(omega_t * T * Y) * (X**2) + 2 * T * X * Y\n\n U_nl = -omega_t * Y * np.sin(omega_t * T * Y) * (X**2)\n U_l = 2 * T * X * Y\n\n u_nl_intg = np.linalg.norm(U_nl.flatten(), 2)\n u_intg = np.linalg.norm((U_l + U_nl).flatten(), 2)\n\n print(\n \"Nonlinear contribution ratio to the derivatives: {}\".format(u_nl_intg / u_intg)\n )\n\n return U, U_t\n\n\ndef time_linear_system(X, Y, T):\n lambd = 1\n\n # Generic function U = exp(-lambd*t)*(x**2*cos(y) + x*y)\n U = np.exp(-lambd * T) * (X**2 * np.cos(Y) + X * Y)\n # Time derivative of U\n U_t = -lambd * U\n\n return U, U_t\n\n\nfunction_switcher = {\"linear\": time_linear_system, \"nonlinear\": time_nonlinear_system}\n\n# Reading command-line arguments\nparser = ArgumentParser(description=\"Argument parsers\")\n\nparser.add_argument(\"--save_path\", type=str)\nparser.add_argument(\"--model_name\", type=str)\nparser.add_argument(\"--problem\", type=str)\nparser.add_argument(\"--case\", type=str)\n\nargs = parser.parse_args()\n\n# The file format is not important\n# at this moment. Let us to use simple Numpy files\nsave_path = args.save_path\nmodel_name = args.model_name\nproblem = args.problem\ncase = args.case\n\nsave_path = save_path + \"/\" + model_name + \"/\"\nif not os.path.isdir(save_path):\n os.mkdir(save_path)\n\n# Constructing data\nN = 100\nNt = 5000\n\nx = np.linspace(0, 1, N)\ny = np.linspace(0, 1, N)\nt = np.linspace(0, 1, Nt)\n\nX, T, Y = np.meshgrid(x, t, y)\n\nsystem = function_switcher.get(problem)\n\nU, U_t = system(X, Y, T)\n\ndata = np.core.records.fromarrays([U, U_t], names=\"U, U_t\", formats=\"f8, f8\")[:, None]\n\ndt = 1.0 / Nt\ndt_ = dt\nN_epochs = int(dt / dt_) * int(Nt / 2)\n\nn_batches = data.shape[0]\n# Training data\ntrain_data = data[: int(n_batches / 2), :, :, :]\n# Testing data\ntest_data = data[int(n_batches / 2) :, :, :, :]\n\n# Preparing multiple data arrays\ninput_data = np.core.records.fromarrays([train_data[\"U\"]], names=\"U\", formats=\"f8\")[\n :, None\n]\n\ntarget_data = np.core.records.fromarrays(\n [train_data[\"U_t\"]], names=\"U_t\", formats=\"f8\"\n)[:, None]\n\ntest_input_data = np.core.records.fromarrays([test_data[\"U\"]], names=\"U\", formats=\"f8\")[\n :, None\n]\n\ntest_target_data = np.core.records.fromarrays(\n [test_data[\"U_t\"]], names=\"U_t\", formats=\"f8\"\n)[:, None]\n\n# The initial state is used to execute a time-integrator\n# as will be seen below\ninitial_state = train_data[-1:, :, :, :]\n\n# Configurations\n# Machine learning model configuration\n# Hidden layers only\nif problem == \"linear\":\n architecture = [100, 100, 100, 100]\n\n # Machine learning configuration model\n model_config = {\n \"dropouts_rates_list\": [0, 0],\n \"learning_rate\": 1e-05,\n \"l2_reg\": 1e-06,\n \"activation_function\": \"elu\",\n \"loss_function\": \"mse\",\n \"optimizer\": \"adam\",\n }\n\n # Fitting process configuration\n fit_config = {\n \"n_epochs\": 20000, # Just for testing purposes\n \"use_second_order_opt\": True, # Default is True\n }\n\n # ROM config (in this case, POD)\n rom_config = {\"n_components\": 2}\n\nif problem == \"nonlinear\":\n architecture = [100, 100]\n\n # Machine learning configuration model\n model_config = {\n \"dropouts_rates_list\": [0, 0],\n \"learning_rate\": 1e-05,\n \"l2_reg\": 1e-05,\n \"activation_function\": \"tanh\",\n \"loss_function\": \"mse\",\n \"optimizer\": \"adam\",\n }\n\n # Fitting process configuration\n fit_config = {\n \"n_epochs\": 20000, # Just for testing purposes\n \"use_second_order_opt\": True, # Default is True\n }\n\n # ROM config (in this case, POD)\n rom_config = {\"n_components\": 10}\n\n# Time-integration configuration\nextra_kwargs = {\n \"initial_state\": initial_state,\n \"epochs\": N_epochs,\n \"dt\": dt_,\n \"resolution\": dt,\n}\n\nif case == \"fit\":\n model = DenseNetwork(architecture=architecture, config=model_config)\n\nelif case == \"restore\":\n model = DenseNetwork(architecture=architecture, config=model_config)\n model.restore(save_path, model_name)\n\nelse:\n raise Exception(\n \"It is necessary to provide the way\" \"for obtaining the machine learning model\"\n )\n\n# Derivative operator\ndiff_config = {\"step\": dt}\ndiff_op = CollocationDerivative(config=diff_config)\n\npipeline = Pipeline(\n stages=[\n (\"data_preparer\", Reshaper()),\n (\"rom\", POD(config=rom_config)),\n (\"model\", model),\n ]\n)\n\npipeline.exec(\n data=train_data,\n input_data=input_data,\n reference_data=test_data,\n data_generator=diff_op,\n fit_kwargs=fit_config,\n)\n\nif case == \"fit\":\n pipeline.save(save_path=save_path, model_name=model_name)\n\nestimated_target_data = pipeline.eval(data=test_input_data)\n\noutput = pipeline.predict(post_process_op=RK4, extra_kwargs=extra_kwargs)\n\nl2_norm = L2Norm()\nerror_target = l2_norm(\n data=estimated_target_data,\n reference_data=test_target_data[\"U_t\"],\n relative_norm=True,\n)\n\nerror_nominal_list = list()\nfor ii in range(output.shape[0]):\n error_nominal = l2_norm(\n data=output[ii, :, :, :],\n reference_data=test_input_data[\"U\"][ii, :, :, :],\n relative_norm=True,\n )\n\n error_nominal_list.append(error_nominal)\n\nerror_nominal = l2_norm(\n data=output, reference_data=test_input_data[\"U\"], relative_norm=True\n)\n\nprint(\"Evaluation error: {} %\".format(error_target * 100))\nprint(\"Evaluation error: {} %\".format(error_nominal * 100))\n\nplt.plot(list(range(len(error_nominal_list))), error_nominal_list)\nplt.savefig(save_path + \"error_curve.png\")\nplt.close()\n\nplt.imshow(output[-1, 0, :, :])\nplt.colorbar()\nplt.savefig(save_path + \"solution_estimated.png\")\nplt.close()\n\nplt.imshow(test_data[\"U\"][-1, 0, :, :])\nplt.colorbar()\nplt.savefig(save_path + \"solution_expected.png\")\nplt.close()\n\nplt.imshow(estimated_target_data[-1, 0, 0, :, :])\nplt.colorbar()\nplt.savefig(save_path + \"derivative_estimated.png\")\nplt.close()\n\nplt.imshow(test_target_data[\"U_t\"][-1, 0, 0, :, :])\nplt.colorbar()\nplt.savefig(save_path + \"derivative_expected.png\")\nplt.close()\n", "sub_path": "examples/Pipeline/test_derivative_pipeline_romy_predict.py", "file_name": "test_derivative_pipeline_romy_predict.py", "file_ext": "py", "file_size_in_byte": 7265, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "numpy.pi", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 43, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 56, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.core.records.fromarrays", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 100, "usage_type": "attribute"}, {"api_name": "numpy.core.records.fromarrays", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 113, "usage_type": "attribute"}, {"api_name": "numpy.core.records.fromarrays", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 117, "usage_type": "attribute"}, {"api_name": "numpy.core.records.fromarrays", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 121, "usage_type": "attribute"}, {"api_name": "numpy.core.records.fromarrays", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 125, "usage_type": "attribute"}, {"api_name": "simulai.regression.DenseNetwork", "line_number": 189, "usage_type": "call"}, {"api_name": "simulai.regression.DenseNetwork", "line_number": 192, "usage_type": "call"}, {"api_name": "simulai.math.differentiation.CollocationDerivative", "line_number": 202, "usage_type": "call"}, {"api_name": "simulai.simulation.Pipeline", "line_number": 204, "usage_type": "call"}, {"api_name": "simulai.io.Reshaper", "line_number": 206, "usage_type": "call"}, {"api_name": "simulai.rom.POD", "line_number": 207, "usage_type": "call"}, {"api_name": "simulai.math.integration.RK4", "line_number": 225, "usage_type": "name"}, {"api_name": "simulai.metrics.L2Norm", "line_number": 227, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 251, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 253, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 253, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 260, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 261, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 261, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 263, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 263, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 267, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 267, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 268, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 268, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 271, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}]} +{"seq_id": "214475267", "text": "from django.conf import settings\nfrom django.http import QueryDict\nfrom models import Session\nfrom django.http import HttpResponseNotFound\n\nclass urlBaseMiddleware(object):\n\n def process_request(self, request):\n session_id = request.GET.get('phonenumber', False)\n service_id = request.GET.get('service', False) #step 1 ashkan\n\n if session_id:\n\n if service_id and int(service_id) not in range(1,4):\n return HttpResponseNotFound(\"Invalid servcieId!\") #step-3 ashkan\n elif not service_id :\n return HttpResponseNotFound(\"service_id is empty\") #step-4 ashkan\n\n session, create = Session.objects.get_or_create(session_id=session_id,serviceid = int(service_id ))\n\n else:\n session = None\n\n request.urlsession = session\n request.urlserviceid = service_id #step 5 ashkan\n", "sub_path": "session/middleware.py", "file_name": "middleware.py", "file_ext": "py", "file_size_in_byte": 883, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.http.HttpResponseNotFound", "line_number": 15, "usage_type": "call"}, {"api_name": "django.http.HttpResponseNotFound", "line_number": 17, "usage_type": "call"}, {"api_name": "models.Session.objects.get_or_create", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Session.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "models.Session", "line_number": 19, "usage_type": "name"}]} +{"seq_id": "630293574", "text": "import random\n\nfrom wellcomeml.utils import throw_extra_import_message\n\nrequired_modules = 'spacy,nervaluate'\nrequired_extras = 'spacy,core'\n\ntry:\n from spacy.training import Example\n import spacy\n from nervaluate import Evaluator\nexcept ImportError as e:\n throw_extra_import_message(error=e, required_modules=required_modules, extras=required_extras)\n\n\nclass SpacyNER:\n \"\"\"\n Train a spaCy NER classifier on texts annotated using Prodigy\n \"\"\"\n\n def __init__(self, n_iter=20, dropout=0.2, output=True):\n\n self.n_iter = n_iter\n self.dropout = dropout\n self.output = output\n\n def fit(self, X, y):\n \"\"\"\n X: a list of sentences,\n e.g. ['Professor Smith said', 'authors Smith and Chen found']\n y: a list of prodigy format spans for each element of X,\n e.g. [{'start': 10, 'end': 15, 'label': 'PERSON'},\n {'start': 8, 'end': 13, 'label': 'PERSON'},\n {'start':18, 'end':22, 'label':'PERSON'}]\n \"\"\"\n\n train_data = list(zip(X, y))\n\n if \"ner\" not in self.nlp_model.pipe_names:\n # If you are training on a blank model\n ner = self.nlp_model.add_pipe(\"ner\")\n self.nlp_model.add_pipe(ner, last=True)\n else:\n ner = self.nlp_model.get_pipe(\"ner\")\n\n # add labels from data\n\n for spans in y:\n for span in spans:\n ner.add_label(span[\"label\"])\n\n examples = []\n for text, spans in train_data:\n annotations = self._spans_to_entities(spans)\n doc = self.nlp_model.make_doc(text)\n example = Example.from_dict(doc, annotations)\n examples.append(example)\n\n other_pipes = [pipe for pipe in self.nlp_model.pipe_names if pipe != \"ner\"]\n with self.nlp_model.select_pipes(disable=other_pipes): # only train NER\n optimizer = self.nlp_model.initialize(lambda: examples)\n\n for i in range(self.n_iter):\n random.shuffle(train_data)\n losses = {}\n\n for example in examples:\n self.nlp_model.update(\n [example],\n sgd=optimizer,\n losses=losses,\n drop=self.dropout,\n )\n\n if self.output:\n self._print_output(i, losses[\"ner\"])\n\n return self.nlp_model\n\n def _print_output(self, batch_i, loss):\n\n dash = \"-\" * 15\n\n if batch_i == 0:\n print(dash)\n print(\"{:8s}{:13s}\".format(\"BATCH |\", \"LOSS\"))\n print(dash)\n print(\"{:<8d}{:<10.2f}\".format(batch_i, loss))\n\n def predict(self, text):\n \"\"\"\n Get entity predictions for a piece of text\n \"\"\"\n\n doc = self.nlp_model(text)\n pred_entities = []\n\n for ent in doc.ents:\n pred_entities.append(\n {\"start\": ent.start_char, \"end\": ent.end_char, \"label\": ent.label_}\n )\n\n return pred_entities\n\n def score(self, y_true, y_pred, tags):\n \"\"\"\n Evaluate the model's performance on the data\n for entity types in the 'tags' list, e.g. ['PERSON', 'LOC']\n \"\"\"\n\n evaluator = Evaluator(y_true, y_pred, tags=tags)\n results, results_by_tag = evaluator.evaluate()\n\n score = {tag: results_by_tag[tag][\"partial\"][\"f1\"] for tag in tags}\n score[\"Overall\"] = results[\"partial\"][\"f1\"]\n return score\n\n def save(self, file_name):\n\n self.nlp_model.to_disk(file_name)\n\n def load(self, model=None):\n \"\"\"\n model:\n The model's location ('models/model')\n or the name of a spaCy model (\"en_core_web_sm\")\n None (default): Then load a blank spacy english model\n \"\"\"\n\n if model:\n self.nlp_model = spacy.load(model)\n else:\n self.nlp_model = spacy.blank(\"en\")\n\n def _spans_to_entities(self, spans):\n \"\"\"\n Convert prodigy spans to spacy entities\n\n from:\n\n ```\n [\n {'start': 36, 'end': 46, 'label': 'PERSON'},\n {'start': 48, 'end': 58, 'label': 'PERSON'},\n {'start': 61, 'end': 69, 'label': 'PERSON'},\n ]\n ```\n\n to:\n\n ```\n {\n 'entities': [\n (36, 46, 'PERSON'),\n (48, 58, 'PERSON'),\n (61, 69, 'PERSON'),\n ]\n }\n ```\n \"\"\"\n\n entities = []\n\n for span in spans:\n entities.append((span[\"start\"], span[\"end\"], span[\"label\"]))\n\n return {\"entities\": entities}\n", "sub_path": "wellcomeml/ml/spacy_ner.py", "file_name": "spacy_ner.py", "file_ext": "py", "file_size_in_byte": 4703, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "wellcomeml.utils.throw_extra_import_message", "line_number": 13, "usage_type": "call"}, {"api_name": "spacy.training.Example.from_dict", "line_number": 56, "usage_type": "call"}, {"api_name": "spacy.training.Example", "line_number": 56, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 64, "usage_type": "call"}, {"api_name": "nervaluate.Evaluator", "line_number": 111, "usage_type": "call"}, {"api_name": "spacy.load", "line_number": 131, "usage_type": "call"}, {"api_name": "spacy.blank", "line_number": 133, "usage_type": "call"}]} +{"seq_id": "89849127", "text": "# -*- coding: utf-8 -*-\n__author__ = 'songbowen'\nimport json\n\nimport sqlalchemy.orm.exc\n\nfrom handler.BaseHandler import BaseHandler\nfrom lib.models import CloudControlIp, CloudControlUrl, CloudControlVfm, CloudControlRule\n\n\nclass CloudControlParamHandler(BaseHandler):\n \"\"\" Interface use to GET/POST cloud control params\n \"\"\"\n def get(self, param, *args, **kwargs):\n param = param.lower()\n if param == \"url\":\n results = self.session.query(CloudControlUrl.name, CloudControlUrl.value).order_by(CloudControlUrl.id).all()\n elif param == \"vfm\":\n results = self.session.query(CloudControlVfm.name, CloudControlVfm.value).order_by(CloudControlVfm.id).all()\n elif param == \"ip\":\n results = self.session.query(CloudControlIp.name, CloudControlIp.value).order_by(CloudControlIp.id).all()\n elif param == \"rule\":\n code = self.get_argument(\"code\", None)\n if not code:\n return self.write(json.dumps([]))\n try:\n record = self.session.query(CloudControlRule).filter(CloudControlRule.id == int(code)).one()\n results = []\n if record.url is not None:\n results += map(lambda ele: \"video-\"+ele, record.url.split(\",\"))\n if record.vfm is not None:\n results += map(lambda ele: \"vfm-\"+ele, record.vfm.split(\",\"))\n if record.ip is not None:\n results += map(lambda ele: \"ip-\"+ele, record.ip.split(\",\"))\n if record.ua is not None:\n results += map(lambda ele: \"ua-\"+ele, record.ua.split(\",\"))\n except sqlalchemy.orm.exc.NoResultFound:\n return self.write(\"rule {0} not found\".format(code))\n except sqlalchemy.orm.exc.MultipleResultsFound:\n return self.write(\"multiple rule {0} found\".format(code))\n else:\n return self.write(\"{0} not supported yet\".format(param))\n\n return self.write(json.dumps(results))\n\n def post(self, param, *args, **kwargs):\n param = param.lower()\n if param != \"rule\":\n new_name = self.get_argument(\"name-new\").strip()\n new_value = self.get_argument(\"value-new\").strip()\n\n if param == \"url\":\n records = self.session.query(CloudControlUrl).order_by(CloudControlUrl.id).all()\n if new_name and new_value:\n new_record = CloudControlUrl(\n name=new_name,\n value=new_value\n )\n elif param == \"vfm\":\n records = self.session.query(CloudControlVfm).order_by(CloudControlVfm.id).all()\n if new_name and new_value:\n new_record = CloudControlVfm(\n name=new_name,\n value=new_value\n )\n elif param == \"ip\":\n records = self.session.query(CloudControlIp).order_by(CloudControlIp.id).all()\n if new_name and new_value:\n new_record = CloudControlIp(\n name=new_name,\n value=new_value\n )\n elif param == \"rule\":\n code = self.get_argument(\"code\", \"\")\n data = self.get_argument(\"data\", \"\")\n if not code:\n return self.write(\"{code} needed!\")\n if not data:\n return self.write(\"ok\")\n\n try:\n record = self.session.query(CloudControlRule).filter(CloudControlRule.code == int(code)).one()\n params = data.split(\",\")\n video = []\n vfm = []\n ua = []\n ip = []\n for param in params:\n key, value = param.split(\"-\")\n if key == \"video\":\n video.append(value)\n elif key == \"vfm\":\n vfm.append(value)\n elif key == \"ua\":\n ua.append(value)\n elif key == \"ip\":\n ip.append(value)\n else:\n break\n record.url = \",\".join(video)\n record.vfm = \",\".join(vfm)\n record.ua = \",\".join(ua)\n record.ip = \",\".join(ip)\n self.session.commit()\n return self.write(\"ok\")\n except sqlalchemy.orm.exc.NoResultFound:\n return self.write(\"code {0} not found!\".format(code))\n except sqlalchemy.orm.exc.MultipleResultsFound:\n return self.write(\"many code {0} found\".format(code))\n else:\n return self.write(\"{0} not supported yet!\".format(param))\n\n for i in range(len(records)):\n records[i].name = self.get_argument(\"name-{0}\".format(i+1))\n records[i].value = self.get_argument(\"value-{0}\".format(i+1))\n\n try:\n self.session.add(new_record)\n except UnboundLocalError:\n # no new record\n pass\n\n self.session.commit()\n return self.write(\"ok\")\n", "sub_path": "handler/interface/CloudControlInterfaceHandler.py", "file_name": "CloudControlInterfaceHandler.py", "file_ext": "py", "file_size_in_byte": 5126, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "handler.BaseHandler.BaseHandler", "line_number": 11, "usage_type": "name"}, {"api_name": "lib.models.CloudControlUrl.name", "line_number": 17, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlUrl", "line_number": 17, "usage_type": "name"}, {"api_name": "lib.models.CloudControlUrl.value", "line_number": 17, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlUrl.id", "line_number": 17, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlVfm.name", "line_number": 19, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlVfm", "line_number": 19, "usage_type": "name"}, {"api_name": "lib.models.CloudControlVfm.value", "line_number": 19, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlVfm.id", "line_number": 19, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlIp.name", "line_number": 21, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlIp", "line_number": 21, "usage_type": "name"}, {"api_name": "lib.models.CloudControlIp.value", "line_number": 21, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlIp.id", "line_number": 21, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}, {"api_name": "lib.models.CloudControlRule", "line_number": 27, "usage_type": "argument"}, {"api_name": "lib.models.CloudControlRule.id", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc.orm", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc", "line_number": 37, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.exc.orm", "line_number": 39, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc", "line_number": 39, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 44, "usage_type": "call"}, {"api_name": "lib.models.CloudControlUrl", "line_number": 53, "usage_type": "argument"}, {"api_name": "lib.models.CloudControlUrl.id", "line_number": 53, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlUrl", "line_number": 55, "usage_type": "call"}, {"api_name": "lib.models.CloudControlVfm", "line_number": 60, "usage_type": "argument"}, {"api_name": "lib.models.CloudControlVfm.id", "line_number": 60, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlVfm", "line_number": 62, "usage_type": "call"}, {"api_name": "lib.models.CloudControlIp", "line_number": 67, "usage_type": "argument"}, {"api_name": "lib.models.CloudControlIp.id", "line_number": 67, "usage_type": "attribute"}, {"api_name": "lib.models.CloudControlIp", "line_number": 69, "usage_type": "call"}, {"api_name": "lib.models.CloudControlRule", "line_number": 82, "usage_type": "argument"}, {"api_name": "lib.models.CloudControlRule.code", "line_number": 82, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc.orm", "line_number": 106, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc", "line_number": 106, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.exc.orm", "line_number": 108, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.exc", "line_number": 108, "usage_type": "name"}]} +{"seq_id": "261412610", "text": "from django.urls import path\nfrom .views import *\n\nurlpatterns =[\n path('income-category', income_category, name='income-category'),\n path('income-category-detail/', income_category_detail, name='income-category-detail'),\n path('income',incomeListView, name='income'),\n path('income-list-detail/',income_list_detail , name='income-list-detail'),\n path('expense-category', expense_category, name='expense-category'),\n path('expense-category-detail/', expense_category_detail, name='expense-category-detail'),\n path('expense', expense_list_view, name='expense'),\n path('expense-list-detail/',expense_list_detail , name='expense-list-detail'),\n path('income-summary',income_summary, name='income-summary'),\n path('expense-summary', expense_summary,name='expense-summary'),\n\n]", "sub_path": "tracker/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 834, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "67510596", "text": "#!/usr/bin/env python2\n# encoding: utf-8\n# @Auther : yjz\n# @File : parser.py\n# @Time : 2020/2/3 15:14\n# @Version : 0.1\n# @Function : 解析函数\n\nimport re\nfrom bs4 import BeautifulSoup\n\n\ndef getProblemset(contents):\n '''\n\n :param contents: 需要解析的问题页面内容\n :return:list,[id,问题名称,已提交次数,通过次数,总提交次数]\n '''\n pattern = re.compile('p\\((.*?)\\);')\n problems = pattern.findall(contents.decode('gb2312'))[1:]\n data = []\n for i in problems:\n i = i.replace(\"\\\\\", '')\n temp = i.split(',')\n if len(temp) != 6:\n for j in range(len(temp) - 6):\n temp[3] += ' ' + temp.pop(4)\n temp.pop(0)\n data.append(temp)\n return data\n\n\ndef getProblem(contents):\n '''\n\n :param contents: 需要解析的详细问题页面内容,采用bs4解析\n :return:list,[问题描述,问题输入,问题输出,样例输入,样例输出]\n '''\n contents = BeautifulSoup(contents, 'lxml')\n content = contents.findAll(class_='panel_content')\n return [content[0].text, content[1].text, content[2].text, content[3].text, content[4].text]\n\n\ndef getStatus(contents):\n '''\n\n :param contents: 状态页面返回的内容\n :return:状态list\n '''\n contents = BeautifulSoup(contents, 'lxml')\n contents = contents.findAll(class_='table_text')[0]\n status = contents.findAll('td')\n data=[]\n temp=[]\n for i in range(len(status)):\n if i % 9 ==0:\n data.append(temp)\n temp=[]\n temp.append(status[i].text)\n data.pop(0)\n return data\n\n", "sub_path": "Parser/parser.py", "file_name": "parser.py", "file_ext": "py", "file_size_in_byte": 1654, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "re.compile", "line_number": 19, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 39, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "46532500", "text": "from buylist.models import SkuLight\nfrom engine.tcgplayer import create_tcg_buylist, TcgPlayerApi\nfrom.models import ReleasedProducts\nfrom datetime import date\nfrom .fix_words import FixWords\n\nfix = FixWords()\n\nclass GetCards:\n sku_light = SkuLight.objects\n tcg = TcgPlayerApi()\n def buylist_by_name(self, card_name):\n sku = self.sku_light.filter(name=card_name)\n if not sku.exists():\n return 'error'\n else:\n m = []\n for card in sku:\n msg = (\"{}\\n({})\\n${}\\n\\n\".format(card.name, card.expansion, create_tcg_buylist(card.sku)))\n m.append(msg)\n m = ','.join(m)\n results = \"TcgPlayer Buylist Updated\\n\\n\" + m\n return results\n\n\n def buylist_by_name_and_set(self, card_set, card_name):\n sku = self.sku_light.filter(expansion=card_set).filter(name=card_name)\n if not sku.exists():\n return 'error'\n else:\n m = []\n for card in sku:\n msg = (\"{}\\n({})\\n${}\\n\\n\".format(card.name, card.expansion, create_tcg_buylist(card.sku)))\n m.append(msg)\n m = ','.join(m)\n results = \"TcgPlayer Buylist Updated\\n\\n\" + m\n return results\n\n def search_by_name_and_set(self, card_name, card_set):\n sku = self.sku_light.filter(expansion=card_set).filter(name=card_name)\n if not sku.exists():\n return 'error'\n else:\n m = []\n for card in sku:\n inventory = self.tcg.search_inventory(self.tcg.card_info_by_sku(card.sku)['results'][0]['productId'])['results'][0][\n 'totalQuantity']\n msg = (\"{}\\n({})\\nQuantity: {}\\n\\n\".format(card.name, card.expansion, inventory))\n m.append(msg)\n m = ','.join(m)\n results = \"Online Inventory: \\n\\n\" + m\n return results\n\n\n def search_by_name(self, card_name):\n sku = self.sku_light.filter(name=card_name)\n if not sku.exists():\n return 'error'\n else:\n m = []\n for card in sku:\n inventory = self.tcg.search_inventory(self.tcg.card_info_by_sku(card.sku)['results'][0]['productId'])['results'][0][\n 'totalQuantity']\n msg = (\"{}\\n({})\\nQuantity: {}\\n\\n\".format(card.name, card.expansion, inventory))\n m.append(msg)\n m = ','.join(m)\n results = \"Online Inventory: \\n\\n\" + m\n return results\n\n\n\nclass GetProducts:\n products = ReleasedProducts.objects\n month_dictionary = {\n 'jan': 'january',\n 'feb': 'february',\n 'mar': 'march',\n 'apr': 'april',\n 'may': 'may',\n 'jun': 'june',\n 'jul': 'july',\n 'aug': 'august',\n 'sep': 'september',\n 'oct': 'october',\n 'nov': 'november',\n 'dec': 'december',\n 'january': 'january',\n 'february': 'february',\n 'march': 'march',\n 'april': 'april',\n 'june': 'june',\n 'july': 'july',\n 'august': 'august',\n 'september': 'september',\n 'october': 'october',\n 'november': 'november',\n 'december': 'december',\n\n }\n\n\n def by_month(self, month, year=date.today().year):\n try:\n _month = self.month_dictionary[month]\n products_by_month = self.products.filter(month=self.month_dictionary[_month]).filter(year=year)\n\n if not products_by_month.exists():\n print(\"THIS\", _month)\n if fix.month_to_integer(_month) < date.today().month:\n if int(year) <= date.today().year + 1 and int(year) > 1993:\n results_list = []\n last_year_results = self.products.filter(month=self.month_dictionary[_month]).filter(\n year=(str(int(year) - 1)))\n for each in last_year_results:\n results = \"{}\\n\" \\\n \"MSRP: {}\\n\" \\\n \"Released: {}\\n\\n\".format(each.product, each.price, each.release_date)\n results_list.append(results)\n results_list = ','.join(results_list)\n return \"Last Year's Products:\\n\\n{}\".format(results_list)\n else:\n return \"No Products in database for that year\"\n\n else:\n return \"No Results for products in {}/{}\".format(_month, year)\n\n else:\n results_list = []\n for each in products_by_month:\n results = \"{}\\n\" \\\n \"MSRP: {}\\n\" \\\n \"Released: {}\\n\\n\".format(each.product, each.price, each.release_date)\n results_list.append(results)\n results_list = ','.join(results_list)\n return \"Products\\n\\n{}\".format(results_list)\n\n except KeyError:\n return 'Incorrect format/spelling for month. Must be like \"jan\" or \"january\" '\n\n def upcoming(self):\n products = self.products.all()\n results_list = []\n for each in products:\n if fix.month_to_integer(each.month.lower()) >= date.today().month and fix.month_to_integer(each.month.lower()) < date.today().month + 2:\n results_list.append(\n \"{}\\n\" \\\n \"MSRP: {}\\n\" \\\n \"Released: {}\\n\\n\".format(each.product, each.price, each.release_date)\n )\n\n results_list = ','.join(results_list)\n return \"Upcoming Products\\n\\n{}\".format(results_list)\n\n\n\n\n\n\n\n\n", "sub_path": "customer/query.py", "file_name": "query.py", "file_ext": "py", "file_size_in_byte": 5751, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "fix_words.FixWords", "line_number": 7, "usage_type": "call"}, {"api_name": "buylist.models.SkuLight.objects", "line_number": 10, "usage_type": "attribute"}, {"api_name": "buylist.models.SkuLight", "line_number": 10, "usage_type": "name"}, {"api_name": "engine.tcgplayer.TcgPlayerApi", "line_number": 11, "usage_type": "call"}, {"api_name": "engine.tcgplayer.create_tcg_buylist", "line_number": 19, "usage_type": "call"}, {"api_name": "engine.tcgplayer.create_tcg_buylist", "line_number": 33, "usage_type": "call"}, {"api_name": "models.ReleasedProducts.objects", "line_number": 73, "usage_type": "attribute"}, {"api_name": "models.ReleasedProducts", "line_number": 73, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 102, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 102, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 109, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 110, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 110, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 144, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 144, "usage_type": "name"}]} +{"seq_id": "192938711", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of INSPIRE.\n# Copyright (C) 2016 CERN.\n#\n# INSPIRE 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# INSPIRE 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 INSPIRE. If not, see .\n#\n# In applying this license, CERN does not waive the privileges and immunities\n# granted to it by virtue of its status as an Intergovernmental Organization\n# or submit itself to any jurisdiction.\n\n\"\"\"Tests for Impact Graph API.\"\"\"\n\nimport json\n\n\ndef test_impact_graphs_api(app):\n \"\"\"Test response of impact graph API.\"\"\"\n with app.test_client() as client:\n result = client.get(\n \"/api/literature/613135\",\n headers={\"Accept\": \"application/x-impact.graph+json\"}\n )\n\n result = json.loads(result.data)\n assert result['title'] == u'First year Wilkinson Microwave Anisotropy Probe (WMAP) observations: Determination of cosmological parameters'\n assert result['year'] == u'2003'\n assert len(result['citations']) == 14\n", "sub_path": "tests/integration/test_impact_graphs.py", "file_name": "test_impact_graphs.py", "file_ext": "py", "file_size_in_byte": 1487, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "json.loads", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "308934001", "text": "# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nfrom PIL import Image\nfrom sklearn.datasets import fetch_mldata\nfrom function import *\nfrom mlp_without_bias import * # バイアス項なし\n# from mlp_with_bias import * #バイアス項あり\n\ndef main():\n print(datetime.datetime.now())\n\n # パラメータ設定\n image_width = 28 # 画像の横サイズ\n image_height = 28 # 画像の縦サイズ\n n_h = 300 # 中間層のニューロン数\n eta = 0.1 # 学習率\n iteration = 3000 # 学習回数\n rep = 100 # 学習表示のインターバル\n coeff = 0.1 # 重み初期値(一様分布 -1 to +1)に掛かる係数\n tr = 30000 # Num of train data\n ts = 10000 # Num of test data\n # trとtsの合計値が70000以下となるように設定\n\n # ネットワーク構築\n layers = np.array([image_height*image_width, n_h, 10]) # ニューロン数設定\n act = np.array(['sigmoid','sigmoid']) # 活性化関数設定\n ml = MultiLayer(layers, coeff) # インスタンス化\n print(\"* BUILDING MLP *\")\n print(\"# of NEURONS: {} - {} - 10\".format(image_height*image_width, n_h))\n print(\"ACTIVATION: (in-hidden){} (hidden-out){}\".format(act[0], act[1]))\n print(\"\")\n\n print(\"* TRAINING PARAM *\")\n print(\"LEARNING RATE: {}\".format(eta))\n print(\"MAX ITERATION: {}\".format(iteration))\n print(\"\")\n\n print(\"* IMAGE PARAM *\")\n print(\"ORIGINAL SIZE (W x H): 28 x 28\")\n print(\"AFTER RESIZING (W x H): {} x {}\".format(image_width, image_height))\n print(\"# of IMAGE for TRAIN: {}\".format(tr))\n print(\"# of IMAGE for TEST: {}\".format(ts))\n print(\"\")\n\n # MNISTデータセットをダウンロード\n print(\"* DOWNLOAD MNIST DATASET (if not exists) *\")\n print(\"\")\n mnist = fetch_mldata('MNIST original', data_home=\".\")\n\n print(\"* PRE-PROCESS MNIST DATASET *\")\n print(\"\")\n # train data (MNIST)\n p = np.random.randint(0, tr, tr) # 学習用画像のインデックスを生成\n X_origin = np.array( bit(mnist.data[p]/255.0) ) # 画像正規化\n X_3d = np.reshape(X_origin, [tr, 28, 28]) # 28x28の2D形式へ変換\n X_3d = [Image.fromarray(i) for i in X_3d] # 画像データへ変換\n X_resize = [i.resize((image_width, image_height)) for i in X_3d] # リサイズ\n X_resize = [np.asarray(i) for i in X_resize] # numpy形式へ変換\n X_resize = np.reshape(X_resize, [tr, image_width*image_height]) # 2Dから1Dへ変換\n y_origin = np.array( mnist.target[p] ) # 整数の教師データ(0-9)\n y_list = y_origin.tolist() # numpy配列をlist化\n y_int = [int(i) for i in y_list] # 各要素をintに変換\n y = np.eye(10)[y_int] # one-hot表現に変換\n\n X_train_origin = X_origin\n X_train = X_resize\n y_train = y\n\n # test data (MNIST)\n p = np.random.randint(tr, tr+ts, ts) # テスト用画像のインデックスを生成\n X_origin = np.array( bit(mnist.data[p]/255.0) ) # 画像正規化\n X_3d = np.reshape(X_origin, [ts, 28, 28]) # 28x28の2D形式へ変換\n X_3d = [Image.fromarray(i) for i in X_3d] # 画像データへ変換\n X_resize = [i.resize((image_width, image_height)) for i in X_3d] # リサイズ\n X_resize = [np.asarray(i) for i in X_resize] # numpy形式へ変換\n X_resize = np.reshape(X_resize, [ts, image_width*image_height]) # 2Dから1Dへ変換\n y_origin = np.array( mnist.target[p] ) # 整数の教師データ(0-9)\n y_list = y_origin.tolist() # numpy配列をlist化\n y_int = [int(i) for i in y_list] # 各要素をintに変換\n y = np.eye(10)[y_int] # one-hot表現に変換\n\n X_test_origin = X_origin\n X_test = X_resize\n y_test = y\n\n print(\"* VISUALIZE MNIST IMAGE *\")\n # 学習用画像の最初の10枚を可視化\n plt.figure(figsize = (20, 4)) # 描画ウィンドウのサイズ\n for i in range(10):\n # オリジナルの28x28画像を1行目に描画\n ax = plt.subplot(2, 10, i+1) # 描画位置設定\n plt.title('28x28') # 各画像のタイトル\n plt.imshow(X_train_origin[i].reshape(28, 28)) # 2D画像に変換して描画\n plt.gray() # グレースケールで描画\n ax.get_xaxis().set_visible(False) # X軸不可視化\n ax.get_yaxis().set_visible(False) # Y軸不可視化\n xlim = ax.get_xlim() # X軸の範囲を取得\n ylim = ax.get_ylim() # Y軸の範囲を取得\n \n # リサイズ後の画像を2行目に描画\n ax = plt.subplot(2, 10, i+11) # 描画位置設定\n plt.title('%dx%d' % (image_width, image_height)) # 各画像のタイトル\n plt.imshow(X_train[i].reshape(image_height, image_width)) # 2D画像に変換して描画\n plt.gray() # グレースケールで描画\n ax.get_xaxis().set_visible(False) # X軸不可視化\n ax.get_yaxis().set_visible(False) # Y軸不可視化\n ### 描画されたリサイズ画像のセンタリング処理\n x_left = xlim[0] - (28.0 - image_width) / 2.0\n x_right = x_left + 28.0\n y_top = ylim[1] - (28.0 - image_height) / 2.0\n y_bottom = y_top + 28.0\n ax.set_xlim(x_left, x_right)\n ax.set_ylim(y_bottom, y_top)\n\n print(\"save mnist.png\")\n print(\"\")\n plt.savefig('mnist.png') # 画像をpng形式で保存\n # plt.show() # ウィンドウでも表示\n\n # train\n # plt.show()で画像ウィンドウを表示させた場合は、\n # 画像ウィンドウを閉じると学習が開始される\n print(\"* START TRAINING *\")\n ml.fit(X_train, y_train, act, eta, iteration, rep)\n \n # test\n result_x = np.array(X_test) # listからnumpy配列に変換\n result_y = np.array(y_test) # listからnumpy配列に変換\n\n correct_n = 0\n print(\"* START TEST *\")\n print(result_x.shape[0])\n for l in range(0,result_x.shape[0]):\n if all( result_y[l] == ml.result(result_x[l],act) ):\n correct_n += 1\n\n per = float( 100.0 * correct_n / ts )\n print(\"ACCURACY: {} %\".format(per))\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 6064, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.datasets.fetch_mldata", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 57, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 58, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 58, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 74, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 75, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 75, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gray", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gray", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 130, "usage_type": "call"}]} +{"seq_id": "515393549", "text": "#!/usr/bin/env python\n# author ejrbuss\nimport os\ntry:\n import tqdm\nexcept:\n notqdm = True;\nimport shutil\nimport random\n\nimport simgit.report as report\n\nfrom simgit.log import log\nfrom simgit.git import git\nfrom simgit.asset import asset\nfrom simgit.program import program\n\ndef response(message):\n \"\"\"\n Helper function returns true if the user responded in the affirmative to\n the query specified by `message`.\n \"\"\"\n return input(message).lower() in ['y', 'yes']\n\ndef dirStat(path):\n \"\"\"\n Finds the size of a directory\n \"\"\"\n size = 0\n files = 0\n try:\n for entry in scanner(path):\n if entry.is_dir(follow_symlinks=False):\n sizer, filesr = dirStat(entry.path)\n if '.git' not in entry.path:\n files += filesr\n size += sizer\n else:\n files += 1\n size += entry.stat(follow_symlinks=False).st_size\n except:\n for dirpath, dirnames, filenames in os.walk(path):\n for d in dirnames:\n if '.git' not in d:\n sizer, filesr = dirStat(os.path.join(dirpath, d))\n files += filesr\n size += sizer\n for f in filenames:\n files += 1\n size += os.path.getsize(os.path.join(dirpath, f))\n return size, files\n\nclass simgit(object):\n \"\"\"\n The simgit object is acts as the API for simgit. See its methods and\n submodels for usage details.\n \"\"\"\n\n def __init__(self, configFn, simDir, quiet=False):\n \"\"\"\n `simgit(configFn, simDir, quiet=False)`\n\n `configFn` is a function that recieves this instance only if this\n instance is in a valid state. `simDir` is the directory to run the\n simulation in. The quiet option should be set to `True` for less output.\n\n The simulation has the following file structure:\n simDir/\n |--repository/ # Where changes and git commands are run\n |--common/ # Where \"common\" programs are stored\n |--project#/ # Where \"project\" programs are stored\n |--benchmarks/ # Where benchmarking data is streamed\n |--reports/ # Where reports are saved\n |--simgit.log # Where the simgit log is streamed to\n\n This function does some work.\n - initialize sub modules\n - initialzie benchmark configuration\n - resolve simulation directory\n - ensure correct file structure\n - ensure alid configuration\n - run configFn\n \"\"\"\n\n # sub components\n self.repo = {} # store metadata dependent on branches\n self.meta = {} # store metadata independent on branches\n self.quiet = quiet\n self.log = log()\n self.git = git(self)\n self.asset = asset(self)\n self.program = program(self)\n\n # benchmark configuration\n self.benchmarks = dict(\n branch=False,\n commit=False,\n status=False,\n log =False\n )\n\n # indicates if the simgit is in a valid state\n self.valid = False\n # Copy of the initialization cwd\n self.cwd = os.getcwd()\n\n # resolve directory\n if os.path.isfile(simDir):\n if response('Sim directory \"{}\" is a file. Continuing will delete it. Continue anyway? (y/n)'.format(simDir)):\n os.remove(simDir)\n if os.path.isdir(simDir):\n if not response('Sim directory \"{}\" already exists. Try to recover old sim? (y/n)'.format(simDir)):\n try:\n shutil.rmtree(simDir)\n except Exception as _:\n if response('Sim directory could not be deleted. Use temporary name? (y/n)'):\n for counter in range(100):\n if not os.path.exists(simDir + str(counter)):\n simDir = simDir + str(counter)\n break\n else:\n print('Could not find a valid temporary name. Giving up.')\n\n # not trying to recover old sim, safe to generate file structure\n if not os.path.exists(simDir):\n os.makedirs(simDir)\n os.chdir(simDir)\n os.makedirs(os.path.join('repository', 'common'))\n os.makedirs('benchmarks')\n os.makedirs('reports')\n with open(os.path.join('repository', 'common', 'gitnotignore.txt'), 'w') as file:\n file.write('Created to prevent git from ignoring directory.')\n self.git('init')\n self.log.clear()\n self.valid = True\n # try to recover using metadata\n elif os.path.isdir():\n os.chdir(simDir)\n self.load()\n self.valid = True\n # simDir is a file and there is nothing to be done\n else:\n print('Bad Initialization. Cannot continue with simDir as a file.')\n exit()\n\n # we can now safely set the simDir\n self.simDir = simDir\n os.chdir(self.cwd)\n # run the configuration function\n if self.valid:\n configFn(self)\n # put things back the way we foudn them\n\n def benchmark(self, branch=None, commit=None, status=None, log=None, none=None, all=None):\n \"\"\"\n Configures benchmarks. Pass `all=True` to turn on all benchmarks. Pass\n `none=True` to turn of all benchmarks. Otherwise pass in benchmarks\n individually like `branch=True`.\n\n Individual benchmarks override `none` and `all` so:\n ```\n instance.benchmark(all=True, commit=False)\n ```\n Will turn on all benchmarks except for commit.\n\n The available benchmarks are:\n - `branch` the time to create a new branch\n - `commit` the time to make a new commit\n - `status` the time to run git status\n - `log` the time to run git log\n \"\"\"\n if none: self.benchmarks = { k: False for k, _ in self.benchmarks.items() }\n if all: self.benchmarks = { k: True for k, _ in self.benchmarks.items() }\n if branch is not None: self.benchmarks['branch'] = branch\n if commit is not None: self.benchmarks['commit'] = commit\n if status is not None: self.benchmarks['status'] = status\n if log is not None: self.benchmarksn['log' ] = log\n\n def options(self, *config):\n \"\"\"\n Set run configuration options. `*config` should be any number of two\n item lists composed of a sim.* operation and an integer constant. The\n integer constant represents the frequency at which that option will be\n chosen relative to the others.\n \"\"\"\n self.option = []\n for option in list(config):\n self.option += ([option[0]] * int(option[1]))\n return self\n\n def run(self, gens=1):\n \"\"\"\n Runs a given set of options for a given number of generations. If not\n provided this function will run only a single option.\n \"\"\"\n os.chdir(self.simDir)\n for _ in range(gens) if self.quiet or notqdm else tqdm.tqdm(range(gens)):\n random.choice(self.option)()\n self.save()\n os.chdir(self.cwd)\n return self\n\n def save(self):\n \"\"\"\n Writes metadata.\n \"\"\"\n with open(os.path.join('repository', 'repo'), 'w') as file:\n file.write(str(self.repo))\n with open('meta', 'w') as file:\n file.write(str(self.meta))\n return self\n\n def load(self, repo=True, meta=False):\n \"\"\"\n Reads metadata.\n \"\"\"\n self.log(os.getcwd())\n if repo:\n with open(os.path.join('repository', 'repo'), 'r') as file:\n self.repo = eval(file.read())\n if meta:\n with open('meta', 'r') as file:\n self.meta = eval(file.read())\n return self\n\n def report(self, config):\n \"\"\"\n Generate reports based off a given config map.\n\n Available options:\n - `markdown` if set to true will generate a markdown report\n - `status` if set to true will print the instance status\n - `graph` applies a config to report.graph\n\n A graph configuration should be an list where the first element is a\n list of the benchmarks to be plotted and the second element of the list\n is the variable for those benchmarks to be plotted against. To have\n graphs generated for all variables use '*' as the second element.\n \"\"\"\n os.chdir(self.simDir)\n if config['markdown']:\n report.markdown(self)\n if config['status']:\n report.status(self)\n if config['graph']:\n benchmarks = config['graph'][0]\n against = config['graph'][1]\n if against == '*':\n report.graph(benchmarks, 'size')\n report.graph(benchmarks, 'files')\n report.graph(benchmarks, 'branches')\n report.graph(benchmarks, 'commits')\n else:\n report.graph(benchmarks, against)\n os.chdir(self.cwd)\n return self\n\n def debug(message):\n \"\"\"\n Helper function, prints unless the instance is supposed to be quiet.\n \"\"\"\n if not self.quiet:\n print(message)\n\n def status(self):\n \"\"\"\n Returns information about the repository at the time of calling as a\n map. Keys include:\n - `size` the size of the repository (in bytes)\n - `files` the number of files in the repository\n - `commits` the total number of commits\n - `branches` the total number of branches (including deleted branches)\n \"\"\"\n size, files = dirStat('repository')\n return {\n 'size' : size,\n 'files' : files,\n 'commits' : self.meta['#commits'],\n 'branches' : self.meta['#branches'] + self.meta['#releases']\n }", "sub_path": "simgit/simgit.py", "file_name": "simgit.py", "file_ext": "py", "file_size_in_byte": 10157, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.walk", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "simgit.log.log", "line_number": 89, "usage_type": "call"}, {"api_name": "simgit.git.git", "line_number": 90, "usage_type": "call"}, {"api_name": "simgit.asset.asset", "line_number": 91, "usage_type": "call"}, {"api_name": "simgit.program.program", "line_number": 92, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path", "line_number": 118, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 126, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 127, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 129, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path", "line_number": 137, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 138, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 148, "usage_type": "call"}, {"api_name": "simgit.log.log", "line_number": 177, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 196, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 197, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 198, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 207, "usage_type": "call"}, {"api_name": "os.path", "line_number": 207, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 240, "usage_type": "call"}, {"api_name": "simgit.report.markdown", "line_number": 242, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 242, "usage_type": "name"}, {"api_name": "simgit.report.status", "line_number": 244, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 244, "usage_type": "name"}, {"api_name": "simgit.report.graph", "line_number": 249, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 249, "usage_type": "name"}, {"api_name": "simgit.report.graph", "line_number": 250, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 250, "usage_type": "name"}, {"api_name": "simgit.report.graph", "line_number": 251, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 251, "usage_type": "name"}, {"api_name": "simgit.report.graph", "line_number": 252, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 252, "usage_type": "name"}, {"api_name": "simgit.report.graph", "line_number": 254, "usage_type": "call"}, {"api_name": "simgit.report", "line_number": 254, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 255, "usage_type": "call"}]} +{"seq_id": "425934242", "text": "import sys\nimport json\nimport random\nimport click\nfrom sqlalchemy import *\nrandom.seed(0)\n\ndef nextval(minv=0, maxv=100):\n return random.randint(minv, maxv)\n\n@click.command()\n@click.option(\"--ddl\", is_flag=True, help=\"print CREATE TABLE statement\")\n@click.option(\"--schema\", is_flag=True, help=\"Print table attributes in first line\")\n@click.option(\"--data\", is_flag=True, help=\"Print the data\")\n@click.option(\"--out\", default=None, help=\"output file name/path\")\n@click.option(\"--dburl\", default=None, help=\"db url if create table. table option req.\")\n@click.option(\"--table\", default=None, help=\"table name to load data\")\n@click.option(\"--seed\", default=0, help=\"Seed to set random number generator\")\n@click.argument('nattrs', default=4) \n@click.argument('ntuples', default=10) \ndef main(ddl, schema, data, out, dburl, table, seed, nattrs, ntuples):\n truemain(ddl, schema, data, out, dburl, table, seed, nattrs, ntuples)\n\n\ndef truemain(ddl, schema, data, out, dburl, table, seed, nattrs, ntuples):\n \"\"\"\n Data generator for Logavulin\n \"\"\"\n random.seed(seed)\n if dburl:\n db = create_engine(dburl)\n if not table:\n raise RuntimeError\n\n attrs = map(\"a{0}\".format, range(int(nattrs)))\n\n if out is None:\n out = sys.stdout\n else:\n out = file(out, \"w\")\n\n if ddl or dburl:\n sql = \"CREATE TABLE %s(id int primary key, %s);\" \n sql = sql % (table, \", \".join(map(\"{0} int\".format, attrs)))\n if dburl:\n db.execute(\"DROP TABLE IF EXISTS %s\" % table)\n db.execute(sql)\n if ddl:\n print>>out, sql\n\n\n if schema:\n print>>out, \"id,%s\" % \",\".join(attrs)\n\n if data:\n tuples = []\n for i in xrange(ntuples):\n vals = [i] + map(nextval, xrange(nattrs))\n tuples.append(vals)\n\n\n for t in tuples:\n print>>out, \",\".join(map(str, t))\n\n if dburl:\n sql = \"INSERT INTO %s(id, %s) VALUES %s\"\n datastr = [\"(%s)\" % \",\".join(map(str, t)) for t in tuples]\n sql = sql % (table, \",\".join(attrs), \", \".join(datastr))\n db.execute(sql)\n\n try:\n if out != sys.stdout:\n out.close()\n except:\n pass\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "src/experiments/synth/datagen.py", "file_name": "datagen.py", "file_ext": "py", "file_size_in_byte": 2118, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "random.seed", "line_number": 6, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 9, "usage_type": "call"}, {"api_name": "click.command", "line_number": 11, "usage_type": "call"}, {"api_name": "click.option", "line_number": 12, "usage_type": "call"}, {"api_name": "click.option", "line_number": 13, "usage_type": "call"}, {"api_name": "click.option", "line_number": 14, "usage_type": "call"}, {"api_name": "click.option", "line_number": 15, "usage_type": "call"}, {"api_name": "click.option", "line_number": 16, "usage_type": "call"}, {"api_name": "click.option", "line_number": 17, "usage_type": "call"}, {"api_name": "click.option", "line_number": 18, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 19, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 20, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 72, "usage_type": "attribute"}]} +{"seq_id": "95814441", "text": "# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2017 - OutTech ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom odoo import api, fields, models, _\nfrom datetime import date\n\nclass VoucherCoupons(models.Model):\n _name = \"voucher.coupons\"\n\n @api.model\n def _get_company(self):\n user = self.env['res.users'].sudo().browse(self._uid)\n if user:\n return user.company_id.id\n\n @api.model\n def _get_user(self):\n user = self.env['res.users'].sudo().browse(self._uid)\n if user:\n return user.id\n\n @api.model\n def _get_date_today(self):\n return date.today()\n\n @api.model\n def _get_default_name(self):\n return self.env['ir.sequence'].next_by_code('voucher.coupons')\n\n @api.model\n def _get_rule(self):\n rule = self.env['voucher.coupons.config'].search([('active','=',True)])\n if rule:\n self.rule = rule.name\n return rule.name\n else:\n return \"\"\n\n name = fields.Char(string='Protocol', default=_get_default_name)\n protocol = fields.Char(string='Protocol')\n company_id = fields.Many2one('res.company', string='Company', default=_get_company)\n user_id = fields.Many2one('res.users', string='User', default=_get_user)\n date = fields.Date(string=\"Date\", default=_get_date_today)\n date_limit = fields.Date(string=\"Date Limit\", required=True)\n partner_id = fields.Many2one('res.partner', string='Customer', domain=\"[('customer','=',True)]\", required=True)\n amount = fields.Float(string=\"Amount\", required=True)\n rule = fields.Text('Rules', compute=_get_rule)\n state = fields.Selection([('created','Created'),('used','Used')],string='State', default='created')\n\n @api.onchange('name')\n def onchange_protocol(self):\n self.protocol = self.name\n return {}\n\n @api.model\n def create(self, vals):\n vals['name'] = vals['protocol']\n return super(VoucherCoupons, self).create(vals)\n\n def button_confirm(self):\n return self.write({'state':'used'})\n\nclass VoucherCouponsCofing(models.Model):\n _name = \"voucher.coupons.config\"\n\n name = fields.Text(string='Regra')\n active = fields.Boolean(string='Active')\n\n _sql_constraints = [\n ('active_rule_uniq', 'unique(active)', \"Only one rule for voucher\")\n ]\n", "sub_path": "addons/outtech/voucher_report/models/voucher_coupons.py", "file_name": "voucher_coupons.py", "file_ext": "py", "file_size_in_byte": 3150, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "odoo.models.Model", "line_number": 24, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 24, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 27, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 27, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 33, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 33, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 41, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 39, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 39, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 43, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 43, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 47, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 47, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 56, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 56, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 57, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 57, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 58, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 58, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 59, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 59, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 60, "usage_type": "name"}, {"api_name": "odoo.fields.Date", "line_number": 60, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 60, "usage_type": "name"}, {"api_name": "odoo.fields.Date", "line_number": 61, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 61, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 62, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 62, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 63, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 63, "usage_type": "name"}, {"api_name": "odoo.fields.Text", "line_number": 64, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 64, "usage_type": "name"}, {"api_name": "odoo.fields.Selection", "line_number": 65, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 65, "usage_type": "name"}, {"api_name": "odoo.api.onchange", "line_number": 67, "usage_type": "call"}, {"api_name": "odoo.api", "line_number": 67, "usage_type": "name"}, {"api_name": "odoo.api.model", "line_number": 72, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 72, "usage_type": "name"}, {"api_name": "odoo.models.Model", "line_number": 80, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 80, "usage_type": "name"}, {"api_name": "odoo.fields.Text", "line_number": 83, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 83, "usage_type": "name"}, {"api_name": "odoo.fields.Boolean", "line_number": 84, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 84, "usage_type": "name"}]} +{"seq_id": "408832173", "text": "import base64\nimport os\nimport paramiko\nimport socket\nimport uuid\nimport warnings\n\nfrom EasyLocalDisk.Client import Client as LocalDiskClient\nfrom EasyLog.Log import Log\nfrom EasyFilesystem.Sftp.ClientError import ClientError\nfrom io import StringIO\nfrom pysftp import CnOpts\nfrom pysftp import Connection\n\n\n# noinspection DuplicatedCode\nclass Client:\n def __init__(self):\n \"\"\"\n Setup SFTP client\n \"\"\"\n self.__sftp_connection__ = None\n self.__fingerprint_validation__ = True\n\n def __del__(self):\n \"\"\"\n Close any existing SFTP connection on deletion of this object. This is needed to prevent Lambda function from generating an error on completion\n\n :return: None\n \"\"\"\n if self.is_connected() is True:\n # noinspection PyBroadException\n try:\n self.__sftp_connection__.close()\n except Exception:\n # Ignore exceptions at this point\n pass\n\n @staticmethod\n def sanitize_path(path) -> str:\n \"\"\"\n Sanitize a path\n\n :type path: str\n :param path: Path to be sanitized\n\n :return: str\n \"\"\"\n # Remove all leading/trailing whitespace\n path = str(path).strip()\n\n # Remove all duplicated slashes in the path\n while '//' in path:\n path = path.replace('//', '/')\n\n # Strip all leading/trailing slashes\n path = path.strip('/')\n\n # Add slash to end of string before returning\n return '/{path}/'.format(path=path)\n\n @staticmethod\n def sanitize_filename(filename) -> str:\n \"\"\"\n Sanitize a full path/filename\n\n :type filename: str\n :param filename: Path/Filename to sanitize\n\n :return: str\n \"\"\"\n # Make sure we got a string\n filename = str(filename)\n\n # Sanitize the path component of the supplied string\n path = Client.sanitize_path(os.path.dirname(filename))\n\n # Extract the filename\n filename = os.path.basename(filename)\n\n # Concatenate them together\n return '{path}{filename}'.format(path=path, filename=filename)\n\n def create_path(self, path, allow_overwrite=False) -> None:\n \"\"\"\n Create path in remote sftp_filesystem\n\n :type path: str\n :param path: The path to create\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the path is allowed to be overwritten if it exists. If False, and the path exists an exception will be thrown\n\n :return: None\n \"\"\"\n # Sanitize the supplied path\n path = Client.sanitize_path(path)\n\n # Make sure the path does not already exist if overwrite is disabled\n if allow_overwrite is False:\n if self.file_exists(filename=path) is True:\n Log.exception(ClientError.ERROR_CREATE_PATH_ALREADY_EXISTS)\n\n # Create the path\n try:\n self.__sftp_connection__.makedirs(remotedir=path)\n except Exception as create_path_exception:\n Log.exception(ClientError.ERROR_CREATE_PATH_UNHANDLED_EXCEPTION, create_path_exception)\n\n # Make sure the path exists\n if self.file_exists(filename=path) is False:\n Log.exception(ClientError.ERROR_CREATE_PATH_FAILED)\n\n def create_temp_path(self, prefix='', temp_path=None) -> str:\n \"\"\"\n Create a new temporary path that is guaranteed to be unique\n\n :type prefix: str\n :param prefix: Optional prefix to prepend to path\n\n :type temp_path: str\n :param temp_path: The base path for all temporary files\n\n :return: str\n \"\"\"\n # If not temp path is set, set a sensible default\n if temp_path is None:\n temp_path = '/temp/'\n\n # Sanitize the supplied path\n temp_path = Client.sanitize_path(temp_path)\n\n # Make sure the temporary folder exists\n if self.file_exists(temp_path) is False:\n Log.exception(ClientError.ERROR_CREATE_TEMP_PATH_FOLDER_NOT_FOUND)\n\n # Enter a loop until we find a folder name that doesn't already exist\n count_attempts = 0\n while True:\n count_attempts += 1\n path = '{temp_path}{prefix}{uuid}'.format(temp_path=temp_path, prefix=prefix, uuid=uuid.uuid4())\n if self.file_exists(path) is False:\n # noinspection PyBroadException\n try:\n self.create_path(path=path, allow_overwrite=False)\n return path\n except Exception:\n # If creation fails its likely because it exists- so we will just try again next time\n pass\n if count_attempts > 10:\n # If we fail to create a path more than 10 times, something is wrong\n Log.exception(ClientError.ERROR_CREATE_TEMP_PATH_FAILED)\n\n def file_list(self, path, recursive=False):\n \"\"\"\n List a list of all files accessible in the sftp_filesystem sftp_filesystem\n\n :type path: str\n :param path: The path in the sftp_filesystem to list\n\n :type recursive: bool\n :param recursive: If True the listing will proceed recursively down through all sub-folders\n\n :return: list\n \"\"\"\n # Sanitize the path\n path = Client.sanitize_path(path)\n\n files = []\n\n try:\n current_path = self.__sftp_connection__.listdir(path)\n for current_item in current_path:\n current_item = Client.sanitize_filename('{remote_path}/{current_item}'.format(remote_path=path, current_item=current_item))\n if self.__sftp_connection__.isdir(current_item):\n # Current item is a directory, if we are doing a recursive listing, iterate down through it\n if recursive is True:\n files.extend(self.file_list(path=current_item, recursive=recursive))\n else:\n # Current item is a file, add it to the list\n files.append(Client.sanitize_filename(current_item))\n except Exception as file_list_exception:\n Log.exception(ClientError.ERROR_FILE_LIST_UNHANDLED_EXCEPTION, file_list_exception)\n\n return files\n\n def path_exists(self, path) -> bool:\n \"\"\"\n Check if path exists\n\n :type path: str\n :param path: Path to check\n\n :return: bool\n \"\"\"\n # Sanitize the filename\n path = Client.sanitize_path(path)\n\n try:\n return self.__sftp_connection__.exists(remotepath=path)\n except Exception as exists_exception:\n Log.exception(ClientError.ERROR_PATH_EXISTS_UNHANDLED_EXCEPTION, exists_exception)\n\n def file_exists(self, filename) -> bool:\n \"\"\"\n Check if file exists\n\n :type filename: str\n :param filename: Filename/path of the file to check\n\n :return: bool\n \"\"\"\n # Sanitize the filename\n filename = Client.sanitize_filename(filename)\n\n try:\n return self.__sftp_connection__.exists(remotepath=filename)\n except Exception as exists_exception:\n Log.exception(ClientError.ERROR_FILE_EXISTS_UNHANDLED_EXCEPTION, exists_exception)\n\n def path_delete(self, path, allow_missing=False) -> None:\n \"\"\"\n Delete a path from S3 bucket\n\n :type path: str\n :param path: Path to be deleted\n\n :type allow_missing: bool\n :param allow_missing: Boolean flag, if False and the file cannot be found to delete an exception will be raised\n\n :return: None\n \"\"\"\n # Sanitize the path\n path = self.sanitize_path(path)\n\n # Make sure the file exists before we try to delete it\n if self.path_exists(path=path) is False:\n # If this is fine, get out of here- the file is already gone\n if allow_missing is True:\n return\n\n Log.exception(ClientError.ERROR_PATH_DELETE_NOT_FOUND)\n\n # Delete the path\n try:\n self.__sftp_connection__.rmdir(path)\n except Exception as delete_exception:\n Log.exception(ClientError.ERROR_PATH_DELETE_UNHANDLED_EXCEPTION, delete_exception)\n\n # Make sure the file no longer exists after deleting\n if self.path_exists(path=path) is True:\n Log.exception(ClientError.ERROR_PATH_DELETE_FAILED)\n\n def file_delete(self, filename, allow_missing=False) -> None:\n \"\"\"\n Delete a file from SFTP server\n\n :type filename: str\n :param filename: Filename/path of the file to download from the SFTP server\n\n :type allow_missing: bool\n :param allow_missing: Boolean flag, if False and the file cannot be found to delete an exception will be raised\n\n :return: None\n \"\"\"\n # Sanitize the filename\n filename = Client.sanitize_filename(filename)\n\n # Make sure the file exists before we try to delete it\n if self.file_exists(filename) is False:\n # If this is fine, get out of here- the file is already gone\n if allow_missing is True:\n return\n Log.exception(ClientError.ERROR_FILE_DELETE_NOT_FOUND)\n\n # Delete the file\n try:\n self.__sftp_connection__.remove(filename)\n except Exception as delete_exception:\n Log.exception(ClientError.ERROR_FILE_DELETE_UNHANDLED_EXCEPTION, delete_exception)\n\n # Make sure the file no longer exists after deleting\n if self.file_exists(filename) is True:\n Log.exception(ClientError.ERROR_FILE_DELETE_FAILED)\n\n def file_move(self, source_filename, destination_filename, allow_overwrite=True) -> None:\n \"\"\"\n Move a file from one location in the sftp_filesystem to another\n\n :type source_filename: str\n :param source_filename: Path/filename to be moved\n\n :type destination_filename: str\n :param destination_filename: Destination path/filename within the same sftp_filesystem\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the file is allowed to be overwritten if it exists. If False, and the file exists an exception will be thrown\n\n :return: None\n \"\"\"\n # Sanitize the filenames\n source_filename = Client.sanitize_filename(source_filename)\n destination_filename = Client.sanitize_filename(destination_filename)\n\n # Ensure the source and destination are not the same\n if source_filename == destination_filename:\n Log.exception(ClientError.ERROR_FILE_MOVE_SOURCE_DESTINATION_SAME)\n\n # If allow overwrite is disabled, make sure the file doesn't already exist\n if allow_overwrite is False:\n if self.file_exists(destination_filename) is True:\n Log.exception(ClientError.ERROR_FILE_MOVE_ALREADY_EXISTS)\n\n # Make sure the source file exists\n if self.file_exists(source_filename) is False:\n Log.exception(ClientError.ERROR_FILE_MOVE_SOURCE_NOT_FOUND)\n\n # Move the file\n try:\n self.__sftp_connection__.rename(remote_src=source_filename, remote_dest=destination_filename)\n except Exception as move_exception:\n Log.exception(ClientError.ERROR_FILE_MOVE_UNHANDLED_EXCEPTION, move_exception)\n\n # Make sure the file exists at its destination\n if self.file_exists(destination_filename) is False:\n Log.exception(ClientError.ERROR_FILE_MOVE_COPY_FAILED)\n\n # Make sure the source file no longer exists\n if self.file_exists(source_filename) is True:\n Log.exception(ClientError.ERROR_FILE_MOVE_DELETE_FAILED)\n\n def file_copy(self, source_filename, destination_filename, allow_overwrite=True) -> None:\n \"\"\"\n Copy a file from one location in the sftp_filesystem to another\n\n :type source_filename: str\n :param source_filename: Path/filename to be moved\n\n :type destination_filename: str\n :param destination_filename: Destination path/filename within the same sftp_filesystem\n\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the file is allowed to be overwritten if it exists. If False, and the file exists an exception will be thrown\n\n :return: None\n \"\"\"\n # Sanitize the filenames\n source_filename = Client.sanitize_filename(source_filename)\n destination_filename = Client.sanitize_filename(destination_filename)\n\n # Ensure the source and destination are not the same\n if source_filename == destination_filename:\n Log.exception(ClientError.ERROR_FILE_COPY_SOURCE_DESTINATION_SAME)\n\n # If we are not in overwrite mode, we need to check if the file exists already\n if allow_overwrite is False:\n if self.file_exists(destination_filename) is True:\n Log.exception(ClientError.ERROR_FILE_COPY_ALREADY_EXISTS)\n\n # Make sure the source file exists\n if self.file_exists(source_filename) is False:\n Log.exception(ClientError.ERROR_FILE_COPY_SOURCE_NOT_FOUND)\n\n # To copy a file we need to download/upload it, storing it in a temporary file. Create a unique location to store it.\n temp_folder = LocalDiskClient.create_temp_path()\n temp_filename = '{temp_folder}/{uuid}'.format(temp_folder=temp_folder, uuid=uuid.uuid4())\n\n try:\n # Download/upload the file\n self.file_download(local_filename=temp_filename, remote_filename=source_filename)\n self.file_upload(local_filename=temp_filename, remote_filename=destination_filename)\n # Delete the temporary file\n LocalDiskClient.file_delete(temp_folder)\n except Exception as copy_exception:\n # Something went wrong- attempt to cleanup locally\n if LocalDiskClient.file_exists(temp_folder) is True:\n # noinspection PyBroadException\n try:\n LocalDiskClient.file_delete(temp_folder)\n except Exception:\n Log.warning('Failed to cleanup temporary file during copy operation')\n pass\n Log.exception(ClientError.ERROR_FILE_COPY_UNHANDLED_EXCEPTION, copy_exception)\n\n # Make sure the file exists at the destination\n if self.file_exists(source_filename) is False:\n Log.exception(ClientError.ERROR_FILE_COPY_FAILED)\n\n def file_download(self, local_filename, remote_filename, allow_overwrite=True) -> None:\n \"\"\"\n Download a file\n\n :type local_filename: str\n :param local_filename: Filename/path to destination on local sftp_filesystem where the file will be downloaded to\n\n :type remote_filename: str\n :param remote_filename: Filename/path of the remote file to be downloaded\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the file is allowed to be overwritten if it exists. If False, and the file exists an exception will be raised\n\n :return: None\n \"\"\"\n # Sanitize the filenames\n remote_filename = Client.sanitize_filename(remote_filename)\n\n # If allow overwrite is disabled, make sure the file doesn't already exist\n if allow_overwrite is False:\n if LocalDiskClient.file_exists(local_filename) is True:\n Log.exception(ClientError.ERROR_FILE_DOWNLOAD_ALREADY_EXISTS)\n\n # Make sure the file exists at the source\n if self.file_exists(remote_filename) is False:\n Log.exception(ClientError.ERROR_FILE_DOWNLOAD_SOURCE_NOT_FOUND)\n\n # Download the file\n try:\n # Make sure the local download path exists\n destination_path = LocalDiskClient.sanitize_path(os.path.dirname(local_filename))\n LocalDiskClient.create_path(destination_path, allow_overwrite=True)\n self.__sftp_connection__.get(remotepath=remote_filename, localpath=local_filename, preserve_mtime=True)\n except Exception as download_exception:\n Log.exception(ClientError.ERROR_FILE_DOWNLOAD_UNHANDLED_EXCEPTION, download_exception)\n\n # Make sure the file now exists locally\n if os.path.exists(local_filename) is False:\n Log.exception(ClientError.ERROR_FILE_DOWNLOAD_FAILED)\n\n def file_download_recursive(self, remote_path, local_path, callback=None, allow_overwrite=True) -> None:\n \"\"\"\n Recursively download all files found in the specified remote path to the specified local path\n\n :type remote_path: str\n :param remote_path: Path on SFTP server to be downloaded\n\n :type local_path: str\n :param local_path: Path on local file system where contents are to be downloaded\n\n :type callback: function/None\n :param callback: Optional callback_staked function to call after each file has downloaded successfully\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the file is allowed to be overwritten if it exists. If False, and the file exists an exception will be thrown\n\n :return: None\n \"\"\"\n # Sanitize the paths\n local_path = LocalDiskClient.sanitize_path(local_path)\n remote_path = Client.sanitize_path(remote_path)\n\n # List files in current path\n files_found = self.file_list(path=remote_path, recursive=True)\n\n Log.test('Found {count} File(s)'.format(count=len(files_found)))\n # Iterate these files\n for current_remote_filename in files_found:\n # The local filename will stored in the same folder structure as on the SFTP server\n current_local_path = LocalDiskClient.sanitize_path(local_path + os.path.dirname(current_remote_filename))\n current_local_filename = LocalDiskClient.sanitize_filename(current_local_path + os.path.basename(current_remote_filename))\n\n # Make sure the current files path exists locally before we start downloading\n LocalDiskClient.create_path(path=current_local_path, allow_overwrite=True)\n\n # Download the current file\n self.file_download(local_filename=current_local_filename, remote_filename=current_remote_filename, allow_overwrite=allow_overwrite)\n\n # If a callback_staked was supplied execute it\n if callback is not None:\n if callable(callback) is False:\n Log.exception(ClientError.ERROR_FILE_DOWNLOAD_CALLBACK_NOT_CALLABLE)\n # If the callback_staked returns false, stop iterating\n if callback(local_filename=current_local_filename, remote_filename=current_remote_filename) is False:\n break\n\n def file_upload(self, local_filename, remote_filename, allow_overwrite=True) -> None:\n \"\"\"\n Upload a file to remote sftp_filesystem\n\n :type local_filename: str\n :param local_filename: Filename/path of file to be uploaded from local sftp_filesystem\n\n :type remote_filename: str\n :param remote_filename: Filename/path where the file should be uploaded\n\n :type allow_overwrite: bool\n :param allow_overwrite: Flag indicating the file is allowed to be overwritten if it exists. If False, and the file exists an exception will be raised\n\n :return: None\n \"\"\"\n # Sanitize the filenames\n local_filename = LocalDiskClient.sanitize_filename(local_filename)\n remote_filename = Client.sanitize_filename(remote_filename)\n\n # Make sure the local file exists\n if LocalDiskClient.file_exists(local_filename) is False:\n Log.exception(ClientError.ERROR_FILE_UPLOAD_SOURCE_NOT_FOUND)\n\n # Make sure the file doesn't already exist if overwrite is disabled\n if allow_overwrite is False:\n if self.file_exists(remote_filename) is True:\n raise Exception(ClientError.ERROR_FILE_UPLOAD_ALREADY_EXISTS)\n\n # Upload the file\n try:\n self.__sftp_connection__.put(localpath=local_filename, remotepath=remote_filename, confirm=False)\n except Exception as upload_exception:\n Log.exception(ClientError.ERROR_FILE_UPLOAD_UNHANDLED_EXCEPTION, upload_exception)\n\n def enable_fingerprint_validation(self) -> None:\n \"\"\"\n Enable host fingerprint checking on connection\n\n :return: None\n \"\"\"\n Log.trace('Enable Fingerprint Validation...')\n self.__fingerprint_validation__ = True\n\n def disable_fingerprint_validation(self) -> None:\n \"\"\"\n Disable host fingerprint checking on connection\n\n :return: None\n \"\"\"\n Log.trace('Disable Fingerprint Validation...')\n self.__fingerprint_validation__ = False\n\n def connect(self, username, address, port, rsa_private_key=None, password=None, fingerprint=None, fingerprint_type=None) -> None:\n \"\"\"\n Connect by inspecting which authentication details were supplied and selecting a best guess method\n\n :type username: str\n :param username: Username to be used in connection\n\n :type address: str\n :param address: SFTP server sftp_address/hostname\n\n :type port: int\n :param port: SFTP server sftp_port number (defaults to 22)\n\n :type rsa_private_key: str\n :param rsa_private_key: RSA private key to be used for authentication\n\n :type password: str or None\n :param password: Optional password used for authentication\n\n :type fingerprint: str or None\n :param fingerprint: SFTP server sftp_fingerprint used to validate server identity\n\n :type fingerprint_type: str or None\n :param fingerprint_type: SFTP server sftp_fingerprint type\n \"\"\"\n if rsa_private_key is not None:\n # Private key was set, use it and connecting using RSA authentication\n self.connect_rsa_private_key(\n address=address,\n port=port,\n username=username,\n rsa_private_key=rsa_private_key,\n password=password,\n fingerprint=fingerprint,\n fingerprint_type=fingerprint_type\n )\n else:\n # Private key was not set, use a username/password\n self.connect_password(\n address=address,\n port=port,\n username=username,\n password=password,\n fingerprint=fingerprint,\n fingerprint_type=fingerprint_type\n )\n\n def connect_rsa_private_key(self, username, address, port, rsa_private_key, password=None, fingerprint=None, fingerprint_type=None) -> None:\n \"\"\"\n Connect to SFTP server using private key authentication\n\n :type username: str\n :param username: Username to be used in connection\n\n :type address: str\n :param address: SFTP server sftp_address/hostname\n\n :type port: int\n :param port: SFTP server sftp_port number (defaults to 22)\n\n :type rsa_private_key: str\n :param rsa_private_key: RSA private key to be used for authentication\n\n :type password: str or None\n :param password: Optional password used for authentication\n\n :type fingerprint: str or None\n :param fingerprint: SFTP server sftp_fingerprint used to validate server identity\n\n :type fingerprint_type: str or None\n :param fingerprint_type: SFTP server sftp_fingerprint type\n\n :return: None\n \"\"\"\n Log.trace('Connecting (RSA Private Key)...')\n\n # We need to ignore the warning due to non-existence of known_hosts file in Lambda\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n Log.debug('SFTP Server: {username}@{address}:{port}'.format(address=address, port=port, username=username))\n Log.debug('RSA Key Length: {key_length} Bytes'.format(key_length=len(rsa_private_key)))\n\n if fingerprint is not None:\n Log.debug('Host Fingerprint: {fingerprint}'.format(fingerprint=fingerprint))\n Log.debug('Host Fingerprint Type: {fingerprint_type}'.format(fingerprint_type=fingerprint_type))\n\n try:\n address = Client.__sanitize_sftp_address__(address)\n port = Client.__sanitize_sftp_port__(port)\n rsa_private_key = Client.__sanitize_sftp_private_key__(rsa_private_key)\n username = Client.__sanitize_sftp_username__(username)\n fingerprint = Client.__sanitize_sftp_fingerprint__(fingerprint)\n fingerprint_type = Client.__sanitize_sftp_fingerprint_type__(fingerprint_type)\n\n connection_options = self.__get_connection_options__(\n address=address,\n fingerprint=fingerprint,\n fingerprint_type=fingerprint_type\n )\n\n self.__sftp_connection__ = Connection(\n address,\n port=port,\n private_key=rsa_private_key,\n username=username,\n password=password,\n cnopts=connection_options\n )\n except Exception as connection_exception:\n if 'no hostkey for host' in str(connection_exception).lower():\n raise Exception(ClientError.ERROR_CONNECT_INVALID_FINGERPRINT, connection_exception)\n\n Log.exception(ClientError.ERROR_CONNECT_FAILED, connection_exception)\n\n # Assert the connection was successful and didn't generate unexpected warnings\n Client.__assert_connection_warning__(w)\n\n # Turn warnings back on\n warnings.simplefilter(\"default\")\n\n def connect_password(self, address, port, username, password, fingerprint=None, fingerprint_type=None) -> None:\n \"\"\"\n Connect to SFTP server using sftp_username and password\n\n :type username: str\n :param username: Username to be used in connection\n\n :type address: str\n :param address: SFTP server sftp_address/hostname\n\n :type port: int\n :param port: SFTP server sftp_port number\n\n :type password: str\n :param password: Password for authentication\n\n :type fingerprint: str or None\n :param fingerprint: SFTP server sftp_fingerprint used to validate server identity\n\n :type fingerprint_type: str or None\n :param fingerprint_type: SFTP server sftp_fingerprint type\n\n :return: None\n \"\"\"\n Log.trace('Connecting (Username/Password)...')\n\n # We need to ignore the warning due to non-existence of known_hosts file in Lambda\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n Log.debug('SFTP Server: {username}@{address}:{port}'.format(address=address, port=port, username=username))\n Log.debug('Host Fingerprint: {fingerprint} ({fingerprint_type})'.format(fingerprint=fingerprint, fingerprint_type=fingerprint_type))\n\n address = Client.__sanitize_sftp_address__(address)\n port = Client.__sanitize_sftp_port__(port)\n username = Client.__sanitize_sftp_username__(username)\n fingerprint = Client.__sanitize_sftp_fingerprint__(fingerprint)\n fingerprint_type = Client.__sanitize_sftp_fingerprint_type__(fingerprint_type)\n\n connection_options = self.__get_connection_options__(\n address=address,\n fingerprint=fingerprint,\n fingerprint_type=fingerprint_type\n )\n\n try:\n self.__sftp_connection__ = Connection(\n address,\n port=port,\n username=username,\n password=password,\n cnopts=connection_options\n )\n except Exception as connection_exception:\n if 'no hostkey for host' in str(connection_exception).lower():\n Log.exception(ClientError.ERROR_CONNECT_INVALID_FINGERPRINT, connection_exception)\n\n Log.exception(ClientError.ERROR_CONNECT_FAILED, connection_exception)\n\n # Assert the connection was successful and didn't generate unexpected warnings\n Client.__assert_connection_warning__(w)\n\n # Turn warnings back on\n warnings.simplefilter(\"default\")\n\n def disconnect(self):\n \"\"\"\n Disconnect from SFTP server\n\n :return: None\n \"\"\"\n Log.trace('Disconnecting...')\n self.__sftp_connection__.close()\n\n def is_connected(self):\n \"\"\"\n Check if we are still connected to the SFTP server\n\n :return: bool\n \"\"\"\n # noinspection PyBroadException\n try:\n # If no connection has ever been established return false\n if self.__sftp_connection__ is None:\n return False\n\n # If there is no SFTP client inside the connection object, return false\n if self.__sftp_connection__.sftp_client is None:\n return False\n\n # If there is no SFTP channel inside the client object, return false\n if self.__sftp_connection__.sftp_client.get_channel() is None:\n return False\n\n # If there is no SFTP transport, return false\n if self.__sftp_connection__.sftp_client.get_channel().get_transport() is None:\n return False\n\n # Otherwise return the current state of the underlying transport layer\n if self.__sftp_connection__.sftp_client.get_channel().get_transport().is_active() is True:\n return True\n\n return False\n\n except Exception:\n return False\n\n # Internal methods\n\n @staticmethod\n def __assert_connection_warning__(warning) -> None:\n \"\"\"\n Assert the expected connection warning was received, throwing an exception if not\n\n :type warning: dict\n :param warning: The warning received\n\n :return: None\n \"\"\"\n # If we didn't receive a warning then all is fine\n if -1 not in warning:\n return\n\n # Otherwise check the category of the warning, it should only be a UserWarning\n warning_category = warning[-1].category\n\n if issubclass(warning_category, UserWarning) is True:\n warning_message = str(warning[-1].message)\n # Check the message is as expected\n if 'Failed to load HostKeys' not in warning_message or 'You will need to explicitly load HostKeys' not in warning_message:\n raise Exception(ClientError.ERROR_CONNECT_FAILED)\n\n return\n\n # Unexpected warning received\n raise Exception(ClientError.ERROR_CONNECT_FAILED)\n\n @staticmethod\n def __fingerprint_to_paramiko_key__(fingerprint, fingerprint_type):\n \"\"\"\n Convert and SFTP private key to key suitable for use by underlying paramiko library\n\n :type fingerprint: str\n :param fingerprint: SFTP server sftp_fingerprint\n\n :type fingerprint_type: str\n :param fingerprint_type: SFTP server sftp_fingerprint type (e.g. ssh-rsa, ssh-dss)\n\n :return: paramiko.RSAKey or paramiko.DSSKey or paramiko/ECDSAKey\n \"\"\"\n try:\n if fingerprint_type == 'ssh-rsa':\n return paramiko.RSAKey(data=base64.b64decode(fingerprint))\n elif fingerprint_type == 'ssh-dss':\n return paramiko.DSSKey(data=base64.b64decode(fingerprint))\n elif fingerprint_type in paramiko.ecdsakey.ECDSAKey.supported_key_format_identifiers():\n return paramiko.ECDSAKey(data=base64.b64decode(fingerprint), validate_point=False)\n except Exception as key_exception:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE, key_exception)\n\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE)\n\n @staticmethod\n def __sanitize_sftp_port__(port):\n \"\"\"\n Validate that an acceptable port number was specified\n\n :type port: int/str/None\n :param port: SFTP server port number (must be in range of 0-65535)\n\n :return: int\n \"\"\"\n # If no port was specified generate an error\n if not port:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PORT)\n\n # If the port number was passed in as a string, make sure it contains digits\n if type(port) is str:\n if not port.isdigit():\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PORT)\n\n # Cast value to an integer\n try:\n port = int(port)\n except ValueError:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PORT)\n\n # Ensure port number is in valid range\n if port < 0 or port > 65535:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PORT)\n\n # Return the valid sftp_port number as an integer value\n return port\n\n @staticmethod\n def __sanitize_sftp_fingerprint_type__(fingerprint_type):\n \"\"\"\n Validate that the specified SFTP fingerprint type was valid\n\n :type fingerprint_type: str/None\n :param fingerprint_type: SFTP server fingerprint type (e.g. ssh-rsa)\n\n :return: str\n \"\"\"\n # If no fingerprint type was specified return None\n if not fingerprint_type:\n return None\n\n # Convert fingerprint type to lowercase\n fingerprint_type = str(fingerprint_type).lower()\n\n # Make sure the key type is one of the acceptable values\n if fingerprint_type not in ['ssh-rsa', 'ssh-dss']:\n if fingerprint_type not in paramiko.ecdsakey.ECDSAKey.supported_key_format_identifiers():\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE)\n\n # Return the valid fingerprint type\n return fingerprint_type\n\n @staticmethod\n def __sanitize_sftp_username__(sftp_username):\n \"\"\"\n Validate a username was supplied\n\n :type sftp_username: str/None\n :param sftp_username: SFTP username\n\n :return: str\n \"\"\"\n # If no username was specified generate an error\n if not sftp_username:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_USERNAME)\n\n # Return the username\n return str(sftp_username)\n\n @staticmethod\n def __sanitize_sftp_private_key__(sftp_private_key):\n \"\"\"\n Validate the specified SFTP private key was valid and return as a suitable paramiko RSA key value\n\n :type sftp_private_key: str/None\n :param sftp_private_key: SFTP private key used for connection\n\n :return: paramiko.RSAKey\n \"\"\"\n # If no private key was specified generate an error\n if not sftp_private_key:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PRIVATE_KEY)\n\n # Convert the private key string to a paramiko RSA key that can be used by the underlying libra4y\n try:\n sftp_private_key_string_io = StringIO(str(sftp_private_key))\n return paramiko.RSAKey.from_private_key(sftp_private_key_string_io)\n except Exception as key_exception:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_PRIVATE_KEY, key_exception)\n\n @staticmethod\n def __sanitize_sftp_fingerprint__(fingerprint):\n \"\"\"\n Validate the specified SFTP fingerprint was valid\n\n :type fingerprint: str/None\n :param fingerprint: SFTP fingerprint\n\n :return: str\n \"\"\"\n # If no fingerprint was specified return None\n if not fingerprint:\n return None\n\n # Return the fingerprint\n return str(fingerprint)\n\n @staticmethod\n def __sanitize_sftp_address__(address):\n \"\"\"\n Validate the specified SFTP server hostname/address is valid and can be resolved successfully\n\n :type address: str/None\n :param address: SFTP server hostname/address\n\n :return: str\n \"\"\"\n # Validate host address was supplied\n if not address:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_ADDRESS)\n\n # Validate host address can be resolved\n try:\n socket.gethostbyname(address)\n except socket.error:\n Log.exception(ClientError.ERROR_CONNECT_SANITIZE_ADDRESS)\n\n # Return the address\n return str(address)\n\n def __get_connection_options__(self, address, fingerprint, fingerprint_type):\n \"\"\"\n Get connection settings for pysftp client\n\n :type address: str\n :param address: SFTP server sftp_address/hostname\n\n :type fingerprint: str/None\n :param fingerprint: SFTP server sftp_fingerprint used to validate server identity. If not specified the known_hosts file on the host machine is used\n\n :type fingerprint_type: str/None\n :param fingerprint_type: SFTP server sftp_fingerprint type (e.g. ssh-rsa, ssh-dss). This must be one of the key types supported by paramiko library\n\n :return: obj\n \"\"\"\n Log.trace('Retrieving Connection Options...')\n options = CnOpts()\n\n if self.__fingerprint_validation__ is False:\n options.hostkeys = None\n else:\n # If a valid sftp_fingerprint and type were specified, add these to the known hosts, otherwise pysftp will use\n # the known_hosts file on the computer\n if fingerprint is not None and fingerprint_type is not None:\n Log.debug('Adding known host sftp_fingerprint to client...')\n options.hostkeys.add(\n hostname=address,\n keytype=fingerprint_type,\n key=self.__fingerprint_to_paramiko_key__(fingerprint, fingerprint_type)\n )\n else:\n Log.warning('No host fingerprints added, relying on known_hosts file')\n\n return options\n", "sub_path": "EasyFilesystem/Sftp/Client.py", "file_name": "Client.py", "file_ext": "py", "file_size_in_byte": 38179, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 102, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 102, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CREATE_PATH_ALREADY_EXISTS", "line_number": 102, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 102, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 108, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 108, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CREATE_PATH_UNHANDLED_EXCEPTION", "line_number": 108, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 108, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 112, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 112, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CREATE_PATH_FAILED", "line_number": 112, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 112, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 135, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 135, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CREATE_TEMP_PATH_FOLDER_NOT_FOUND", "line_number": 135, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 135, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 141, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 152, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 152, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CREATE_TEMP_PATH_FAILED", "line_number": 152, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 152, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 183, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 183, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_LIST_UNHANDLED_EXCEPTION", "line_number": 183, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 183, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 202, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 202, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_PATH_EXISTS_UNHANDLED_EXCEPTION", "line_number": 202, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 202, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 219, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 219, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_EXISTS_UNHANDLED_EXCEPTION", "line_number": 219, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 219, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 242, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 242, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_PATH_DELETE_NOT_FOUND", "line_number": 242, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 242, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 248, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 248, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_PATH_DELETE_UNHANDLED_EXCEPTION", "line_number": 248, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 248, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 252, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 252, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_PATH_DELETE_FAILED", "line_number": 252, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 252, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 274, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 274, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DELETE_NOT_FOUND", "line_number": 274, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 274, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 280, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 280, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DELETE_UNHANDLED_EXCEPTION", "line_number": 280, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 280, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 284, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 284, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DELETE_FAILED", "line_number": 284, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 284, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 307, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 307, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_SOURCE_DESTINATION_SAME", "line_number": 307, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 307, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 312, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 312, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_ALREADY_EXISTS", "line_number": 312, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 312, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 316, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 316, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_SOURCE_NOT_FOUND", "line_number": 316, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 316, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 322, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 322, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_UNHANDLED_EXCEPTION", "line_number": 322, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 322, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 326, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 326, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_COPY_FAILED", "line_number": 326, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 326, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 330, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 330, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_MOVE_DELETE_FAILED", "line_number": 330, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 330, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 354, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 354, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_COPY_SOURCE_DESTINATION_SAME", "line_number": 354, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 354, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 359, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 359, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_COPY_ALREADY_EXISTS", "line_number": 359, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 359, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 363, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 363, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_COPY_SOURCE_NOT_FOUND", "line_number": 363, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 363, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.create_temp_path", "line_number": 366, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 366, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 367, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client.file_delete", "line_number": 374, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 374, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.file_exists", "line_number": 377, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 377, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.file_delete", "line_number": 380, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 380, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.warning", "line_number": 382, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 382, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 384, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 384, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_COPY_UNHANDLED_EXCEPTION", "line_number": 384, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 384, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 388, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 388, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_COPY_FAILED", "line_number": 388, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 388, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.file_exists", "line_number": 410, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 410, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 411, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 411, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DOWNLOAD_ALREADY_EXISTS", "line_number": 411, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 411, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 415, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 415, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DOWNLOAD_SOURCE_NOT_FOUND", "line_number": 415, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 415, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.sanitize_path", "line_number": 420, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 420, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 420, "usage_type": "call"}, {"api_name": "os.path", "line_number": 420, "usage_type": "attribute"}, {"api_name": "EasyLocalDisk.Client.Client.create_path", "line_number": 421, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 421, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 424, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 424, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DOWNLOAD_UNHANDLED_EXCEPTION", "line_number": 424, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 424, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 427, "usage_type": "call"}, {"api_name": "os.path", "line_number": 427, "usage_type": "attribute"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 428, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 428, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DOWNLOAD_FAILED", "line_number": 428, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 428, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.sanitize_path", "line_number": 449, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 449, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.test", "line_number": 455, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 455, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.sanitize_path", "line_number": 459, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 459, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path", "line_number": 459, "usage_type": "attribute"}, {"api_name": "EasyLocalDisk.Client.Client.sanitize_filename", "line_number": 460, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 460, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path", "line_number": 460, "usage_type": "attribute"}, {"api_name": "EasyLocalDisk.Client.Client.create_path", "line_number": 463, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 463, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 471, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 471, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_DOWNLOAD_CALLBACK_NOT_CALLABLE", "line_number": 471, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 471, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.sanitize_filename", "line_number": 492, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 492, "usage_type": "name"}, {"api_name": "EasyLocalDisk.Client.Client.file_exists", "line_number": 496, "usage_type": "call"}, {"api_name": "EasyLocalDisk.Client.Client", "line_number": 496, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 497, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 497, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_UPLOAD_SOURCE_NOT_FOUND", "line_number": 497, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 497, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_UPLOAD_ALREADY_EXISTS", "line_number": 502, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 502, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 508, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 508, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_FILE_UPLOAD_UNHANDLED_EXCEPTION", "line_number": 508, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 508, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 516, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 516, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 525, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 525, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 602, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 602, "usage_type": "name"}, {"api_name": "warnings.catch_warnings", "line_number": 605, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 606, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 608, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 608, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 609, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 609, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 612, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 612, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 613, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 613, "usage_type": "name"}, {"api_name": "pysftp.Connection", "line_number": 629, "usage_type": "call"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_INVALID_FINGERPRINT", "line_number": 639, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 639, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 641, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 641, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_FAILED", "line_number": 641, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 641, "usage_type": "name"}, {"api_name": "warnings.simplefilter", "line_number": 647, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 673, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 673, "usage_type": "name"}, {"api_name": "warnings.catch_warnings", "line_number": 676, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 677, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 679, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 679, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 680, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 680, "usage_type": "name"}, {"api_name": "pysftp.Connection", "line_number": 695, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 704, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 704, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_INVALID_FINGERPRINT", "line_number": 704, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 704, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 706, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 706, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_FAILED", "line_number": 706, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 706, "usage_type": "name"}, {"api_name": "warnings.simplefilter", "line_number": 712, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 720, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 720, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_FAILED", "line_number": 779, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 779, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_FAILED", "line_number": 784, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 784, "usage_type": "name"}, {"api_name": "paramiko.RSAKey", "line_number": 801, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 801, "usage_type": "call"}, {"api_name": "paramiko.DSSKey", "line_number": 803, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 803, "usage_type": "call"}, {"api_name": "paramiko.ecdsakey.ECDSAKey.supported_key_format_identifiers", "line_number": 804, "usage_type": "call"}, {"api_name": "paramiko.ecdsakey", "line_number": 804, "usage_type": "attribute"}, {"api_name": "paramiko.ECDSAKey", "line_number": 805, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 805, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 807, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 807, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE", "line_number": 807, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 807, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 809, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 809, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE", "line_number": 809, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 809, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 823, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 823, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PORT", "line_number": 823, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 823, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 828, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 828, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PORT", "line_number": 828, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 828, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 834, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 834, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PORT", "line_number": 834, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 834, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 838, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 838, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PORT", "line_number": 838, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 838, "usage_type": "name"}, {"api_name": "paramiko.ecdsakey.ECDSAKey.supported_key_format_identifiers", "line_number": 862, "usage_type": "call"}, {"api_name": "paramiko.ecdsakey", "line_number": 862, "usage_type": "attribute"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 863, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 863, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_FINGERPRINT_TYPE", "line_number": 863, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 863, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 880, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 880, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_USERNAME", "line_number": 880, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 880, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 897, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 897, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PRIVATE_KEY", "line_number": 897, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 897, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 901, "usage_type": "call"}, {"api_name": "paramiko.RSAKey.from_private_key", "line_number": 902, "usage_type": "call"}, {"api_name": "paramiko.RSAKey", "line_number": 902, "usage_type": "attribute"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 904, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 904, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_PRIVATE_KEY", "line_number": 904, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 904, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 935, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 935, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_ADDRESS", "line_number": 935, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 935, "usage_type": "name"}, {"api_name": "socket.gethostbyname", "line_number": 939, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 940, "usage_type": "attribute"}, {"api_name": "EasyLog.Log.Log.exception", "line_number": 941, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 941, "usage_type": "name"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError.ERROR_CONNECT_SANITIZE_ADDRESS", "line_number": 941, "usage_type": "attribute"}, {"api_name": "EasyFilesystem.Sftp.ClientError.ClientError", "line_number": 941, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.trace", "line_number": 961, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 961, "usage_type": "name"}, {"api_name": "pysftp.CnOpts", "line_number": 962, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log.debug", "line_number": 970, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 970, "usage_type": "name"}, {"api_name": "EasyLog.Log.Log.warning", "line_number": 977, "usage_type": "call"}, {"api_name": "EasyLog.Log.Log", "line_number": 977, "usage_type": "name"}]} +{"seq_id": "421470089", "text": "__copyright__ = \"\"\"\n\n Copyright 2021 Samapriya Roy\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n__license__ = \"Apache 2.0\"\nimport ee\nimport os\n\n\n# Image copy\ndef image_copy(initial, replace_string, replaced_string, fpath):\n if replace_string == replaced_string or replace_string == None:\n final = fpath\n else:\n final = initial.replace(replace_string, replaced_string)\n try:\n if ee.data.getAsset(final):\n print(\"Image already copied: {}\".format(final))\n except Exception as e:\n print(\"Copying image to {}\".format(final))\n try:\n ee.data.copyAsset(initial, final)\n except Exception as e:\n print(e)\n\n\n# Table copy\ndef table_copy(initial, replace_string, replaced_string, fpath):\n if replace_string == replaced_string or replace_string == None:\n final = fpath\n else:\n final = initial.replace(replace_string, replaced_string)\n try:\n if ee.data.getAsset(final):\n print(\"Table already copied: {}\".format(final))\n except Exception as e:\n print(\"Copying table to {}\".format(final))\n try:\n ee.data.copyAsset(initial, final)\n except Exception as e:\n print(e)\n\n\n# Collection copy\ndef collection_copy(initial, replace_string, replaced_string, fpath):\n initial_list = ee.data.listAssets({\"parent\": initial})\n assets_names = [os.path.basename(asset[\"name\"]) for asset in initial_list[\"assets\"]]\n if replace_string == replaced_string or replace_string == None:\n collection_path = fpath\n else:\n collection_path = initial.replace(replace_string, replaced_string)\n try:\n if ee.data.getAsset(collection_path):\n print(\n \"Collection exists: {}\".format(ee.data.getAsset(collection_path)[\"id\"])\n )\n except Exception as e:\n print(\"Collection does not exist: Creating {}\".format(collection_path))\n try:\n ee.data.createAsset(\n {\"type\": ee.data.ASSET_TYPE_IMAGE_COLL_CLOUD}, collection_path\n )\n except Exception:\n ee.data.createAsset(\n {\"type\": ee.data.ASSET_TYPE_IMAGE_COLL}, collection_path\n )\n\n collection_path = ee.data.getAsset(collection_path)[\"name\"]\n final_list = ee.data.listAssets({\"parent\": collection_path})\n final_names = [os.path.basename(asset[\"name\"]) for asset in final_list[\"assets\"]]\n diff = set(assets_names) - set(final_names)\n print(\"Copying a total of \" + str(len(diff)) + \" images.....\")\n for count, items in enumerate(diff):\n print(\"Copying \" + str(count + 1) + \" of \" + str(len(diff)), end=\"\\r\")\n init = initial + \"/\" + items\n fin = collection_path + \"/\" + items\n try:\n ee.data.copyAsset(init, fin)\n except Exception as e:\n print(e)\n\n\n# Folder create\ndef fcreate(folder_path, replace_string, replaced_string):\n folder_path = folder_path.replace(replace_string, replaced_string)\n try:\n if ee.data.getAsset(folder_path):\n print(\"Folder exists: {}\".format(ee.data.getAsset(folder_path)[\"id\"]))\n except Exception as e:\n print(\"Folder does not exist: Creating {}\".format(folder_path))\n try:\n ee.data.createAsset({\"type\": ee.data.ASSET_TYPE_FOLDER_CLOUD}, folder_path)\n except:\n ee.data.createAsset({\"type\": ee.data.ASSET_TYPE_FOLDER}, folder_path)\n\n\n# Recursive folder paths\nfolder_list = []\n\n\ndef get_folder(path):\n parser = ee.data.getAsset(path)\n if parser[\"type\"].lower() == \"folder\":\n folder_list.append(parser[\"name\"])\n recursive(parser[\"name\"])\n\n\ndef recursive(path):\n path = ee.data.getAsset(path)\n if path[\"type\"].lower() == \"folder\":\n path = path[\"name\"]\n folder_list.append(path)\n children = ee.data.listAssets({\"parent\": path})\n for child in children[\"assets\"]:\n if not child[\"name\"] in folder_list:\n get_folder(child[\"name\"])\n return folder_list\n\n\n# Copy function\ndef copy(path, fpath):\n ee.Initialize()\n try:\n if not ee.data.getAsset(path) == None:\n if ee.data.getAsset(path)[\"type\"].lower() == \"folder\":\n gee_folder_path = recursive(path)\n gee_folder_path = sorted(list(set(gee_folder_path)))\n print(\"Total folders: {}\".format(len(set(folder_list))))\n # Get the initial path\n initial_path_suffix = path.split(\"/\")[-1]\n replace_string = (\n \"/\".join(ee.data.getAsset(path + \"/\")[\"name\"].split(\"/\")[:-1])\n + \"/\"\n + initial_path_suffix\n )\n # Get the final path\n final_path_suffix = fpath.split(\"/\")[-1]\n replaced_string = (\n ee.data.getAsset((\"/\".join(fpath.split(\"/\")[:-1]) + \"/\"))[\"name\"]\n + \"/\"\n + final_path_suffix\n )\n for folders in gee_folder_path:\n fcreate(folders, replace_string, replaced_string)\n children = ee.data.listAssets({\"parent\": folders})\n for child in children[\"assets\"]:\n if child[\"type\"].lower() == \"image_collection\":\n collection_copy(\n child[\"name\"], replace_string, replaced_string, fpath\n )\n elif child[\"type\"].lower() == \"image\":\n image_copy(\n child[\"name\"], replace_string, replaced_string, fpath\n )\n elif child[\"type\"].lower() == \"table\":\n table_copy(\n child[\"name\"], replace_string, replaced_string, fpath\n )\n print(\"\")\n elif ee.data.getAsset(path)[\"type\"].lower() == \"image\":\n path = ee.data.getAsset(path)[\"name\"]\n initial_path_suffix = path.split(\"/\")[-1]\n replace_string = (\n \"/\".join(ee.data.getAsset(path)[\"name\"].split(\"/\")[:-1])\n + \"/\"\n + initial_path_suffix\n )\n final_path_suffix = fpath.split(\"/\")[-1]\n replaced_string = (\n ee.data.getAsset(\"/\".join(fpath.split(\"/\")[:-1]))[\"name\"]\n + \"/\"\n + final_path_suffix\n )\n image_copy(path, replace_string, replaced_string, fpath)\n elif ee.data.getAsset(path)[\"type\"].lower() == \"image_collection\":\n path = ee.data.getAsset(path)[\"name\"]\n initial_list = ee.data.listAssets({\"parent\": path})\n assets_names = [\n os.path.basename(asset[\"name\"]) for asset in initial_list[\"assets\"]\n ]\n collection_path = fpath\n try:\n if ee.data.getAsset(collection_path):\n print(\n \"Collection exists: {}\".format(\n ee.data.getAsset(collection_path)[\"id\"]\n )\n )\n except Exception as e:\n print(\n \"Collection does not exist: Creating {}\".format(collection_path)\n )\n try:\n ee.data.createAsset(\n {\"type\": ee.data.ASSET_TYPE_IMAGE_COLL_CLOUD},\n collection_path,\n )\n except Exception:\n ee.data.createAsset(\n {\"type\": ee.data.ASSET_TYPE_IMAGE_COLL}, collection_path\n )\n\n collection_path = ee.data.getAsset(collection_path)[\"name\"]\n final_list = ee.data.listAssets({\"parent\": collection_path})\n final_names = [\n os.path.basename(asset[\"name\"]) for asset in final_list[\"assets\"]\n ]\n diff = set(assets_names) - set(final_names)\n print(\"Copying a total of \" + str(len(diff)) + \" images.....\")\n for count, items in enumerate(diff):\n print(\n \"Copying \" + str(count + 1) + \" of \" + str(len(diff)), end=\"\\r\"\n )\n init = path + \"/\" + items\n fin = collection_path + \"/\" + items\n try:\n ee.data.copyAsset(init, fin)\n except Exception as e:\n print(e)\n # collection_copy(path, replace_string, replaced_string, fpath)\n elif ee.data.getAsset(path)[\"type\"].lower() == \"table\":\n path = ee.data.getAsset(path)[\"name\"]\n replace_string = None\n replaced_string = ee.data.getAsset(\n \"/\".join(fpath.split(\"/\")[:-1]) + \"/\"\n )[\"name\"]\n table_copy(path, replace_string, replaced_string, fpath)\n except Exception as e:\n print(e)\n\n\n# copy(path='projects/earthengine-legacy/assets/users/samapriya/ppop/Dar-Es-Salaam-AOI',fpath='projects/earthengine-legacy/assets/users/samapriya/Dar-Es-Salaam-AOI')\n", "sub_path": "geeadd/batch_copy.py", "file_name": "batch_copy.py", "file_ext": "py", "file_size_in_byte": 9974, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "ee.data.getAsset", "line_number": 30, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 30, "usage_type": "attribute"}, {"api_name": "ee.data.copyAsset", "line_number": 35, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 35, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 47, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 47, "usage_type": "attribute"}, {"api_name": "ee.data.copyAsset", "line_number": 52, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 52, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 59, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 66, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 66, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 68, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 68, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 73, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 73, "usage_type": "attribute"}, {"api_name": "ee.data", "line_number": 74, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 77, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 77, "usage_type": "attribute"}, {"api_name": "ee.data", "line_number": 78, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 81, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 81, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 82, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "ee.data.copyAsset", "line_number": 91, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 91, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 100, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 100, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 101, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 101, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 105, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 105, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 107, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 107, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 115, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 115, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 122, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 122, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 126, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 126, "usage_type": "attribute"}, {"api_name": "ee.Initialize", "line_number": 135, "usage_type": "call"}, {"api_name": "ee.data.getAsset", "line_number": 137, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 137, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 138, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 138, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 145, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 145, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 152, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 152, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 158, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 158, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 173, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 173, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 174, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 174, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 177, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 177, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 183, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 183, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 188, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 188, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 189, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 189, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 190, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 190, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 196, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 196, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 199, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 199, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 207, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 207, "usage_type": "attribute"}, {"api_name": "ee.data", "line_number": 208, "usage_type": "attribute"}, {"api_name": "ee.data.createAsset", "line_number": 212, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 212, "usage_type": "attribute"}, {"api_name": "ee.data", "line_number": 213, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 216, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 216, "usage_type": "attribute"}, {"api_name": "ee.data.listAssets", "line_number": 217, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 217, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "ee.data.copyAsset", "line_number": 230, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 230, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 234, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 234, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 235, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 235, "usage_type": "attribute"}, {"api_name": "ee.data.getAsset", "line_number": 237, "usage_type": "call"}, {"api_name": "ee.data", "line_number": 237, "usage_type": "attribute"}]} +{"seq_id": "98423410", "text": "import bpy\nimport bmesh\nimport bgl\nimport mathutils\nfrom bpy.props import BoolProperty, EnumProperty, FloatProperty\nfrom .. utils.core import get_sides\nfrom .. utils.graph import build_edge_graph\nfrom .. utils.support import get_distance_between_verts\nfrom .. utils.developer import output_traceback\nfrom .. utils.ui import wrap_mouse, draw_init, draw_end, draw_title, draw_prop, step_enum, popup_message\nfrom .. utils import MACHIN3 as m3\n\n\n\n# TODO: add secondary way to mark fixed on the other side, perhas by using the freeestyle edges?\n# maybe via a method mode SIDE vs MARKEDLOOPS\n\n# TODO: do a proximity merge as well, verts that a renot on the edge loop, but are close(extra threshould?) to a fixed vert,\n# TODO: what you really want here is closeness to an edge, hmm\n\n# TODO: center merge instead of target merge?\n\n\nsideselctionitems = [(\"A\", \"A\", \"\"),\n (\"B\", \"B\", \"\")]\n\n\nclass BooleanCleanup(bpy.types.Operator):\n bl_idname = \"machin3.boolean_cleanup\"\n bl_label = \"MACHIN3: Boolean Cleanup\"\n bl_options = {'REGISTER', 'UNDO'}\n\n sideselection = EnumProperty(name=\"Side\", items=sideselctionitems, default=\"A\")\n\n threshold = FloatProperty(name=\"Threshold\", default=0, min=0, step=0.1)\n\n triangulate = BoolProperty(name=\"Triangulate\", default=False)\n\n # modal\n allowmodalthreashold = BoolProperty(default=True)\n\n # hidden\n sharp = BoolProperty(default=False)\n debuginit = BoolProperty(default=True)\n\n @classmethod\n def poll(cls, context):\n bm = bmesh.from_edit_mesh(context.active_object.data)\n mode = tuple(context.tool_settings.mesh_select_mode)\n\n if mode == (True, False, False) or mode == (False, True, False):\n return len([v for v in bm.verts if v.select]) >= 1\n\n\n def check(self, context):\n return True\n\n def draw(self, context):\n layout = self.layout\n\n column = layout.column()\n\n row = column.row()\n row.prop(self, \"sideselection\", expand=True)\n\n column.prop(self, \"threshold\")\n\n column.prop(self, \"triangulate\")\n\n def draw_VIEW3D(self, args):\n fixedcolor = (0.25, 1, 0.25)\n unmovedcolor = (1, 0.25, 0.25)\n alpha = 1\n\n mx = self.active.matrix_world\n\n bgl.glEnable(bgl.GL_BLEND)\n bgl.glDisable(bgl.GL_DEPTH_TEST)\n\n\n # draw fixed verts\n\n pointcolor = (*fixedcolor, alpha)\n bgl.glColor4f(*pointcolor)\n bgl.glPointSize(8)\n bgl.glBegin(bgl.GL_POINTS)\n\n for coords in self.fixed_verts:\n vco = mx * coords\n\n bgl.glVertex3f(*vco)\n\n bgl.glEnd()\n\n # draw moveable verts\n\n pointcolor = (*unmovedcolor, alpha)\n bgl.glColor4f(*pointcolor)\n bgl.glPointSize(6)\n bgl.glBegin(bgl.GL_POINTS)\n\n for coords in self.unmoved_verts:\n vco = mx * coords\n\n bgl.glVertex3f(*vco)\n\n draw_end()\n\n def draw_HUD(self, args):\n draw_init(self, args)\n\n draw_title(self, \"Boolean Cleanup\")\n\n draw_prop(self, \"Side\", self.sideselection, key=\"scroll UP/DOWN\")\n self.offset += 10\n\n draw_prop(self, \"Threshold\", self.threshold, offset=18, decimal=4, active=self.allowmodalthreashold, key=\"move LEFT/RIGHT, toggle W, reset ALT + W\")\n self.offset += 10\n\n draw_prop(self, \"Triangulate\", self.triangulate, offset=18, key=\"toggle T\")\n\n draw_end()\n\n def modal(self, context, event):\n context.area.tag_redraw()\n\n # update mouse postion for HUD\n if event.type == \"MOUSEMOVE\":\n self.mouse_x = event.mouse_region_x\n self.mouse_y = event.mouse_region_y\n\n events = ['WHEELUPMOUSE', 'ONE', 'WHEELDOWNMOUSE', 'TWO', 'W', 'T']\n\n # only consider MOUSEMOVE as a trigger, when modalthreshod is actually active\n if self.allowmodalthreashold:\n events.append('MOUSEMOVE')\n\n if event.type in events:\n\n # CONTROL threshold\n\n if event.type == 'MOUSEMOVE':\n wrap_mouse(self, context, event, x=True)\n delta = self.mouse_x - self.init_mouse_x # bigger if going to the right\n\n if self.allowmodalthreashold:\n if event.shift:\n self.threshold = delta * 0.0001\n elif event.ctrl:\n self.threshold = delta * 0.01\n else:\n self.threshold = delta * 0.001\n\n\n # TOGGLE triangulate\n\n elif event.type == 'W' and event.value == \"PRESS\":\n if event.alt:\n self.allowmodalthreashold = False\n self.threshold = 0\n else:\n self.allowmodalthreashold = not self.allowmodalthreashold\n\n elif event.type == 'T' and event.value == \"PRESS\":\n self.triangulate = not self.triangulate\n\n\n # SELECT side/fixed\n\n elif event.type in ['WHEELUPMOUSE', 'ONE'] and event.value == \"PRESS\":\n self.sideselection = step_enum(self.sideselection, sideselctionitems, 1)\n\n elif event.type in ['WHEELDOWNMOUSE', 'TWO'] and event.value == \"PRESS\":\n self.sideselection = step_enum(self.sideselection, sideselctionitems, -1)\n\n\n # modal BooleanCleanup\n try:\n ret = self.main(self.active, modal=True)\n\n # caught and error\n if ret is False:\n bpy.types.SpaceView3D.draw_handler_remove(self.HUD, 'WINDOW')\n bpy.types.SpaceView3D.draw_handler_remove(self.VIEW3D, 'WINDOW')\n return {'FINISHED'}\n # unexpected error\n except:\n output_traceback(self)\n bpy.types.SpaceView3D.draw_handler_remove(self.HUD, 'WINDOW')\n bpy.types.SpaceView3D.draw_handler_remove(self.VIEW3D, 'WINDOW')\n return {'FINISHED'}\n\n # VIEWPORT control\n\n elif event.type in {'MIDDLEMOUSE'}:\n return {'PASS_THROUGH'}\n\n # FINISH\n\n elif event.type in ['LEFTMOUSE', 'SPACE']:\n bpy.types.SpaceView3D.draw_handler_remove(self.HUD, 'WINDOW')\n bpy.types.SpaceView3D.draw_handler_remove(self.VIEW3D, 'WINDOW')\n return {'FINISHED'}\n\n # CANCEL\n\n elif event.type in {'RIGHTMOUSE', 'ESC'}:\n self.cancel_modal()\n return {'CANCELLED'}\n\n return {'RUNNING_MODAL'}\n\n def cancel_modal(self):\n bpy.types.SpaceView3D.draw_handler_remove(self.HUD, 'WINDOW')\n bpy.types.SpaceView3D.draw_handler_remove(self.VIEW3D, 'WINDOW')\n\n m3.set_mode(\"OBJECT\")\n self.initbm.to_mesh(self.active.data)\n m3.set_mode(\"EDIT\")\n\n def invoke(self, context, event):\n self.active = m3.get_active()\n\n # make sure the current edit mode state is saved to obj.data\n self.active.update_from_editmode()\n\n # save this initial mesh state, this will be used when canceling the modal and to reset it for each mousemove event\n self.initbm = bmesh.new()\n self.initbm.from_mesh(self.active.data)\n\n # mouse positions\n self.mouse_x = self.init_mouse_x = self.fixed_mouse_x = event.mouse_region_x\n self.mouse_y = self.init_mouse_y = self.fixed_mouse_y = event.mouse_region_y\n\n args = (self, context)\n self.VIEW3D = bpy.types.SpaceView3D.draw_handler_add(self.draw_VIEW3D, (args, ), 'WINDOW', 'POST_VIEW')\n self.HUD = bpy.types.SpaceView3D.draw_handler_add(self.draw_HUD, (args, ), 'WINDOW', 'POST_PIXEL')\n\n context.window_manager.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self, context):\n active = m3.get_active()\n\n try:\n self.main(active)\n except:\n output_traceback(self)\n\n return {'FINISHED'}\n\n def main(self, active, modal=False):\n debug = False\n # debug = True\n\n if debug:\n m3.clear()\n if self.debuginit:\n m3.debug_idx()\n self.debuginit = False\n\n mesh = active.data\n\n m3.set_mode(\"OBJECT\")\n\n # reset the mesh the initial state\n if modal:\n self.initbm.to_mesh(active.data)\n\n # create bmesh\n bm = bmesh.new()\n bm.from_mesh(mesh)\n bm.normal_update()\n bm.verts.ensure_lookup_table()\n\n verts = [v for v in bm.verts if v.select]\n edges = [e for e in bm.edges if e.select]\n\n if any([not e.smooth for e in edges]):\n self.sharp = True\n\n # create the side lists of dictionaries\n sideA, sideB, cyclic, err = get_sides(bm, verts, edges, debug=debug)\n\n if sideA and sideB:\n # tag the fixed verts, based on the side selection\n self.tag_fixed_verts(sideA, sideB)\n\n # fix the end verts for non-cyclic selections\n if not cyclic:\n sideA[0][\"vert\"].tag = True\n sideA[-1][\"vert\"].tag = True\n\n # create mesh_graph (for the selected verts)\n mg = build_edge_graph(verts, edges, debug=debug)\n\n # move the verts that aren't fixed and get the coordinates of the fixed and unmoved ones for bgl drawing\n self.fixed_verts, self.unmoved_verts = self.move_merts(bm, mg, cyclic, debug=debug)\n\n # triangulate\n if self.triangulate:\n self.triangulate_side(bm, sideA, sideB)\n\n # merge\n bmesh.ops.remove_doubles(bm, verts=verts, dist=0.00001)\n\n # triangulization may result in some edges no longer being sharp, if they were before!\n if self.triangulate and self.sharp:\n for e in bm.edges:\n if e.select:\n e.smooth = False\n\n bm.to_mesh(mesh)\n m3.set_mode(\"EDIT\")\n\n return True\n\n else:\n popup_message(err[0], title=err[1])\n m3.set_mode(\"EDIT\")\n\n return False\n\n def triangulate_side(self, bm, sideA, sideB):\n faces = []\n # note, this is intentionally reversed! you want to triangulize the opposite side\n if self.sideselection == \"A\":\n for sB in sideB:\n for f in sB[\"faces\"]:\n if f not in faces:\n faces.append(f)\n else:\n for sA in sideA:\n for f in sA[\"faces\"]:\n if f not in faces:\n faces.append(f)\n\n bmesh.ops.triangulate(bm, faces=faces)\n\n def move_merts(self, bm, mg, cyclic, debug=False):\n fixed_vert_coords = []\n unmoved_vert_coords = []\n\n if debug:\n print(\"cylclic selection:\", cyclic)\n\n for eidx, vidx in enumerate(mg):\n if debug:\n print(\"vert:\", vidx)\n\n # A and B does not refer to the previous sides of the edge selection here, but to the verts on either side of the current vert\n fixed = mg[vidx][\"fixed\"]\n if debug:\n print(\" » fixed:\", fixed)\n\n # fixed vert\n if fixed:\n fixed_vert_coords.append(mathutils.Vector((bm.verts[vidx].co)))\n continue\n\n # moveable vert\n else:\n A = mg[vidx][\"connected\"][0]\n B = mg[vidx][\"connected\"][1]\n\n Aidx, Afixed, Adist = A\n Bidx, Bfixed, Bdist = B\n\n lsort = [A, B]\n lsort = sorted(lsort, key=lambda l: l[2])\n closest = lsort[0]\n furthest = lsort[1]\n\n # move the verts to the closest neighbouring vert\n if closest[2] <= self.threshold:\n closestidx = closest[0]\n closestdist = closest[2]\n\n furthestidx = furthest[0]\n\n # move vert and any potentil children\n bm.verts[vidx].co = bm.verts[closestidx].co\n if debug:\n print(\" » moved to vert %d - distance: %f\" % (closestidx, closestdist))\n\n for childidx in mg[vidx][\"children\"]:\n bm.verts[childidx].co = bm.verts[closestidx].co\n if debug:\n print(\" » moved the child vert %d as well\" % (childidx))\n\n\n # update closest verts 'children' entry\n mg[closestidx][\"children\"].append(vidx)\n if debug:\n print(\" » updated %d's mg 'children' entry with vert %d\" % (closestidx, vidx))\n\n\n for childidx in mg[vidx][\"children\"]:\n mg[closestidx][\"children\"].append(childidx)\n\n if debug:\n print(\" » updated %d's mg 'children' entry with vert %d\" % (closestidx, childidx))\n\n\n # update the \"connected\" mg entries of the clostest and furthest verts, essentially making the movable vert invisible, as its now only a child of the closests\n closest_conected = mg[closestidx][\"connected\"]\n furthest_connected = mg[furthestidx][\"connected\"]\n\n\n # you can't just get the new distance by adding the distance to the closest to the distance to the furthest.\n # you need to calculate it from the closest and furthest vert positions, as with the current vert moved, there's now a straight line between closest and furthest\n newdist = get_distance_between_verts(bm.verts[closestidx], bm.verts[furthestidx])\n\n # in the closest and furthest vert of the one we have moved, find which of the 2 connected verts is the one we have moved\n # and replace it with the furthest/clostest, effectively, stepping over the moved one, as if it were merged already\n for i, con in enumerate(closest_conected):\n if con[0] == vidx:\n mg[closestidx][\"connected\"][i] = (furthestidx, furthest[1], newdist)\n\n if debug:\n print(\" » updated %d's mg 'connected' entry with vert %d replacing vert %d\" % (closestidx, furthestidx, vidx))\n\n for i, con in enumerate(furthest_connected):\n if con[0] == vidx:\n mg[furthestidx][\"connected\"][i] = (closestidx, closest[1], newdist)\n\n if debug:\n print(\" » updated %d's mg 'connected' entry with vert %d replacing vert %d\" % (furthestidx, closestidx, vidx))\n\n # not moving this vert as its below the distance threashold\n else:\n unmoved_vert_coords.append(mathutils.Vector((bm.verts[vidx].co)))\n\n return fixed_vert_coords, unmoved_vert_coords\n\n def tag_fixed_verts(self, sideA, sideB):\n if self.sideselection == \"A\":\n for sA in sideA:\n if sA[\"edges\"]:\n # edge = sA[\"edges\"][0]\n # edge.select = True\n\n # tag the vert to mark it is fixed\n sA[\"vert\"].tag = True\n else:\n for sB in sideB:\n if sB[\"edges\"]:\n # edge = sB[\"edges\"][0]\n # edge.select = True\n\n # tag the vert to mark it is fixed\n sB[\"vert\"].tag = True\n", "sub_path": "All_In_One/addons/MESHmachine/operators/boolean_cleanup.py", "file_name": "boolean_cleanup.py", "file_ext": "py", "file_size_in_byte": 15531, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "bpy.types", "line_number": 28, "usage_type": "attribute"}, {"api_name": "bpy.props.EnumProperty", "line_number": 33, "usage_type": "call"}, {"api_name": "bpy.props.FloatProperty", "line_number": 35, "usage_type": "call"}, {"api_name": "bpy.props.BoolProperty", "line_number": 37, "usage_type": "call"}, {"api_name": "bpy.props.BoolProperty", "line_number": 40, "usage_type": "call"}, {"api_name": "bpy.props.BoolProperty", "line_number": 43, "usage_type": "call"}, {"api_name": "bpy.props.BoolProperty", "line_number": 44, "usage_type": "call"}, {"api_name": "bmesh.from_edit_mesh", "line_number": 48, "usage_type": "call"}, {"api_name": "bgl.glEnable", "line_number": 77, "usage_type": "call"}, {"api_name": "bgl.GL_BLEND", "line_number": 77, "usage_type": "attribute"}, {"api_name": "bgl.glDisable", "line_number": 78, "usage_type": "call"}, {"api_name": "bgl.GL_DEPTH_TEST", "line_number": 78, "usage_type": "attribute"}, {"api_name": "bgl.glColor4f", "line_number": 84, "usage_type": "call"}, {"api_name": "bgl.glPointSize", "line_number": 85, "usage_type": "call"}, {"api_name": "bgl.glBegin", "line_number": 86, "usage_type": "call"}, {"api_name": "bgl.GL_POINTS", "line_number": 86, "usage_type": "attribute"}, {"api_name": "bgl.glVertex3f", "line_number": 91, "usage_type": "call"}, {"api_name": "bgl.glEnd", "line_number": 93, "usage_type": "call"}, {"api_name": "bgl.glColor4f", "line_number": 98, "usage_type": "call"}, {"api_name": "bgl.glPointSize", "line_number": 99, "usage_type": "call"}, {"api_name": "bgl.glBegin", "line_number": 100, "usage_type": "call"}, {"api_name": "bgl.GL_POINTS", "line_number": 100, "usage_type": "attribute"}, {"api_name": "bgl.glVertex3f", "line_number": 105, "usage_type": "call"}, {"api_name": "utils.ui.draw_end", "line_number": 107, "usage_type": "call"}, {"api_name": "utils.ui.draw_init", "line_number": 110, "usage_type": "call"}, {"api_name": "utils.ui.draw_title", "line_number": 112, "usage_type": "call"}, {"api_name": "utils.ui.draw_prop", "line_number": 114, "usage_type": "call"}, {"api_name": "utils.ui.draw_prop", "line_number": 117, "usage_type": "call"}, {"api_name": "utils.ui.draw_prop", "line_number": 120, "usage_type": "call"}, {"api_name": "utils.ui.draw_end", "line_number": 122, "usage_type": "call"}, {"api_name": "utils.ui.wrap_mouse", "line_number": 143, "usage_type": "call"}, {"api_name": "utils.ui.step_enum", "line_number": 171, "usage_type": "call"}, {"api_name": "utils.ui.step_enum", "line_number": 174, "usage_type": "call"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 183, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 183, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 184, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 184, "usage_type": "attribute"}, {"api_name": "utils.developer.output_traceback", "line_number": 188, "usage_type": "call"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 189, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 189, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 190, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 190, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 201, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 201, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 202, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 202, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 214, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 214, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_remove", "line_number": 215, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 215, "usage_type": "attribute"}, {"api_name": "utils.MACHIN3.set_mode", "line_number": 217, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 217, "usage_type": "name"}, {"api_name": "utils.MACHIN3.set_mode", "line_number": 219, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 219, "usage_type": "name"}, {"api_name": "utils.MACHIN3.get_active", "line_number": 222, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 222, "usage_type": "name"}, {"api_name": "bmesh.new", "line_number": 228, "usage_type": "call"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_add", "line_number": 236, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 236, "usage_type": "attribute"}, {"api_name": "bpy.types.SpaceView3D.draw_handler_add", "line_number": 237, "usage_type": "call"}, {"api_name": "bpy.types", "line_number": 237, "usage_type": "attribute"}, {"api_name": "utils.MACHIN3.get_active", "line_number": 243, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 243, "usage_type": "name"}, {"api_name": "utils.developer.output_traceback", "line_number": 248, "usage_type": "call"}, {"api_name": "utils.MACHIN3.clear", "line_number": 257, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 257, "usage_type": "name"}, {"api_name": "utils.MACHIN3.debug_idx", "line_number": 259, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 259, "usage_type": "name"}, {"api_name": "utils.MACHIN3.set_mode", "line_number": 264, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 264, "usage_type": "name"}, {"api_name": "bmesh.new", "line_number": 271, "usage_type": "call"}, {"api_name": "utils.core.get_sides", "line_number": 283, "usage_type": "call"}, {"api_name": "utils.graph.build_edge_graph", "line_number": 295, "usage_type": "call"}, {"api_name": "bmesh.ops.remove_doubles", "line_number": 305, "usage_type": "call"}, {"api_name": "bmesh.ops", "line_number": 305, "usage_type": "attribute"}, {"api_name": "utils.MACHIN3.set_mode", "line_number": 314, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 314, "usage_type": "name"}, {"api_name": "utils.ui.popup_message", "line_number": 319, "usage_type": "call"}, {"api_name": "utils.MACHIN3.set_mode", "line_number": 320, "usage_type": "call"}, {"api_name": "utils.MACHIN3", "line_number": 320, "usage_type": "name"}, {"api_name": "bmesh.ops.triangulate", "line_number": 338, "usage_type": "call"}, {"api_name": "bmesh.ops", "line_number": 338, "usage_type": "attribute"}, {"api_name": "mathutils.Vector", "line_number": 358, "usage_type": "call"}, {"api_name": "utils.support.get_distance_between_verts", "line_number": 412, "usage_type": "call"}, {"api_name": "mathutils.Vector", "line_number": 432, "usage_type": "call"}]} +{"seq_id": "553094217", "text": "from tkinter import *\nfrom PIL import Image, ImageTk\nfrom ttk import Combobox\nimport tkFileDialog, tkMessageBox, os, xlrd, pickle, anydbm\nfrom math import sqrt\nimport ttk\nimport urllib2\nfrom bs4 import BeautifulSoup\nimport re\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\nimport io\n\n\n\nclass Proj4(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent, bg = \"white\")\n self.parent = parent\n self.parent.title('SEHIR Reserh Projects Analyzer ')\n ttk.Style().configure(\"TFrame\", background=\"#F333\")\n self.interface(parent)\n self.pack()\n\n\n\n def interface(self,parent):\n Label(text = 'SEHIR Research Projects Analyzer -CS Edition',width = 50, bg = \"Blue\", fg = \"white\",font = (\"Helvetica\", 14, 'bold'),anchor = CENTER).pack(fill = None, expand = 0)\n self.frame0 = Frame(self.parent)\n self.frame0.pack(fill = BOTH, expand = True,side = TOP)\n self.frame1 = Frame(self.frame0)\n self.frame1.pack(fill = X, expand = 0, side = LEFT)\n self.url = Label(self.frame1,text ='Please Provide a url:',font = (\"Helvetica\", 9, 'bold'), anchor = W).grid(column = 0, row = 0, padx = 7, sticky = W+N)\n self.webpage = StringVar #We might use the strinvar so that we get the info we provide in the entry\n self.urlEntry = Entry(self.frame1,bg = 'yellow', width = 50,textvariable = self.webpage)\n self.urlEntry.grid(column = 0, row = 1,columnspan = 3, padx = 7, pady = 10, sticky = W+E)\n self.frame2 = Frame(self.frame0)\n self.frame2.pack(fill = X, expand = 0, side = LEFT)\n Button(self.frame2, text = 'Fetch Reserch Projects',command = self.fetchButton, anchor = CENTER,font = (\"Helvetica\", 9, 'bold'), width = 30).pack(side = LEFT, fill = X, expand = 0, padx = 20)\n Label(text = '\"'* (self.frame1.winfo_screenwidth()/7)).pack(fill = X, expand = 1)\n self.frame3 = Frame(self.parent)\n self.frame3.pack(fill = X, expand = 1, side = TOP)\n Label(self.frame3 , text = 'Filter Reserch Projects By:',font = (\"Helvetica\", 12, 'bold'),anchor = W).grid(column = 0, row = 0)\n Label(self.frame3 , text = 'Pick a Project:',font = (\"Helvetica\", 12, 'bold'), anchor = W ).grid(column = 1, row = 0, padx = 200)\n self.frame4 = Frame(self.parent)\n self.frame4.columnconfigure(3, weight = 1)\n self.frame4.columnconfigure(5, weight = 1)\n self.frame4.columnconfigure(1, weight = 1)\n self.frame4.columnconfigure(7, weight = 1)\n self.frame4.rowconfigure(4, weight = 1)\n self.frame4.pack(fill = X, expand = 1, side = TOP )\n Label(self.frame4, text = 'Year: ', anchor = W,font = (\"Helvetica\", 10, 'bold'), fg = 'blue' ).grid(row = 0,column=0, pady = 7, sticky = W)\n Label(self.frame4, text = 'Principle Investigator: ', anchor = W,font = (\"Helvetica\", 10, 'bold'), fg = 'blue' ).grid(row = 1,column=0,pady = 7, sticky = W)\n Label(self.frame4, text = 'Funding Institution: ', anchor = W,font = (\"Helvetica\", 10, 'bold'), fg = 'blue' ).grid(row = 2,column=0,pady = 7, sticky = W)\n\n #I will come back here\n self.yearBoxValue = StringVar()\n self.yearBox = Combobox(self.frame4, textvariable = self.yearBoxValue)\n self.yearBox.grid(row = 0,column=1,pady = 7, sticky = W,padx = 15)\n self.InvestBoxValue = StringVar()\n self.InvestBox = Combobox(self.frame4, textvariable = self.InvestBoxValue)\n self.InvestBox.grid(row = 1,column=1,pady = 7, sticky = W,padx = 15)\n self.InstitBoxValue = StringVar()\n self.InstitBox = ttk.Combobox(self.frame4, textvariable = self.InstitBoxValue)\n self.InstitBox.grid(row = 2,column=1,pady = 7, sticky = W,padx = 15)\n\n self.scrollbar = Scrollbar(self.frame4, orient=VERTICAL) #Creating the scrollbar which will work together with Listbox\n self.listbox = Listbox(self.frame4, yscrollcommand=self.scrollbar.set)\n self.scrollbar.config(command=self.listbox.yview)#Tell the scrollbar that its gonna be working with the ListBox\n self.scrollbar.grid(column = 6,row = 0, rowspan = 3,sticky = N+S)\n self.listbox.grid(column = 3,row = 0,rowspan = 3,columnspan = 3 ,sticky = N+E+S+W)\n\n Button(self.frame4, text = 'Display Project Titles',command = self.dispButton,font = (\"Helvetica\", 9, 'bold'), anchor = CENTER).grid(row = 4, column = 0, sticky = W,padx = 10, pady = 20)\n Button(self.frame4, text = 'Show Description',command = self.DescrButton, font = (\"Helvetica\", 9, 'bold'), anchor = CENTER).grid(row = 4, column = 5, sticky = W,padx = 10, pady = 20)\n Label(text = '\"'* (self.frame1.winfo_screenwidth()/7)).pack(fill = X, expand = 1)\n self.frame5 = Frame(self.parent)\n self.frame5.columnconfigure(0, weight = 1)\n self.frame5.columnconfigure(1, weight = 1)\n self.frame5.columnconfigure(2, weight = 1)\n self.frame5.rowconfigure(0, weight = 1)\n self.frame5.pack(fill = BOTH, expand = 1,side = TOP)\n self.canvas1=Canvas(self.frame5,bg='#FFFFFF',width=800,height=300, scrollregion = (0,0,200,200),relief = GROOVE)\n self.canvas1.config(width = 820, height = 320)\n self.canvas1.grid(row = 0, column = 0,columnspan = 2, sticky = N+E+S+W,pady = 10,padx = 5)\n self.canvas2=Canvas(self.frame5,bg='#FFFFFF',width=200,height=500, scrollregion = (0,0,300,300),relief = GROOVE)\n self.vertical_scroll = Scrollbar(self.frame5,orient=VERTICAL)\n self.vertical_scroll.grid(row = 0, column = 3, sticky = N+S)\n self.vertical_scroll.config(command = self.canvas2.yview) #we tell it its gonna work with canvas2\n self.horizontal_scroll = Scrollbar(self.frame5,orient=HORIZONTAL)\n self.horizontal_scroll.grid(row = 1, column = 2, sticky = W+E) #pack(side=RIGHT,fill=Y)\n self.horizontal_scroll.config(command = self.canvas2.xview)\n self.canvas2.config(yscrollcommand = self.vertical_scroll.set,xscrollcommand = self.horizontal_scroll.set )\n self.canvas2.config(width = 300, height = 300)\n self.canvas2.grid(row = 0, column = 2, sticky = N+E+S+W,pady = 10,padx = 5)\n\n\n\n\n\n def fetchButton(self):\n s = self.urlEntry.get() #Gets whatever we write in the URL entry box\n self.response = urllib2.urlopen(str(s)) # It opens and downloads the webpage\n self.soup = BeautifulSoup(self.response, 'html.parser') #It reads the source of the webpage, and after this we can play with it\n self.data= self.soup.find_all(\"li\",{\"class\":\"list-group-item\"}) #tAke all the parts which contain info about the projects\n self.mainDict = {}\n self.Year = []\n self.Investigator = []\n self.Institution = []\n for title in self.data:\n allYears = title.find_all(\"p\")[0].text #Gives the part where years are mentioned\n (startYear,endYear) = (int(allYears.split()[2]),int(allYears.split()[6])) #Take the years and convert them to int\n allInstitutions = title.find_all(\"p\")[1].text #Gives the part witth ist...\n (inst,name_of_inst) = (allInstitutions.split(':\\n')[0],allInstitutions.split(':\\n')[1])\n q = str(title.find(\"h4\").text) #Gives the title of the project each step\n allInvestigators = title.find_all(\"p\")[2].text #Find the part of the investigators\n blabla = title.find_all(\"img\")[0]['src'] #Finds the needed continuity of the picture link\n\n allTexts = title.find_all(\"p\")[4].string\n self.mainDict[q.lstrip().rstrip()] = {} #Creates dict inside the mainDict holding the name of the project\n self.mainDict[q.lstrip().rstrip()]['Years'] = (startYear,endYear) # Put the start/end years inside the dict of the project title\n self.mainDict[q.lstrip().rstrip()][str(inst.lstrip().rstrip())] = str(name_of_inst.lstrip().rstrip()) #Put the name of institution inside the Project title dict\n self.mainDict[q.lstrip().rstrip()]['Text'] = allTexts #Put the text inside the project title dict\n self.mainDict[q.lstrip().rstrip()]['src'] = blabla #Put the image url inside the same dict\n self.mainDict[q.lstrip().rstrip()][str(allInvestigators.split('\\n')[2].lstrip().rstrip())] = str(allInvestigators.split('\\n')[5].lstrip().rstrip())#Put investigators name inside the same dict\n for year in (startYear,endYear):\n if year not in self.Year: #In order to not put a YEAR twice or 3 times, only once\n self.Year.append(year)\n if name_of_inst not in self.Institution: #Same for institution\n self.Institution.append(name_of_inst)\n if str(allInvestigators.split('\\n')[5].lstrip().rstrip()) not in self.Investigator: # Same for Investigators\n self.Investigator.append(str(allInvestigators.split('\\n')[5].lstrip().rstrip()))\n self.yearBox['values'] =['All Years'] + sorted(self.Year)\n self.yearBox.current(0)\n self.InvestBox['values'] = ['All Investigators'] + sorted(self.Investigator)\n self.InvestBox.current(0)\n self.InstitBox['values'] = ['All Institutions'] + sorted(self.Institution)\n self.InstitBox.current(0)\n\n\n def dispButton(self):\n self.res1 = []\n self.res2 = []\n self.res3 = []\n\n if self.yearBoxValue.get() == 'All Years':\n for key in self.mainDict.keys():\n self.res1.append(key)\n else:\n for key in self.mainDict.keys():\n (x,y) = self.mainDict[key]['Years'] #It checks every title, and gets the start/end years of every title, if what we\n # have selected is in between these years, we append the title to our first lis\n if x<= int(self.yearBoxValue.get()) <= y:\n self.res1.append(key)\n\n\n\n if self.InvestBoxValue.get() == 'All Investigators':\n for key in self.mainDict.keys():\n self.res2.append(key)\n else:\n for key in self.mainDict.keys():\n if self.InvestBoxValue.get() == self.mainDict[key]['Principal Investigator:']:\n self.res2.append(key)\n\n\n if self.InstitBoxValue.get() == 'All Institutions':\n for key in self.mainDict.keys():\n self.res3.append(key)\n else:\n for key in self.mainDict.keys():\n if str(self.InstitBoxValue.get().lstrip().rstrip()) == str(self.mainDict[key]['Funding Institution']):\n self.res3.append(key)\n\n\n self.finalRes = list(set(self.res1) & set(self.res2) & set(self.res3)) #Find the intersection of the 3 lists by converting them to sets first, and to list afterwards\n self.listbox.delete(0, END)\n for val in self.finalRes: #We simply insert the final values(titles) into the ListBox\n self.listbox.insert(END, val)\n def DescrButton(self):\n\n self.index = int(self.listbox.curselection()[0])\n self.value =self.listbox.get(self.index) #We get what we have selected from Listbox\n print(self.value)\n self.myStr = ''\n self.canvas2.delete(\"all\")\n self.canvas_text = self.canvas2.create_text(0,0, anchor = NW)\n self.myL = list(str(self.mainDict[self.value]['Text']))\n self.counter = 0\n for i in self.myL:\n if i == ' ' or i == ',' or i == '.':\n self.counter +=1\n if self.counter == 11:\n self.myStr += i + '\\n'\n self.counter = 0\n else:\n self.myStr += i\n self.canvas2.itemconfig(self.canvas_text, text = self.myStr )\n self.draw()\n\n def draw(self):\n url = self.urlEntry.get()[0:23] + str(self.mainDict[self.value]['src'])[1:]\n print(url,type(url))\n image_bytes = urllib2.urlopen(url).read()\n data_stream = io.BytesIO(image_bytes)\n #print data_stream\n pil_image = Image.open(data_stream)\n #print pil_image\n tk_image = ImageTk.PhotoImage(pil_image)\n #print tk_image\n self.canvas1.create_image(0, 0, image=tk_image, anchor='nw')\n #print 'done'\n\n#{\"class\":\"img-responsive img-thumbnail small-gap\"}\n\n\n\n\n\n\n\n\n\n\n\n\ndef main():\n\n\n\n root = Tk()\n app = Proj4(root)\n app.winfo_geometry()\n root.rowconfigure(0, weight=5)\n root.columnconfigure(0, weight=5)\n root.mainloop()\n\nmain()", "sub_path": "Progr_Practice_Python/mini_proj_4/alajdin_rustemi.py", "file_name": "alajdin_rustemi.py", "file_ext": "py", "file_size_in_byte": 12410, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "sys.setdefaultencoding", "line_number": 12, "usage_type": "call"}, {"api_name": "ttk.Style", "line_number": 22, "usage_type": "call"}, {"api_name": "ttk.Combobox", "line_number": 59, "usage_type": "call"}, {"api_name": "ttk.Combobox", "line_number": 62, "usage_type": "call"}, {"api_name": "ttk.Combobox", "line_number": 65, "usage_type": "call"}, {"api_name": "urllib2.urlopen", "line_number": 103, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 104, "usage_type": "call"}, {"api_name": "urllib2.urlopen", "line_number": 204, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 205, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 207, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 207, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 209, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 209, "usage_type": "name"}]} +{"seq_id": "122390516", "text": "import os\nimport csv\nimport talib\nimport pandas\nimport array as arr\nimport yfinance as yf\nimport json\nfrom flask import Flask, request, render_template\nfrom patterns import candlestick_patterns, price_action_patterns\nfrom datetime import date\nimport numpy as np\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# from scipy.signal import argrelextrema\n# from statsmodels.nonparametric.kernel_regression import KernelReg\n# from fbprophet import Prophet\nfrom pattern_finder import find_extrema, find_patterns, plot_window\n\napp = Flask(__name__)\n\n\n@app.route('/getjson')\ndef getjson():\n ticker = request.args.get('symbol', None)\n if ticker is None:\n return {\n \"error\": \"No symbol found.\"\n }\n else:\n ticker = ticker.upper()\n path = os.path.join(os.getcwd(), \"data\", \"stocks\", ticker+\".csv\")\n return csv_to_json(path)\n\n\n@app.route('/chatbot')\ndef chatbot():\n from newspaper import Article\n import random\n import string\n import nltk\n from sklearn.feature_extraction.text import CountVectorizer\n from sklearn.metrics.pairwise import cosine_similarity\n import numpy as np\n import warnings\n warnings.filterwarnings('ignore')\n\n nltk.download('punkt', quiet=True)\n\n# Get the article\n# article = Article('https://www.investopedia.com/articles/investing/082614/how-stock-market-works.asp')\n article = Article(\n 'https://www.investopedia.com/terms/t/technicalanalysis.asp')\n article.download()\n article.parse()\n article.nlp()\n corpus = article.text\n\n# Print the article data\n\n text = corpus\n sentence_list = nltk.sent_tokenize(text) # A list a sentence\n\n print(sentence_list)\n\n def greeting_response(text):\n text = text.lower()\n # Bots greeting response\n bot_greetings = ['hello', 'hi', 'hey', 'hi there']\n # User greetings\n user_greetings = ['hi', 'heya', 'hello', 'hola']\n\n for word in text.split():\n if word in user_greetings:\n return random.choice(bot_greetings)\n\n def index_sort(list_var):\n length = len(list_var)\n list_index = list(range(0, length))\n\n x = list_var\n for i in range(length):\n for j in range(length):\n if x[list_index[i]] > x[list_index[j]]:\n temp = list_index[i]\n list_index[i] = list_index[j]\n list_index[j] = temp\n\n return list_index\n\n def bot_response(user_input):\n user_input = user_input.lower()\n sentence_list.append(user_input)\n bot_response = ''\n cm = CountVectorizer().fit_transform(sentence_list)\n similarity_scores = cosine_similarity(cm[-1], cm)\n similarity_scores_list = similarity_scores.flatten()\n index = index_sort(similarity_scores_list)\n index = index[1:]\n response_flag = 0\n\n j = 0\n for i in range(len(index)):\n if similarity_scores_list[index[i]] > 0.0:\n bot_response = bot_response+' '+sentence_list[index[i]]\n response_flag = 1\n j = j+1\n if j > 2:\n break\n if response_flag ==0:\n bot_response = bot_response+' '+\"I apologize, I dont understand.\"\n\n sentence_list.remove(user_input)\n return bot_response\n\n print(\"Bot: Hi! I am your ChatBot.\")\n\n exit_list = ['exit', 'see you later', 'bye', 'quit']\n while(True):\n user_input = input()\n if user_input.lower() in exit_list:\n print(\"Bot: Bye Bye!\")\n break\n else:\n if greeting_response(user_input) != None:\n print(\"Bot: \"+greeting_response(user_input))\n else:\n print('Bot: '+bot_response(user_input))\n\n\n@app.route('/scanner')\ndef scanner():\n pattern = request.args.get('pattern', False)\n fet = request.args.get('fet')\n stock_list = request.args.get('state', state())\n stocks = {}\n\n with open('data/symbols.csv') as f:\n for row in csv.reader(f):\n stocks[row[0]] = {'company': row[1]}\n\n if pattern:\n for filename in os.listdir('data/stocks'):\n df = pandas.read_csv('data/stocks/{}'.format(filename))\n pattern_function = getattr(talib, pattern)\n symbol = filename.split('.')[0]\n\n try:\n results = pattern_function(\n df['Open'], df['High'], df['Low'], df['Close'])\n results.iloc[::-1]\n\n last = results.tail(50).values[0]\n i = 0\n for j in reversed(results):\n if last == 0:\n last = int(j)\n if last != 0:\n break\n\n if i == 50:\n break\n\n i += 1\n\n if last > 0:\n stocks[symbol][pattern] = 'BULLISH'\n stocks[symbol][\"day\"] = i\n print(i)\n elif last < 0:\n stocks[symbol][pattern] = 'BEARISH'\n stocks[symbol][\"day\"] = i\n print(i)\n else:\n stocks[symbol][pattern] = None\n except Exception as e:\n print('Failed on File: ', filename, e)\n if fet:\n fetch_data()\n\n return render_template('scanner.html',\n candlestick_patterns=candlestick_patterns,\n stocks=stocks, pattern=pattern, fet=fet,\n state=stock_list, active='scanner')\n\n\n@app.route('/news', methods=['GET', \"POST\"])\ndef news():\n from newsapi import NewsApiClient\n newsapi = NewsApiClient(api_key='ca28357f195f40a9b89c153b4f569361')\n if request.method == 'POST':\n term = request.form.get('name')\n all_articles = newsapi.get_everything(q=term,\n sources='google-news-in,the-hindu,the-times-of-india',\n domains='www.thehindu.com,timesofindia.indiatimes.com,news.google.com',\n from_param='2021-09-28',\n to='2021-09-30',\n language='en',\n sort_by='relevancy',\n page=2)\n\n return render_template('news.html', articles=all_articles['articles'])\n\n\n return render_template('news.html', articles=None)\n\n@app.route('/prediction', methods=['GET', \"POST\"])\ndef prediction():\n if request.method == 'POST':\n try:\n ticker = yf.Ticker('AAPL')\n data = ticker.history(period=\"1d\")\n df = pandas.DataFrame(data).reset_index()\n df = df[[\"Date\", \"Close\"]]\n df = df.rename(columns = {\"Date\": \"ds\",\"Close\":\"y\"})\n fbp = Prophet(daily_seasonality= True)\n fbp.fit(df)\n fut = fbp.make_future_dataframe(periods=3650)\n forecast = fbp.predict(fut)\n print(forecast)\n\n except Exception as e:\n print(\"Failed to get required data.\", e)\n return render_template('prediction.html')\n\n\n\n\n@app.route('/finder', methods=['GET', \"POST\"])\ndef finder():\n if request.method == 'POST':\n symbol = request.form.get('name')\n try:\n googl = yf.download(symbol + '.NS', start='2020-01-01', end='2020-01-31')\n googl.drop(['Adj Close'], axis=1, inplace=True)\n prices, extrema, smooth_prices, smooth_extrema = find_extrema(googl['Close'], bw=[1.5])\n patterns = find_patterns(extrema)\n\n return render_template('finder.html',symbol=symbol, items=patterns.items(), pap=price_action_patterns)\n\n except Exception as e:\n print(\"Failed to get required data.\", e)\n\n return render_template('finder.html')\n\n \n\n@app.route('/about')\ndef about():\n return render_template('about.html', active=\"about\")\n\n\n@app.route('/patterns')\ndef patterns():\n return render_template('patterns.html', active=\"pattern\")\n\n\n@app.route('/fetch_data')\ndef fetch_data():\n current_date = str(date.today())\n with open('data/symbols.csv') as f:\n for line in f:\n if \",\" not in line:\n continue\n symbol = line.split(\",\")[0]\n # print(symbol)\n data = yf.download(symbol + '.NS', start=\"2020-01-01\", end=\"{}\".format(current_date))\n data.to_csv('data/stocks/{}.csv'.format(symbol))\n\n return {\n \"code\": \"success\"\n }\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', active='home')\n\n\n@app.route('/state')\ndef state():\n consolidate_stock = arr.array('b', []) # a1\n consolidate_stock = \"Consolidating:\\n\"\n breakout_stock = arr.array('b', []) # a2\n breakout_stock = \"Breaking Out:\\n\"\n\n def consolidating(df, percentage=2):\n recent_candlesticks = df[-5:]\n\n max_close = recent_candlesticks['Close'].max()\n min_close = recent_candlesticks['Close'].min()\n\n threshold = 1 - (percentage / 100)\n if min_close > (max_close * threshold):\n return True\n\n return False\n\n def breaking_out(df, percentage=2.5):\n last_close = df[-1:]['Close'].values[0]\n\n if consolidating(df[:-1], percentage=percentage):\n recent_closes = df[-6:-1]\n\n if last_close > recent_closes['Close'].max():\n return True\n\n return False\n\n for filename in os.listdir('data/stocks/'):\n df = pandas.read_csv('data/stocks/{}'.format(filename))\n\n if consolidating(df, percentage=2.5):\n a1 = \"{}\".format(filename.strip('.csv')) + \"\\n\"\n consolidate_stock += a1\n\n if breaking_out(df):\n a2 = \"{}\".format(filename.strip('.csv')) + \"\\n\"\n breakout_stock += a2\n\n stock_list = consolidate_stock + \"\\n\" + breakout_stock\n\n return stock_list\n\n\ndef csv_to_json(csvFilePath):\n jsonArray = []\n\n # read csv file\n with open(csvFilePath, encoding='utf-8') as csvf:\n # load csv file data using csv library's dictionary reader\n csvReader = csv.DictReader(csvf)\n\n # convert each csv row into python dict\n for row in csvReader:\n # add this python dict to json array\n jsonArray.append(row)\n\n # convert python jsonArray to JSON String and write to file\n jsonString = json.dumps(jsonArray, indent=4)\n return jsonString\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 10848, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 32, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 46, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 48, "usage_type": "call"}, {"api_name": "newspaper.Article", "line_number": 52, "usage_type": "call"}, {"api_name": "nltk.sent_tokenize", "line_number": 62, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 75, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 95, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 96, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 133, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 133, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 134, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 134, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 135, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 135, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 139, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 143, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 144, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 181, "usage_type": "call"}, {"api_name": "patterns.candlestick_patterns", "line_number": 182, "usage_type": "name"}, {"api_name": "newsapi.NewsApiClient", "line_number": 190, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 191, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 191, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 192, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 192, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 192, "usage_type": "name"}, {"api_name": "newsapi.get_everything", "line_number": 193, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 205, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 209, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 209, "usage_type": "name"}, {"api_name": "yfinance.Ticker", "line_number": 211, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 213, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 224, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 231, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 231, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 232, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 232, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 232, "usage_type": "name"}, {"api_name": "yfinance.download", "line_number": 234, "usage_type": "call"}, {"api_name": "pattern_finder.find_extrema", "line_number": 236, "usage_type": "call"}, {"api_name": "pattern_finder.find_patterns", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 239, "usage_type": "call"}, {"api_name": "patterns.items", "line_number": 239, "usage_type": "call"}, {"api_name": "patterns.price_action_patterns", "line_number": 239, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 244, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 250, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 255, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 260, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 260, "usage_type": "name"}, {"api_name": "yfinance.download", "line_number": 267, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 277, "usage_type": "call"}, {"api_name": "array.array", "line_number": 282, "usage_type": "call"}, {"api_name": "array.array", "line_number": 284, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 310, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 311, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 332, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 340, "usage_type": "call"}]} +{"seq_id": "607275817", "text": "# -*- coding: utf-8 -*-\n# versao: 1.5.0\n# python 3 comtability\nfrom __future__ import print_function\nfrom io import open\n\ntry:\n from urllib.request import urlopen\nexcept ImportError:\n from urllib2 import urlopen\n\n# personal import\ntry:\n from phanterparseconfigxml import parseConfigXML\nexcept ImportError:\n from plugin_phantermobileconstructor.phanterparseconfigxml import parseConfigXML\ntry:\n from phanterparseandroidmanifestxml import parseAndroidManifestXML\nexcept ImportError:\n from plugin_phantermobileconstructor.phanterparseandroidmanifestxml import parseAndroidManifestXML\n\n# python battery\nimport subprocess\nimport os\nimport zipfile\nimport shutil\nimport time\nimport re\nfrom sys import platform\n\n# this import need install (battery dont incluided)\nimport psutil\nfrom PIL import Image as PilImage\n\n# imports from web2py\nfrom gluon.html import URL\nfrom gluon import current\nfrom gluon.compileapp import find_exposed_functions\n\n\nclass PhanterAndroid(object):\n \"\"\"Make the connection between cordova app and web2py app\n\n - On init create this folders structure if not exists:\n web2py\n | - cordova\n |-folderAppCordova\n\n - The name of folderAppCordova is the same of your web2py aplication\n Cointains the default cordova app\n\n - On Web2py Developer, inside of plugin_phantermobileconstructor, \n all functions started with \"www_\" will be rendered in the cordova application (on buildHtml method)\n and all files in static/plugin_phantermobileconstructor/www will be copied to the www folder of cordova App\n\n exemple:\n - On controller plugin_phantermobileconstructor.py\n def www_index():\n #your code\n return dict()\n def www_other_function():\n return DIV(\"my div\")\n\n - On static/plugin_phantermobileconstructor/www\n static/plugin_phantermobileconstructor/www/\n |-css/\n |-mycss.css\n |-outhes.css\n |-images/\n |-myimage.jpg\n |-js/\n |-Jquery.js\n\n - will generate the following structure in the cordova application:\n folderAppCordova/\n |-www/\n |-index.html\n |-outher_function.html\n |-css/\n |-mycss.css\n |-outhes.css\n |-images/\n |-myimage.jpg\n |-js/\n |-Jquery.js\n \"\"\"\n\n def __init__(self, default_controller=None, advanced_filter=False):\n \"\"\"@aplication_id: generally follows the following format: com.yoursite.youraplication\n eg. br.com.conexaodidata.myaplication\n NOTE: this option is obsolet\n \"\"\"\n self.requeriments_store={\n 'cordova':False,\n 'keytool':False,\n 'phonegap':False,\n 'javac':False\n }\n self.advanced_filter=advanced_filter\n self.ajax_developer=None\n self.ajax_production=None\n self._created_key=[]\n self.request = current.request\n self.aplication_name = self.request.application\n self.default_controller = default_controller\n self.ports = []\n self.port = 3000\n self.cordova_app_folder = os.path.join(\n self.request.env.web2py_path, 'cordova')\n self.aplication_folder = os.path.join(\n self.request.env.web2py_path, 'cordova', self.aplication_name)\n self.server_chosen = 'phonegap'\n self.requeriments_store\n self.plugins_cordova={\n 'battery_status':[\n 'Battery Status',\n 'cordova-plugin-battery-status',\n ],\n 'camera':[\n 'Camera',\n 'cordova-plugin-camera',\n ],\n 'console':[\n 'Console',\n 'cordova-plugin-console',\n ],\n 'contacts':[\n 'Contacts',\n 'cordova-plugin-contacts',\n ],\n 'device':[\n 'Device',\n 'cordova-plugin-device',\n\n ],\n 'device_motion':[\n 'Device Motion',\n 'cordova-plugin-device-motion',\n ],\n 'device_orientation':[\n 'Device Orientation',\n 'cordova-plugin-device-orientation',\n ],\n 'dialogs':[\n 'Dialogs',\n 'cordova-plugin-dialogs',\n ],\n 'file':[\n 'File',\n 'cordova-plugin-file',\n ],\n 'file_transfer':[\n 'File Transfer',\n 'cordova-plugin-file-transfer',\n ],\n 'geolocation':[\n 'Geolocation',\n 'cordova-plugin-geolocation',\n ],\n 'globalization':[\n 'Globalization',\n 'cordova-plugin-globalization',\n ],\n 'inappbrowser':[\n 'Inappbrowser',\n 'cordova-plugin-inappbrowser',\n ],\n 'media':[\n 'Media',\n 'cordova-plugin-media',\n ],\n 'media_capture':[\n 'Media Capture',\n 'cordova-plugin-media-capture',\n ],\n 'network_information':[\n 'Network Information',\n 'cordova-plugin-network-information',\n ],\n 'vibration':[\n 'Vibration',\n 'cordova-plugin-vibration',\n ],\n 'statusbar':[\n 'Statusbar',\n 'cordova-plugin-statusbar',\n ]\n }\n exists_condovapath = os.path.exists(self.cordova_app_folder)\n exists_aplicationpath = os.path.exists(self.aplication_folder)\n if not exists_condovapath or not exists_aplicationpath:\n self._prepareTheEnvironment(buildHtml=True)\n\n def statusServer(self, server=None, timewait=1):\n if server:\n self.server_chosen = server\n time.sleep(timewait)\n return self._examine_process()\n\n def openServer(self, server=None):\n \"\"\"\n @server: 'phonegap' or 'cordova'\n In linux the server will have to be opened manually, \n so the method will try to find the process and the port.\n \"\"\"\n request = self.request\n if server:\n self.server_chosen = server\n print(\"Open %s server...\" % self.server_chosen)\n procs = self._examine_process()\n if procs:\n self.port = procs['port']\n print('Server is run in door %s' % procs['port'])\n else:\n port = 3000\n def myrange():\n cont=3000\n while cont<4000:\n cont+=1\n yield cont\n for y in myrange():\n if y in self.ports:\n pass\n else:\n self.ports.append(y)\n port = y\n break\n self.port = port\n if platform == \"win32\" or platform == 'cygwin':\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n engine=configxml.checkEngine('browser')\n if not engine or not os.path.exists(os.path.join(self.aplication_folder,'platforms', 'browser')):\n with open(os.path.join(self.cordova_app_folder, '%s_platform_add_browser.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content+=\"cordova platform add browser\\n\"\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print(\"Inserting Browser Platform\")\n try:\n subprocess.call([os.path.join(self.cordova_app_folder, '%s_platform_add_browser.bat' %\n self.aplication_name)])\n except Exception as e:\n print(e)\n if self.server_chosen == 'phonegap':\n with open(os.path.join(self.cordova_app_folder, '%s_server_%s_run.bat' %(self.aplication_name, self.server_chosen)), 'w') as file_opened:\n content = \"cd %s\\nphonegap serve -p%s\" % (\n self.aplication_folder, port)\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n else:\n with open(os.path.join(self.cordova_app_folder, '%s_server_%s_run.bat' %(self.aplication_name, self.server_chosen)), 'w') as file_opened:\n content = \"cd %s\\ncordova serve %s\" % (\n self.aplication_folder, port)\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n processo = subprocess.Popen([os.path.join(\n self.cordova_app_folder, '%s_server_%s_run.bat' %(self.aplication_name, self.server_chosen))], shell=True)\n elif platform == \"linux\" or platform == \"linux2\":\n\n processo = subprocess.Popen(['%S serve %s' %(self.server_chosen, port)], shell=True, cwd=self.aplication_folder)\n proc = psutil.Process(processo.pid)\n while not proc.children():\n print(\"Try open server %s run on door %s\" % (self.server_chosen, port))\n time.sleep(1)\n cont=50\n while cont<50:\n cont+=1\n print(\"Try conect (open url) to 'http://%s:%s'...\" %(self.request.env.http_host.split(':')[0], port),)\n try:\n urlopen('http://%s:%s' %(self.request.env.http_host.split(':')[0], port))\n break\n except Exception as e:\n print(\"Fail! be patient! Try again...\")\n time.sleep(3)\n\n print(\"\\n================================\\n Conected\\n-------------------------------\\n\")\n \n def ajaxServer(self, developer, production):\n self.ajax_developer=developer\n self.ajax_production=production\n\n def closeServer(self):\n \"\"\"\n Will try to find the server process and will close it\n \"\"\"\n print(\"Closing...\")\n procs = self._examine_process()\n if procs:\n proc = psutil.Process(procs['pid'])\n proc.kill()\n else:\n print('Server not found. nothing to do')\n\n def _filterHtml(self, html, for_apk=False):\n request = self.request\n if self.default_controller:\n html_filtrado = html.replace(\n \"/%s/static/%s/\" % (request.application, self.default_controller), \"\")\n html_filtrado = html_filtrado.replace(\n \"%s/static/%s/\" % (request.application, self.default_controller), \"\")\n html_filtrado = html_filtrado.replace(\n \"/static/%s/\" %self.default_controller, \"\")\n html_filtrado = html_filtrado.replace(\n \"static/%s/\" %self.default_controller, \"\")\n else:\n html_filtrado = html.replace(\n \"/%s/static/plugin_phantermobileconstructor/www/\" % request.application, \"\")\n html_filtrado = html_filtrado.replace(\n \"%s/static/plugin_phantermobileconstructor/www/\" % request.application, \"\")\n html_filtrado = html_filtrado.replace(\n \"/static/plugin_phantermobileconstructor/www/\", \"\")\n html_filtrado = html_filtrado.replace(\n \"static/plugin_phantermobileconstructor/www/\", \"\")\n if for_apk:\n if self.ajax_production and self.ajax_developer:\n html_filtrado = html_filtrado.replace(\n self.ajax_developer, self.ajax_production)\n com_href=re.compile(\"href=[\\\"']/%s/%s/.+?[\\\"']\" %(request.application, self.default_controller))\n\n if com_href.findall(html_filtrado):\n for r in com_href.findall(html_filtrado):\n sample_link=r\n html_fpage='href=\"%s.html\"' %sample_link.split('/')[-1].replace('\"','').replace(\"'\",\"\")\n html_filtrado=html_filtrado.replace(sample_link, html_fpage)\n\n if self.advanced_filter:\n html_filtrado= html_filtrado.replace('\\r\\n', '\\n')\n while '\\n\\n' in html_filtrado:\n html_filtrado= html_filtrado.replace('\\n\\n', '\\n')\n html_filtrado=re.compile('\\n\\s\\s+\\n').sub('\\n', html_filtrado)\n\n return html_filtrado\n \n def buildHtml(self):\n self._buildhtml()\n\n def _buildhtml(self, for_apk=False):\n \"\"\"\n All functions started with \"www_\" will be rendered in the cordova application (on buildHtml method)\n and all files in static/plugin_phantermobileconstructor/www will be copied to the www folder of cordova App\n \"\"\"\n request = self.request\n\n print(\"Compiling html...\")\n self.closeServer()\n if self.default_controller:\n self.origem = os.path.join(request.env.web2py_path, 'applications',\n self.aplication_name, 'static', self.default_controller) \n else:\n self.origem = os.path.join(request.env.web2py_path, 'applications',\n self.aplication_name, 'static', 'plugin_phantermobileconstructor', 'www')\n # self.lista_de_pastas_origem_e_destino = []\n # self.lista_de_pastas_destino = []\n self.lista_de_arquivos_origem_e_destinos = []\n self._examine_folders(self.origem)\n # for y in self.lista_de_pastas_destino:\n # if not os.path.exists(y):\n # os.makedirs(y)\n for x in self.lista_de_arquivos_origem_e_destinos:\n shutil.copy(x[0], x[1])\n mobile_functions = []\n if self.default_controller:\n new_controller = os.path.join(request.env.web2py_path, 'applications',\n self.aplication_name, 'controllers', \"%s.py\" % self.default_controller)\n with open(new_controller, 'r') as file_opened:\n mobile_functions = find_exposed_functions(file_opened.read())\n controller_name=self.default_controller\n else:\n controller_plugin = os.path.join(request.env.web2py_path, 'applications',\n self.aplication_name, 'controllers', 'plugin_phantermobileconstructor.py')\n with open(controller_plugin, 'r') as file_opened:\n mobile_functions = find_exposed_functions(file_opened.read())\n mobile_functions=(x for x in mobile_functions if x.startswith(\"www_\"))\n controller_name='plugin_phantermobileconstructor'\n \n if mobile_functions:\n for function_m in mobile_functions:\n if function_m:\n f=str(function_m)\n endereco=URL(controller_name, f, host=True)\n url = \"%s\" %endereco\n print(\"Try open url: %s\" % url)\n cont = 0\n if self.default_controller:\n html_file_name = function_m\n else:\n html_file_name = function_m.replace('www_', '')\n while cont < 5:\n try:\n html_url = urlopen(url)\n html = html_url.read()\n break\n except Exception as e:\n time.sleep(2)\n print(e)\n cont += 1\n print(\"Fail! try %s of 5\" % cont)\n try:\n html2=html.decode('utf-8')\n except:\n html2=html\n if for_apk:\n html2=self._filterHtml(html2, for_apk=True)\n else:\n html2=self._filterHtml(html2)\n try:\n arquivo_destino = os.path.join(\n self.aplication_folder, 'www', \"%s.html\" % html_file_name)\n with open(arquivo_destino, 'w', encoding='utf8') as file_opened:\n print('Get html source of %s and copy to %s' % (url, arquivo_destino))\n file_opened.write(html2)\n except Exception as e:\n print(e)\n\n if platform == \"win32\" or platform == 'cygwin':\n with open(os.path.join(self.cordova_app_folder, '%s_cordova_prepare.bat' %(self.aplication_name)), 'w') as file_opened:\n print('cordova prepare')\n content = \"cd %s\\ncordova prepare\" %self.aplication_folder\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n processo = subprocess.Popen([os.path.join(\n self.cordova_app_folder, '%s_cordova_prepare.bat' %(self.aplication_name))], shell=True)\n elif platform == \"linux\" or platform == \"linux2\":\n subprocess.call(['cordova prepare'], shell=True, cwd=self.aplication_folder)\n print(\"html build\")\n\n def _getServerandDoorCmdLine(self, cmdline):\n strcmdline=' '.join(cmdline)\n if 'serve' in strcmdline:\n if 'phonegap' in strcmdline:\n if '-p' in strcmdline:\n padrao = re.compile(r'serve *-[pP]([0-9]+)')\n port = padrao.findall(strcmdline)\n try:\n port = int(port[0])\n except:\n print(\"error: port dont is a number!\")\n port = None\n if port:\n self.ports.append(port)\n return ['phonegap', port]\n else:\n return []\n else:\n return []\n elif 'cordova' in strcmdline:\n padrao = re.compile('serve *([0-9]+)')\n port = padrao.findall(strcmdline)\n try:\n port = int(port[0])\n except:\n print(\"error: port dont is a number!\")\n port = None\n if port:\n self.ports.append(port)\n return ['cordova', port]\n else:\n return []\n else:\n return []\n\n def _examine_process(self):\n request = self.request\n if platform == \"win32\" or platform == 'cygwin':\n nome = 'node.exe'\n elif platform =='linux' or platform =='linux2':\n nome = 'node'\n processo_localizado = {}\n localized=False\n for proc in psutil.process_iter():\n if proc.name() == nome:\n if proc.cwd() == self.aplication_folder:\n linha_de_comando = proc.cmdline()\n port_and_server = self._getServerandDoorCmdLine(\n linha_de_comando)\n if port_and_server and not localized and (self.server_chosen==port_and_server[0]):\n localized=True\n processo_localizado['server'] = port_and_server[0]\n processo_localizado['port'] = port_and_server[1]\n processo_localizado['pid'] = proc.pid\n print(\"\\n================ SERVER INFO ==================\" +\\\n \"\\n Server: %s\\n Porta: %s\\n Pasta:%s \\n PID: %s\\n\" % (port_and_server[0], port_and_server[1], proc.cwd(), proc.pid) +\\\n \"------------------------------------\\n\")\n return processo_localizado\n\n def _examine_folders(self, path):\n request = self.request\n if not os.path.isfile(path):\n lista = os.listdir(path)\n if lista:\n for x in lista:\n target=os.path.join(path.replace(os.path.join(self.origem), os.path.join(self.aplication_folder, 'www')), x)\n if os.path.isfile(os.path.join(path, x)):\n if os.path.exists(target):\n os.unlink(target)\n self.lista_de_arquivos_origem_e_destinos.append([os.path.join(path, x), target])\n else:\n try:\n os.makedirs(target)\n except:\n pass\n self._examine_folders(os.path.join(path, x))\n\n def _prepareTheEnvironment(self, buildHtml=True):\n request = self.request\n\n print('Prepare Environment')\n if not os.path.exists(self.cordova_app_folder):\n print('Creating Folder: %s' % self.cordova_app_folder)\n os.makedirs(self.cordova_app_folder)\n if platform == \"win32\" or platform == 'cygwin':\n if not os.path.exists(os.path.join(self.cordova_app_folder, '%s_create_app.bat' % self.aplication_name)):\n print(\"Creating file %s_create_app.bat\" % self.aplication_name)\n with open(os.path.join(self.cordova_app_folder, '%s_create_app.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\ncordova create %s %s %s\" % (\n self.cordova_app_folder, self.aplication_name, 'com.yoursite.yourapp', self.aplication_name)\n try:\n content=content.decode('utf-8')\n except:\n pass \n file_opened.write(content)\n print(\"Executing: %s_create_app\" %self.aplication_name)\n subprocess.call([os.path.join(self.cordova_app_folder, '%s_create_app.bat' %\n self.aplication_name)], stdout=subprocess.PIPE, shell=True, stdin=subprocess.PIPE)\n\n if not os.path.exists(os.path.join(self.cordova_app_folder, '%s_platform_browser.bat' % self.aplication_name)):\n print(\"Creating file %s_platform_browser.bat\" % self.aplication_name)\n with open(os.path.join(self.cordova_app_folder, '%s_platform_browser.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\ncordova platform add browser\" %(self.aplication_folder)\n try:\n content=content.decode('utf-8')\n except:\n pass \n file_opened.write(content)\n print(\"Executing: %s_platform_browser.bat\" %self.aplication_name)\n subprocess.call([os.path.join(self.cordova_app_folder, '%s_platform_browser.bat' %\n self.aplication_name)], shell=True)\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n engine=configxml.checkEngine('android')\n if not engine or not os.path.exists(os.path.join(self.aplication_folder,'platforms', 'android')):\n with open(os.path.join(self.cordova_app_folder, '%s_create_apk_build.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content+=\"cordova platform add android\\n\"\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print(\"Inserting Android Platform\")\n try:\n apk1=subprocess.call([os.path.join(self.cordova_app_folder, '%s_create_apk_build.bat' %\n self.aplication_name)])\n except Exception as e:\n print(e)\n if not configxml.checkPlugin('cordova-plugin-splashscreen'):\n with open(os.path.join(self.cordova_app_folder, '%s_add_plugin_splashscreen.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content+=\"cordova plugin add cordova-plugin-splashscreen\\n\"\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n procs=subprocess.call([os.path.join(self.cordova_app_folder, '%s_add_plugin_splashscreen.bat' %\n self.aplication_name)])\n\n elif platform == \"linux\" or platform == \"linux2\":\n if not os.path.exists(self.aplication_folder):\n subprocess.call([\"cordova create %s %s %s\" % (os.path.join(self.cordova_app_folder, self.aplication_name), 'com.yoursite.yourapp', self.aplication_name)], cwd=self.cordova_app_folder, shell=True)\n subprocess.call([\"cordova platform add browser\"], cwd=self.aplication_folder, shell=True)\n subprocess.call([\"cordova plugin add cordova-plugin-splashscreen\"], cwd=self.aplication_folder, shell=True)\n\n if buildHtml:\n self._buildhtml()\n\n def resetApp(self):\n self.removeCordovaApp()\n self.PrepareTheEnvironment(buildHtml=False)\n\n def _remove_file(self, file):\n if os.path.exists(file):\n try:\n os.unlink(file)\n except Exception as e:\n print(\"Erro on remove:\", file)\n print(e)\n\n def requeriments(self, update_req='all'):\n \"\"\"try check requeriments\n @update: if all, all requirements will be checked.\n set 'cordova' to check cordova\n set 'keytool' to check keytool\n set 'phonegap' to check phonegap\n set 'javac' to check javac\n \"\"\"\n if platform == 'win32' or platform == 'cygwin':\n re_cordova=re.compile(r'^[A-Z]:\\\\.+cordova\\.cmd')\n re_phonegap=re.compile(r'^[A-Z]:\\\\.+phonegap\\.cmd')\n re_keytool=re.compile(r'[A-Z]:\\\\.+\\\\Java\\\\.+bin\\\\keytool\\.exe')\n re_javac=re.compile(r'[A-Z]:\\\\.+\\\\Java\\\\.+bin\\\\javac\\.exe')\n if update_req=='all' or update_req=='cordova':\n try:\n cordova=subprocess.check_output(['where','cordova.cmd'])\n cordova=cordova.strip().split('\\n')[0]\n path_cordova=re_cordova.findall(cordova.decode('utf-8'))\n self.requeriments_store['cordova']=path_cordova\n except Exception as e:\n print(\"Don't find cordova in your system, try install. eg. npm install -g cordova\")\n print(e)\n if update_req=='all' or update_req=='phonegap':\n try:\n phonegap=subprocess.check_output(['where','phonegap.cmd'])\n phonegap=phonegap.strip().split('\\n')[0]\n path_phonegap=re_phonegap.findall(phonegap.decode('utf-8'))\n self.requeriments_store['phonegap']=path_phonegap\n except Exception as e:\n print(\"Don't find phonegap in your system, try install. eg. npm install -g phonegap\")\n print(e)\n if update_req=='all' or update_req=='keytool':\n try:\n with open(os.path.join(self.cordova_app_folder, 'check_keytool.bat'), 'w') as file_opened:\n file_opened.write('where /r \"%ProgramW6432%\\java\" keytool.exe\\nwhere /r \"%ProgramFiles%\\java\" keytool.exe'.decode('utf-8'))\n keytool=subprocess.Popen([os.path.join(self.cordova_app_folder, 'check_keytool.bat')], stdout=subprocess.PIPE)\n result_keytool=keytool.stdout.read()\n try:\n path_keytool=re_keytool.findall(result_keytool.decode('utf-8'))\n except Exception as e:\n raise e\n self.requeriments_store['keytool']=path_keytool\n except Exception as e:\n print(\"Don't find keytool in your system, try install JAVA SDK\")\n print(e )\n if update_req=='all' or update_req=='javac':\n try:\n with open(os.path.join(self.cordova_app_folder, 'check_javac.bat'), 'w') as file_opened:\n file_opened.write('where /r \"%ProgramW6432%\\java\" javac.exe\\nwhere /r \"%ProgramFiles%\\java\" javac.exe'.decode('utf-8'))\n javac=subprocess.Popen([os.path.join(self.cordova_app_folder, 'check_javac.bat')], stdout=subprocess.PIPE)\n result_javac=javac.stdout.read()\n path_javac=re_javac.findall(result_javac.decode('utf-8'))\n self.requeriments_store['javac']=path_javac\n except Exception as e:\n print(\"Don't find javac in your system, try install JAVA SDK\")\n print(e)\n return self.requeriments_store\n elif platform=='linux' or platform=='linux2':\n if update_req=='all' or update_req=='cordova':\n try:\n cordova=subprocess.check_output(['which','cordova'])\n cordova=cordova.strip().split('\\n')[0]\n self.requeriments_store['cordova']=[cordova]\n except Exception as e:\n print(\"Don't find cordova in your system, try install. eg. npm install -g cordova\")\n print(e)\n if update_req=='all' or update_req=='phonegap':\n try:\n phonegap=subprocess.check_output(['which','phonegap'])\n phonegap=phonegap.strip().split('\\n')[0]\n self.requeriments_store['phonegap']=[phonegap]\n except Exception as e:\n print(\"Don't find phonegap in your system, try install. eg. npm install -g phonegap\")\n print(e)\n if update_req=='all' or update_req=='keytool':\n try:\n keytool=subprocess.check_output(['which','keytool'])\n keytool=keytool.strip().split('\\n')[0]\n self.requeriments_store['keytool']=[keytool]\n except Exception as e:\n print(\"Don't find keytool in your system, try install JAVA SDK\")\n print(e )\n if update_req=='all' or update_req=='javac':\n try:\n javac=subprocess.check_output(['which','javac'])\n javac=javac.strip().split('\\n')[0]\n self.requeriments_store['javac']=[javac]\n except Exception as e:\n print(\"Don't find javac in your system, try install JAVA SDK\")\n print(e)\n return self.requeriments_store\n\n def removeCordovaApp(self):\n request = self.request\n\n self.closeServer()\n print('remove:', self.aplication_folder)\n if os.path.exists(self.aplication_folder):\n try:\n shutil.rmtree(self.aplication_folder)\n except Exception as e:\n print(\"Erro on remove:\", self.aplication_folder)\n print(e)\n if platform == \"win32\" or platform == 'cygwin':\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_create_app.bat' % self.aplication_name))\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_server_cordova_run_.bat' % self.aplication_name))\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_create_apk_debug.bat' % self.aplication_name))\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_create_apk_release.bat' % self.aplication_name))\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_platform_browser' % self.aplication_name))\n self._remove_file(os.path.join(self.cordova_app_folder, '%s_cordova_prepare' % self.aplication_name))\n \n def _processImg(self, file, nx, ny):\n request = self.request\n try:\n img = PilImage.open(os.path.join(request.folder,'uploads', file))\n tamanho_max_x = nx\n tamanho_max_y = ny\n x = img.size[0]\n y = img.size[1]\n\n proportion_x=float(tamanho_max_x)/x\n tx_by=tamanho_max_x\n ty_by=int(proportion_x*y)\n\n proportion_y=float(tamanho_max_y)/y\n tx_bx=int(proportion_y*x)\n ty_bx=tamanho_max_y\n\n if ty_by>tamanho_max_y:\n imagem=img.resize((tx_by, ty_by), PilImage.ANTIALIAS)\n cutter=(tamanho_max_y-ty_by)/-2.\n imagem=imagem.crop((0, cutter, tamanho_max_x, cutter+tamanho_max_y))\n\n elif tx_bx>tamanho_max_x:\n imagem=img.resize((tx_bx, ty_bx), PilImage.ANTIALIAS)\n cutter=(tamanho_max_x-tx_bx)/-2.\n imagem=imagem.crop((cutter, 0, cutter+tamanho_max_x, tamanho_max_y))\n else:\n imagem=img.resize((tamanho_max_y, tamanho_max_y), PilImage.ANTIALIAS)\n return imagem\n\n except Exception as e:\n print(\"Error! Process Image\")\n print(e)\n\n def createIcon(self, file_db):\n if file_db:\n icons_sizes={'icon-36-ldpi':(36, 36),\n 'icon-48-mdpi':(48, 48),\n 'icon-72-hdpi':(72, 72),\n 'icon-96-xhdpi':(96, 96),\n 'icon-144-xxhdpi':(144, 144),\n 'icon-192-xxxhdpi':(192, 192)\n }\n for x in icons_sizes.keys():\n file_name = '%s.png' % x\n imagem=self._processImg(file_db, icons_sizes[x][0], icons_sizes[x][1])\n if imagem:\n end_arquivo=os.path.join(self.aplication_folder, 'res', 'icon', 'android', file_name)\n imagem.save(end_arquivo)\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n configxml.addIcons()\n configxml.save()\n else:\n print(\"File dont exist\")\n\n def createSplash(self, file_db, portrait=True):\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n\n if file_db:\n if portrait:\n splash_sizes={\n 'screen-hdpi-portrait':(480, 800),\n 'screen-ldpi-portrait':(200, 320),\n 'screen-mdpi-portrait':(320, 480),\n 'screen-xhdpi-portrait':(720, 1280),\n 'screen-xxhdpi-portrait':(1080, 1920),\n 'screen-xxxhdpi-portrait':(1440, 2560)\n }\n else:\n splash_sizes={\n 'screen-hdpi-landscape':(800, 480),\n 'screen-ldpi-landscape':(320, 200),\n 'screen-mdpi-landscape':(480, 320),\n 'screen-xhdpi-landscape':(1280, 720),\n 'screen-xxhdpi-landscape':(1920, 1080),\n 'screen-xxxhdpi-landscape':(2560, 1440)\n } \n for x in splash_sizes.keys():\n file_name = '%s.png' % x\n imagem=self._processImg(file_db, splash_sizes[x][0], splash_sizes[x][1])\n if imagem:\n end_arquivo=os.path.join(self.aplication_folder, 'res', 'screen', 'android', file_name)\n imagem.save(end_arquivo)\n if portrait:\n configxml.addSplash(portrait=True)\n else:\n configxml.addSplash(portrait=False)\n configxml.save()\n else:\n print(\"File don't exist\")\n \n def createKeystore(self, keytool, \n keyname=\"phantermobile\", \n aliasname='phantermobile', \n validity=10000, \n storepass='yourstorepasslarge',\n keypass='youkeypasslarge',\n CN='Your Name',\n OU='Departament',\n O='Organizacion',\n L='District',\n ST='State',\n C='BR'):\n kargs={\n 'keytool':keytool, \n 'keyname':keyname,\n 'aliasname':aliasname,\n 'validity':validity,\n 'storepass':storepass,\n 'keypass':keypass,\n 'CN':CN,\n 'OU':OU,\n 'O':O,\n 'L':L,\n 'ST':ST,\n 'C':C,\n }\n keytool=keytool.replace('program files', 'progra~1').replace('Program Files', 'Progra~1')\n print(keytool, \"##############################################\")\n args_keytool=\"-genkey -v -keystore %(keyname)s.keystore -alias %(aliasname)s \"\\\n \"-keyalg RSA -keysize 2048 -validity %(validity)s -storepass %(storepass)s -keypass \"\\\n \"%(keypass)s -dname \\\"CN=%(CN)s OU=%(OU)s O=%(O)s L=%(L)s ST=%(ST)s C=%(C)s\\\"\"\n if platform == \"win32\" or platform == 'cygwin':\n args_keytool_map=args_keytool %kargs\n with open(os.path.join(self.cordova_app_folder, 'create_key_%s.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.cordova_app_folder)\n complete_comand=\"%s %s\" %(keytool, args_keytool_map)\n content+=complete_comand\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print(\"creating keystore\")\n subprocess.call([os.path.join(self.cordova_app_folder, 'create_key_%s.bat' %\n self.aplication_name)])\n\n elif platform == \"linux\" or platform == \"linux2\":\n print(\"creating keystore\")\n if os.path.exists(os.path.join(self.cordova_app_folder, \"%s.keystore\" %keyname)):\n self._remove_file(os.path.join(self.cordova_app_folder, \"%s.keystore\" %keyname))\n\n subprocess.call('keytool %s' %args_keytool, cwd=self.cordova_app_folder, shell=True)\n if os.path.exists(os.path.join(self.cordova_app_folder,\"%s.keystore\" %keyname)):\n print(\"Keystore saved in %s!\" %self.cordova_app_folder)\n self._created_key=[os.path.join(self.cordova_app_folder, \"%s.keystore\" %keyname), storepass, aliasname, keypass]\n else:\n print(\"Keystore don't created!!!\")\n return self._created_key\n \n def addPlugIn(self, plugin):\n self._interruptJava()\n if plugin in self.plugins_cordova.keys():\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n check_plugin=configxml.checkPlugin(self.plugins_cordova[plugin][1])\n if not check_plugin:\n if platform == \"win32\" or platform == 'cygwin':\n with open(os.path.join(self.cordova_app_folder, '%s_add_plugin_%s.bat' %(self.aplication_name, plugin)), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content +=\"cordova plugin add %s\" %self.plugins_cordova[plugin][1]\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print('Install plugin \"%s\"' %self.plugins_cordova[plugin][0])\n try:\n subprocess.call(os.path.join(self.cordova_app_folder, '%s_add_plugin_%s.bat' %(self.aplication_name, plugin)))\n except Exception as e:\n print(\"Erros install plugin %s\" %self.plugins_cordova[plugin][0])\n print(e)\n elif platform == \"linux\" or platform == \"linux2\":\n try:\n subprocess.call(\"cordova plugin add %s\" %self.plugins_cordova[plugin][1], cwd=self.aplication_folder, shell=True)\n except Exception as e:\n print(\"Erros install plugin %s\" %self.plugins_cordova[plugin][0])\n print(e) \n else:\n print(\"Don't is possible automatic install of plugin '%s'\" %plugin)\n\n def removePlugIn(self, plugin):\n self._interruptJava()\n if plugin in self.plugins_cordova.keys():\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n check_plugin=configxml.checkPlugin(self.plugins_cordova[plugin][1])\n if check_plugin:\n if platform == \"win32\" or platform == 'cygwin':\n with open(os.path.join(self.cordova_app_folder, '%s_remove_plugin_%s.bat' %(self.aplication_name, plugin)), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content +=\"cordova plugin rm %s\" %self.plugins_cordova[plugin][1]\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print('Install plugin \"%s\"' %self.plugins_cordova[plugin][0])\n try:\n subprocess.call(os.path.join(self.cordova_app_folder, '%s_remove_plugin_%s.bat' %(self.aplication_name, plugin)))\n except Exception as e:\n print(\"Erros install plugin %s\" %self.plugins_cordova[plugin][0])\n print(\"e\")\n elif platform == \"linux\" or platform == \"linux2\":\n try:\n subprocess.call(\"cordova plugin rm %s\" %self.plugins_cordova[plugin][1], cwd=self.aplication_folder, shell=True)\n except Exception as e:\n print(\"Erros install plugin %s\" %self.plugins_cordova[plugin][0])\n print(e) \n\n else:\n print(\"Don't is possible automatic install of plugin '%s'\" %plugin)\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n check_plugin=configxml.checkPlugin(self.plugins_cordova[plugin][1])\n\n def _interruptJava(self):\n for x in range(5):\n time.sleep(1)\n try:\n for proc in psutil.process_iter():\n if proc.name()=='java.exe':\n proc.kill()\n except Exception as e:\n print(e)\n\n def createApk(self, level=\"debug\"):\n \"\"\"\n @level: create apk debug if setted 'debug', create apk release if setted 'release'\n @include_key: is include in apk if keystore exists\n \"\"\"\n self._buildhtml(for_apk=True)\n if os.path.exists(os.path.join(self.aplication_folder, 'package.json')):\n self._remove_file(os.path.join(self.aplication_folder, 'package.json'))\n configxml=parseConfigXML(os.path.join(self.aplication_folder, 'config.xml'))\n engine=configxml.checkEngine('android')\n\n outputfilebase=os.path.join(self.aplication_folder,'platforms', 'android', 'build', 'outputs', 'apk')\n if platform == \"win32\" or platform == 'cygwin':\n if not engine or not os.path.exists(os.path.join(self.aplication_folder,'platforms', 'android')):\n with open(os.path.join(self.cordova_app_folder, '%s_create_apk_build.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n content+=\"cordova platform add android\\n\"\n try:\n content=content.decode('utf-8')\n except:\n pass\n file_opened.write(content)\n print(\"Inserting Android Platform\")\n try:\n apk1=subprocess.call([os.path.join(self.cordova_app_folder, '%s_create_apk_build.bat' %\n self.aplication_name)])\n except Exception as e:\n print(e)\n manifestandroidxml=parseAndroidManifestXML(os.path.join(\n self.request.env.web2py_path, 'cordova', self.request.application, 'platforms','android','AndroidManifest.xml'))\n if configxml.checkNeedInternet():\n manifestandroidxml.addElementRoot('uses-permission', 'name', \"android.permission.INTERNET\")\n else:\n manifestandroidxml.removeElementRoot('uses-permission', 'name', \"android.permission.INTERNET\")\n manifestandroidxml.save()\n\n with open(os.path.join(self.cordova_app_folder, '%s_create_apk_release.bat' % self.aplication_name), 'w') as file_opened:\n content = \"cd %s\\n\" %os.path.join(self.aplication_folder)\n if level=='release':\n if self._created_key:\n outputfile=os.path.join(outputfilebase, 'android-release.apk')\n content+=\"cordova build android --verbose --release -- --keystore=\\\"%s\\\" --storePassword=%s --alias=%s --password=%s\" %(\n self._created_key[0],self._created_key[1],self._created_key[2], self._created_key[3])\n # with open(os.path.join(self.aplication_folder, 'platforms', 'android', 'gradle.properties'), 'w') as file_opened2:\n\n # content2=\"storeFile=%s\\nstorePassword=%s\\nstoreType=pkcs12\\n\" %(self._created_key[0], self._created_key[1])\n # \"keyAlias=%s\\nkeyPassword=%(keypass)s\" %(self._created_key[2], )\n else:\n outputfile=os.path.join(outputfilebase, 'android-release-unsigned.apk')\n content+=\"cordova build android --verbose --release\\n\"\n else:\n outputfile=os.path.join(outputfilebase, 'android-debug.apk')\n content+=\"cordova build android --verbose\\n\"\n try:\n content=content.decode('utf-8')\n except:\n pass \n file_opened.write(content)\n\n procs=subprocess.Popen([os.path.join(self.cordova_app_folder, '%s_create_apk_release.bat' %\n self.aplication_name)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n print('\\n\\n\\n####################################################')\n print('# Creating APK file')\n print(\"# PID: \", procs.pid)\n print('#####################################################\\n\\n\\n')\n while True:\n time.sleep(.1) # so i don't kill the cpu on the machine i'm checking\n try:\n output = procs.stdout.readline()\n except Exception as e:\n print(e)\n break\n if output:\n print(output.strip())\n if 'BUILD SUCCESSFUL' in str(output.strip()):\n break\n\n elif platform == \"linux\" or platform == \"linux2\":\n if not engine:\n subprocess.call([\"cordova platform add android\"], cwd=self.aplication_folder, shell=True)\n manifestandroidxml=parseAndroidManifestXML(os.path.join(\n self.request.env.web2py_path, 'cordova', self.request.application, 'platforms','android','AndroidManifest.xml'))\n if configxml.checkNeedInternet():\n manifestandroidxml.addElementRoot('uses-permission', 'name', \"android.permission.INTERNET\")\n else:\n manifestandroidxml.removeElementRoot('uses-permission', 'name', \"android.permission.INTERNET\")\n manifestandroidxml.save()\n if level=='release':\n if self._created_key:\n subprocess.call([\"cordova build android --verbose --release -- --keystore=\\\"%s\\\" --storePassword=%s --alias=%s\" %(\n self._created_key[0],self._created_key[1],self._created_key[2]\n )], cwd=self.aplication_folder, shell=True)\n else:\n subprocess.call(['cordova build android --verbose --release'], cwd=self.aplication_folder, shell=True)\n else:\n subprocess.call(['cordova build android --verbose'], cwd=self.aplication_folder, shell=True)\n time.sleep(5)\n self._interruptJava()\n print(\"Done!\")\n", "sub_path": "modules/plugin_phantermobileconstructor/phanterandroid.py", "file_name": "phanterandroid.py", "file_ext": "py", "file_size_in_byte": 49795, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "24", "api": [{"api_name": "gluon.current.request", "line_number": 103, "usage_type": "attribute"}, {"api_name": "gluon.current", "line_number": 103, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path", "line_number": 110, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 189, "usage_type": "call"}, {"api_name": "os.path", "line_number": 189, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 190, "usage_type": "call"}, {"api_name": "os.path", "line_number": 190, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 197, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 229, "usage_type": "name"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path", "line_number": 230, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 232, "usage_type": "call"}, {"api_name": "os.path", "line_number": 232, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 232, "usage_type": "call"}, {"api_name": "io.open", "line_number": 233, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 233, "usage_type": "call"}, {"api_name": "os.path", "line_number": 233, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 234, "usage_type": "call"}, {"api_name": "os.path", "line_number": 234, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 243, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 243, "usage_type": "call"}, {"api_name": "os.path", "line_number": 243, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 248, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 248, "usage_type": "call"}, {"api_name": "os.path", "line_number": 248, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 257, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 257, "usage_type": "call"}, {"api_name": "os.path", "line_number": 257, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path", "line_number": 265, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 267, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 269, "usage_type": "call"}, {"api_name": "psutil.Process", "line_number": 270, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 273, "usage_type": "call"}, {"api_name": "urllib2.urlopen", "line_number": 279, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 283, "usage_type": "call"}, {"api_name": "psutil.Process", "line_number": 298, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 327, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 339, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 356, "usage_type": "call"}, {"api_name": "os.path", "line_number": 356, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 359, "usage_type": "call"}, {"api_name": "os.path", "line_number": 359, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 369, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 372, "usage_type": "call"}, {"api_name": "os.path", "line_number": 372, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 374, "usage_type": "call"}, {"api_name": "gluon.compileapp.find_exposed_functions", "line_number": 375, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 378, "usage_type": "call"}, {"api_name": "os.path", "line_number": 378, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 380, "usage_type": "call"}, {"api_name": "gluon.compileapp.find_exposed_functions", "line_number": 381, "usage_type": "call"}, {"api_name": "gluon.html.URL", "line_number": 389, "usage_type": "call"}, {"api_name": "urllib2.urlopen", "line_number": 399, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 403, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 416, "usage_type": "call"}, {"api_name": "os.path", "line_number": 416, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 418, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 424, "usage_type": "name"}, {"api_name": "io.open", "line_number": 425, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 425, "usage_type": "call"}, {"api_name": "os.path", "line_number": 425, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 433, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 433, "usage_type": "call"}, {"api_name": "os.path", "line_number": 433, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 435, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 436, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 444, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 459, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 476, "usage_type": "name"}, {"api_name": "sys.platform", "line_number": 478, "usage_type": "name"}, {"api_name": "psutil.process_iter", "line_number": 482, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 500, "usage_type": "call"}, {"api_name": "os.path", "line_number": 500, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 501, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 504, "usage_type": "call"}, {"api_name": "os.path", "line_number": 504, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 505, "usage_type": "call"}, {"api_name": "os.path", "line_number": 505, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 505, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 506, "usage_type": "call"}, {"api_name": "os.path", "line_number": 506, "usage_type": "attribute"}, {"api_name": "os.unlink", "line_number": 507, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 508, "usage_type": "call"}, {"api_name": "os.path", "line_number": 508, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 511, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 514, "usage_type": "call"}, {"api_name": "os.path", "line_number": 514, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 520, "usage_type": "call"}, {"api_name": "os.path", "line_number": 520, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 522, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 523, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 524, "usage_type": "call"}, {"api_name": "os.path", "line_number": 524, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 524, "usage_type": "call"}, {"api_name": "io.open", "line_number": 526, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 526, "usage_type": "call"}, {"api_name": "os.path", "line_number": 526, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 535, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 535, "usage_type": "call"}, {"api_name": "os.path", "line_number": 535, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 536, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 538, "usage_type": "call"}, {"api_name": "os.path", "line_number": 538, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 538, "usage_type": "call"}, {"api_name": "io.open", "line_number": 540, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 540, "usage_type": "call"}, {"api_name": "os.path", "line_number": 540, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 548, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 548, "usage_type": "call"}, {"api_name": "os.path", "line_number": 548, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 550, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 550, "usage_type": "call"}, {"api_name": "os.path", "line_number": 550, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 552, "usage_type": "call"}, {"api_name": "os.path", "line_number": 552, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 552, "usage_type": "call"}, {"api_name": "io.open", "line_number": 553, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 553, "usage_type": "call"}, {"api_name": "os.path", "line_number": 553, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 554, "usage_type": "call"}, {"api_name": "os.path", "line_number": 554, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 563, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 563, "usage_type": "call"}, {"api_name": "os.path", "line_number": 563, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 568, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 568, "usage_type": "call"}, {"api_name": "os.path", "line_number": 568, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 569, "usage_type": "call"}, {"api_name": "os.path", "line_number": 569, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 576, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 576, "usage_type": "call"}, {"api_name": "os.path", "line_number": 576, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 579, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 580, "usage_type": "call"}, {"api_name": "os.path", "line_number": 580, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 581, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 581, "usage_type": "call"}, {"api_name": "os.path", "line_number": 581, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 582, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 583, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 593, "usage_type": "call"}, {"api_name": "os.path", "line_number": 593, "usage_type": "attribute"}, {"api_name": "os.unlink", "line_number": 595, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 608, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 609, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 610, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 611, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 612, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 615, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 624, "usage_type": "call"}, {"api_name": "io.open", "line_number": 633, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 633, "usage_type": "call"}, {"api_name": "os.path", "line_number": 633, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 635, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 635, "usage_type": "call"}, {"api_name": "os.path", "line_number": 635, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 635, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 647, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 647, "usage_type": "call"}, {"api_name": "os.path", "line_number": 647, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 649, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 649, "usage_type": "call"}, {"api_name": "os.path", "line_number": 649, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 649, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 657, "usage_type": "name"}, {"api_name": "subprocess.check_output", "line_number": 660, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 668, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 676, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 684, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 697, "usage_type": "call"}, {"api_name": "os.path", "line_number": 697, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 699, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 703, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 704, "usage_type": "call"}, {"api_name": "os.path", "line_number": 704, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 705, "usage_type": "call"}, {"api_name": "os.path", "line_number": 705, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 706, "usage_type": "call"}, {"api_name": "os.path", "line_number": 706, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 707, "usage_type": "call"}, {"api_name": "os.path", "line_number": 707, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 708, "usage_type": "call"}, {"api_name": "os.path", "line_number": 708, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 709, "usage_type": "call"}, {"api_name": "os.path", "line_number": 709, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 714, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 714, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 714, "usage_type": "call"}, {"api_name": "os.path", "line_number": 714, "usage_type": "attribute"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 729, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 729, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 734, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 734, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 738, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 738, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 758, "usage_type": "call"}, {"api_name": "os.path", "line_number": 758, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 760, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 760, "usage_type": "call"}, {"api_name": "os.path", "line_number": 760, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 767, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 767, "usage_type": "call"}, {"api_name": "os.path", "line_number": 767, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 792, "usage_type": "call"}, {"api_name": "os.path", "line_number": 792, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 833, "usage_type": "name"}, {"api_name": "io.open", "line_number": 835, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 835, "usage_type": "call"}, {"api_name": "os.path", "line_number": 835, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 836, "usage_type": "call"}, {"api_name": "os.path", "line_number": 836, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 845, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 845, "usage_type": "call"}, {"api_name": "os.path", "line_number": 845, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 848, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 850, "usage_type": "call"}, {"api_name": "os.path", "line_number": 850, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 850, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 851, "usage_type": "call"}, {"api_name": "os.path", "line_number": 851, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 853, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 854, "usage_type": "call"}, {"api_name": "os.path", "line_number": 854, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 854, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 856, "usage_type": "call"}, {"api_name": "os.path", "line_number": 856, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 864, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 864, "usage_type": "call"}, {"api_name": "os.path", "line_number": 864, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 867, "usage_type": "name"}, {"api_name": "io.open", "line_number": 868, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 868, "usage_type": "call"}, {"api_name": "os.path", "line_number": 868, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 869, "usage_type": "call"}, {"api_name": "os.path", "line_number": 869, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 878, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 878, "usage_type": "call"}, {"api_name": "os.path", "line_number": 878, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 882, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 884, "usage_type": "call"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 894, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 894, "usage_type": "call"}, {"api_name": "os.path", "line_number": 894, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 897, "usage_type": "name"}, {"api_name": "io.open", "line_number": 898, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 898, "usage_type": "call"}, {"api_name": "os.path", "line_number": 898, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 899, "usage_type": "call"}, {"api_name": "os.path", "line_number": 899, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 908, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 908, "usage_type": "call"}, {"api_name": "os.path", "line_number": 908, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 912, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 914, "usage_type": "call"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 921, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 921, "usage_type": "call"}, {"api_name": "os.path", "line_number": 921, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 926, "usage_type": "call"}, {"api_name": "psutil.process_iter", "line_number": 928, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 940, "usage_type": "call"}, {"api_name": "os.path", "line_number": 940, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 940, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 941, "usage_type": "call"}, {"api_name": "os.path", "line_number": 941, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseconfigxml.parseConfigXML", "line_number": 942, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 942, "usage_type": "call"}, {"api_name": "os.path", "line_number": 942, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 945, "usage_type": "call"}, {"api_name": "os.path", "line_number": 945, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 946, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 947, "usage_type": "call"}, {"api_name": "os.path", "line_number": 947, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 947, "usage_type": "call"}, {"api_name": "io.open", "line_number": 948, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 948, "usage_type": "call"}, {"api_name": "os.path", "line_number": 948, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 949, "usage_type": "call"}, {"api_name": "os.path", "line_number": 949, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 958, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 958, "usage_type": "call"}, {"api_name": "os.path", "line_number": 958, "usage_type": "attribute"}, {"api_name": "plugin_phantermobileconstructor.phanterparseandroidmanifestxml.parseAndroidManifestXML", "line_number": 962, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 962, "usage_type": "call"}, {"api_name": "os.path", "line_number": 962, "usage_type": "attribute"}, {"api_name": "io.open", "line_number": 970, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 970, "usage_type": "call"}, {"api_name": "os.path", "line_number": 970, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 971, "usage_type": "call"}, {"api_name": "os.path", "line_number": 971, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 974, "usage_type": "call"}, {"api_name": "os.path", "line_number": 974, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 982, "usage_type": "call"}, {"api_name": "os.path", "line_number": 982, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 985, "usage_type": "call"}, {"api_name": "os.path", "line_number": 985, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 993, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 993, "usage_type": "call"}, {"api_name": "os.path", "line_number": 993, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 994, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 1000, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 1011, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 1013, "usage_type": "call"}, {"api_name": "plugin_phantermobileconstructor.phanterparseandroidmanifestxml.parseAndroidManifestXML", "line_number": 1014, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1014, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1014, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 1023, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 1027, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 1029, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 1030, "usage_type": "call"}]}