diff --git "a/837.jsonl" "b/837.jsonl" new file mode 100644--- /dev/null +++ "b/837.jsonl" @@ -0,0 +1,624 @@ +{"seq_id":"53723372","text":"from vos.utils.helpers import load_pretrained_snapshot\nfrom vos.utils.quick_args import save__init__args\nfrom vos.runner.video_mask import VideoMaskRunner\n\nfrom exptools.logging import logger\n\nfrom tqdm import tqdm\nimport sys\nimport torch\nfrom torch.utils import data\n\nclass TwoStageRunner(VideoMaskRunner):\n \"\"\" The runner help with the STM training method.\n \n Details refering to https://arxiv.org/abs/1904.00607 and vos/algo/STM.py\n \"\"\"\n def __init__(self,\n pretrain_optim_epochs,\n pretrain_dataloader,\n max_predata_see= None,\n max_data_see= None, # if the dataset is too large, use these to limit the number of \n # iterations\n **kwargs\n ):\n save__init__args(locals())\n super(TwoStageRunner, self).__init__(**kwargs)\n\n def store_train_info(self, itr_i, train_info, extra_info):\n super(TwoStageRunner, self).store_train_info(itr_i, train_info, extra_info)\n self._store_extra_info(itr_i, extra_info, evaluate= False)\n\n def store_eval_info(self, itr_i, eval_info, extra_info):\n super(TwoStageRunner, self).store_eval_info(itr_i, eval_info, extra_info)\n self._store_extra_info(itr_i, extra_info, evaluate= True)\n\n def log_diagnostic(self, itr_i):\n super(TwoStageRunner, self).log_diagnostic(itr_i)\n self._log_extra_info(itr_i, evaluate= False)\n self._log_extra_info(itr_i, evaluate= True)\n\n def _train_loops(self,\n dataloader,\n eval_dataloader,\n max_optim_epochs,\n max_train_itr,\n itr_i,\n ):\n try:\n for epoch_i in range(max_optim_epochs):\n for batch_i, data in tqdm(enumerate(dataloader)):\n itr_i += 1\n train_info, extra_info = self.algo.train(itr_i, data)\n self.store_train_info(itr_i, train_info, extra_info)\n\n if not eval_dataloader is None and itr_i % self.eval_interval == 0:\n self.model.eval()\n for eval_data in tqdm(eval_dataloader):\n # torch.cuda.empty_cache()\n eval_info, extra_info = self.algo.eval(itr_i, eval_data)\n self.store_eval_info(itr_i, eval_info, extra_info)\n # torch.cuda.empty_cache()\n self.model.train()\n \n if itr_i % self.log_interval == 0:\n self.log_diagnostic(itr_i)\n if max_train_itr is not None and itr_i >= max_train_itr:\n return itr_i\n if not sys.stdin.isatty() and sys.stdin.readline() == \"next\":\n logger.log(f\"User requested, move to next stage at iter: {itr_i}\")\n return itr_i\n except KeyboardInterrupt:\n logger.log(f\"Keyboard interrupt at iter: {itr_i}, move to next stage\")\n return itr_i\n\n def startup(self):\n if self.max_predata_see is not None \\\n and self.max_predata_see < len(self.pretrain_dataloader) * self.pretrain_optim_epochs:\n self.max_pretrain_itr = self.max_predata_see // self.pretrain_dataloader.batch_size\n else:\n self.max_pretrain_itr = None\n if self.max_data_see is not None \\\n and self.max_data_see < len(self.dataloader) * self.max_optim_epochs:\n self.max_train_itr = self.max_data_see // self.dataloader.batch_size\n else:\n self.max_train_itr = None\n super(TwoStageRunner, self).startup()\n\n def train(self, snapshot_filename= None):\n \"\"\" one more image dataset to pre-train the network\n \"\"\"\n self.startup()\n \n if not snapshot_filename is None:\n itr_i = load_pretrained_snapshot(snapshot_filename, self.model, self.algo)\n else:\n itr_i = 0\n \n # pretrain\n itr_i = self._train_loops(\n dataloader= self.pretrain_dataloader,\n eval_dataloader= self.eval_dataloader,\n max_optim_epochs= self.pretrain_optim_epochs,\n max_train_itr= self.max_pretrain_itr,\n itr_i= itr_i,\n )\n logger.log(\"Finish pretraining, start main train at iteration: {}\".format(itr_i))\n torch.cuda.empty_cache()\n # main train\n self._train_loops(\n dataloader= self.dataloader,\n eval_dataloader= self.eval_dataloader,\n max_optim_epochs= self.max_optim_epochs,\n max_train_itr= self.max_train_itr,\n itr_i= itr_i,\n )\n self.shutdown()\n","sub_path":"vos/runner/two_stage.py","file_name":"two_stage.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306804049","text":"# -*- coding:utf-8 -*-\n# @Author : 江湖一笑\n# @Time : 2021/8/10 9:19\n# @Software : Python_study\n# @Python_verison : 3.7\nimport yaml\n\n\n# 将python数据转换成yaml文件\nstream = open('test.yaml','w')\ndata = [1, 2, 'aaa',{'key1':'value1'}]\nyaml.dump(data=data,stream=stream)\nprint(yaml.dump(data))\n\n\n# 将yaml数据转换成python文件\n\n'''\n-表示一个数组\n缩进用空格,不要用tab\n字典使用key:value\n\n'''\nstream1 = '''\n- \n - 2\n - aaa\n- \n key1: value1\n '''\nprint(yaml.load(stream=stream1, Loader =yaml.FullLoader))\n# [[2, 'aaa'], {'key1': 'value1'}]\n\n# 列表嵌套字典\nstream2 = '''\n- \n - 2\n - aaa\n - key1: value1\n '''\nprint(yaml.load(stream=stream2, Loader =yaml.FullLoader))\n# [[2, 'aaa', {'key1': 'value1'}]]\n\n# 字典嵌套列表\nstream2 = '''\ncompanies:\n -\n id: 1\n name: company1\n price: 200W\n'''\n\nprint(yaml.load(stream=stream2, Loader =yaml.FullLoader))\n\n# 复合结构\nstream3 ='''\nlanguages:\n - Ruby\n - Perl\n - Python \nwebsites:\n YAML: yaml.org \n Ruby: ruby-lang.org \n Python: python.org \n Perl: use.perl.org\n'''\nprint(yaml.load(stream=stream3, Loader =yaml.FullLoader))\n\n","sub_path":"第七章-测试框架之数据驱动应用/python处理yaml数据/python处理yaml数据.py","file_name":"python处理yaml数据.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76693915","text":"#!/usr/bin/env python\n\nimport sys\nimport collections\nimport itertools\n\ninfilename = 'input.txt'\nif len(sys.argv) > 2 and sys.argv[1] == '-i':\n infilename = sys.argv[2]\n\nprint('Using input file: %s' % infilename)\n\nf = open(infilename, 'r')\ndata = f.readlines()\nf.close()\n\ndata = [line.strip() for line in data]\n\ncoords = []\nvels = []\n\nfor line in data:\n tokens = line.replace('<', ' ').replace('>', ' ').replace(',', ' ').split()\n coords.append((int(tokens[1]), int(tokens[2])))\n vels.append((int(tokens[4]), int(tokens[5])))\n\ndef print_board(coords):\n x, y = list(zip(*coords))\n min_x = min(x)\n min_y = min(y)\n max_x = max(x)\n max_y = max(y)\n\n if max_x-min_x > 300 or max_y-min_y>100:\n print('Nope')\n return\n\n board = [[' '] * (max_x - min_x+1) for xx in range(max_y - min_y+1)]\n print(len(board))\n print(len(board[0]))\n for x,y in coords:\n print('y', y-min_y, 'x', x-min_x)\n board[y-min_y][x-min_x] = 'X'\n\n for row in board:\n print(''.join(row))\n\ndef get_height(coords):\n x,y=list(zip(*coords))\n return max(x)-min(x)\n\nstates = {0: list(coords)}\ndone = False\ntime = 1\nprev_height = get_height(coords)\nwhile not done:\n new_coords = [(coords[xx][0] + vels[xx][0], coords[xx][1] + vels[xx][1]) for xx in range(len(coords))]\n hh = get_height(new_coords)\n if (hh > prev_height):\n done = True\n else:\n states[time] = list(new_coords)\n coords = list(new_coords)\n prev_height = hh\n time += 1\n\nprint('Time', time)\nprint_board(coords)\n \n","sub_path":"2018/10/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293048596","text":"import mysql.connector\nimport csv\nimport hashlib\nimport json\n\n# Ready config file\nconfig = json.load(open('Connection/config.json'))\ndb = config['connections']['local']\n\n# Connect\ncon = mysql.connector.connect(**db)\n\ninsert_stm = con.cursor()\nselect_stm = con.cursor()\nupdate_stm = con.cursor()\n\ncaminhoImg = 'C:/Users/LFFT/Desktop/Resize/'\ncaminhoCSV = 'C:/Users/LFFT/Desktop/CSV/Lista.csv'\n\nprodutos = []\n\n\ndef gerarMD5(my_string):\n m = hashlib.md5()\n m.update(my_string.encode('utf-8'))\n return m.hexdigest()\n\n\nmeuHash = ''\ncontador = 0\nwith open(caminhoCSV, 'r') as ficheiro:\n ler = csv.reader(ficheiro, delimiter=';')\n\n for linha in ler:\n try:\n with open(caminhoImg + linha[0] + '.jpg', 'rb') as imagem:\n strImg = imagem.read()\n imagem.close()\n '''\n meuHash = gerarMD5(linha[1])\n insert_stm.execute('INSERT INTO images(name,name_original,entity,entity_id,content,mime,md5,created_at)'\n 'VALUES(%s,%s,%s,%s,%s,%s,%s,now())',\n (meuHash + '.jpg', meuHash + '.jpg', 'category', linha[0], strImg, 'image/jpeg',\n meuHash))\n select_stm.execute('SELECT id FROM images WHERE md5=' + \"'\" + meuHash + \"'\")\n str_image = select_stm.fetchone()[0]\n id_image = int(str_image)\n update_stm.execute('UPDATE products SET image_id =%s, updated_at = now() WHERE id =%s',\n (id_image, linha[0]))\n con.commit()\n '''\n contador += 1\n except FileNotFoundError:\n print('Imagem:' + linha[0] + ' nao foi encontradada.')\n ficheiro.close()\ncon.close()\nprint(contador)\n","sub_path":"Image/insertImage.py","file_name":"insertImage.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"448912823","text":"\"\"\"\nRetrieve data from EPA's Integrated Planning Model (IPM) v6\n\nUnlike most of the PUDL data sources, IPM is not an annual timeseries. This file\nassumes that only v6 will be used as an input, so there are a limited number\nof files.\n\"\"\"\n\nimport logging\nfrom pathlib import Path\nimport pandas as pd\nfrom pudl.settings import SETTINGS\nimport pudl.constants as pc\n\nlogger = logging.getLogger(__name__)\n\ndatadir = Path(SETTINGS['epaipm_data_dir'])\npudl_datadir = Path(SETTINGS['pudl_data_dir'])\n\n\ndef get_epaipm_name(file):\n \"\"\"\n Return the appopriate EPA IPM excel file.\n\n Args:\n file (str): The file that we're trying to read data for.\n Returns:\n path to EPA IPM spreadsheet.\n \"\"\"\n if sorted(datadir.glob(file)):\n name = sorted(datadir.glob(file))[0]\n elif sorted(pudl_datadir.glob(file)):\n name = sorted(pudl_datadir.glob(file))[0]\n else:\n raise FileNotFoundError(\n f'No files matching the pattern \"{file}\" were found.'\n )\n\n return name\n\n\ndef get_epaipm_file(filename, read_file_args):\n \"\"\"\n Read in files to create dataframes. No need to use ExcelFile\n objects with the IPM files because each file is only a single sheet.\n\n Args:\n filename: ['single_transmission', 'joint_transmission']\n read_file_args: dictionary of arguments for pandas read_*\n\n Returns:\n xlsx file of EPA IPM data\n \"\"\"\n epaipm_file = {}\n pattern = pc.files_dict_epaipm[filename]\n logger.info(\n f\"Extracting data from EPA IPM {filename} spreadsheet.\")\n\n full_filename = get_epaipm_name(pattern)\n suffix = full_filename.suffix\n\n if suffix == '.xlsx':\n epaipm_file = pd.read_excel(\n full_filename,\n **read_file_args\n )\n elif suffix == '.csv':\n epaipm_file = pd.read_csv(\n full_filename,\n **read_file_args\n )\n # if filename == 'transmission_single':\n # epaipm_xlsx = epaipm_xlsx.reset_index()\n return epaipm_file\n\n\ndef create_dfs_epaipm(files=pc.files_epaipm):\n \"\"\"\n Create a dictionary of pages (keys) to dataframes (values) from epaipm\n tabs.\n\n Args:\n a list of epaipm files\n\n Returns:\n dictionary of pages (key) to dataframes (values)\n\n \"\"\"\n # Prep for ingesting epaipm\n # Create excel objects\n epaipm_dfs = {}\n for f in files:\n # NEEDS is the only IPM data file with multiple sheets. Keeping the overall\n # code simpler but adding this if statement to read both sheets (active and\n # retired by 2021).\n if f == 'plant_region_map_ipm':\n epaipm_dfs['plant_region_map_ipm_active'] = get_epaipm_file(\n f,\n pc.read_excel_epaipm_dict['plant_region_map_ipm_active']\n )\n epaipm_dfs['plant_region_map_ipm_retired'] = get_epaipm_file(\n f,\n pc.read_excel_epaipm_dict['plant_region_map_ipm_retired']\n )\n else:\n epaipm_dfs[f] = get_epaipm_file(\n f,\n pc.read_excel_epaipm_dict[f]\n )\n\n return epaipm_dfs\n\n\ndef extract(epaipm_tables=pc.epaipm_pudl_tables):\n \"\"\"\n Extract data from IPM files.\n\n arga\n ----------\n epaipm_tables (iterable): A tuple or list of table names to extract\n\n Returns:\n -------\n dict\n dictionary of dataframes with extracted (but not yet transformed) data\n from each file.\n \"\"\"\n # Prep for ingesting EPA IPM\n # create raw ipm dfs from spreadsheets\n\n logger.info('Beginning ETL for EPA IPM.')\n\n files = {\n table: pattern for table, pattern in pc.files_dict_epaipm.items()\n if table in epaipm_tables\n }\n\n epaipm_raw_dfs = create_dfs_epaipm(\n files=files\n )\n return epaipm_raw_dfs\n","sub_path":"pudl/extract/epaipm.py","file_name":"epaipm.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181071430","text":"from queue import Queue\n\nclass Node():\n \"\"\"Node in a graph representing a person.\"\"\"\n\n def __init__(self, name, adjacent=None):\n \"\"\"Create a person node with friends adjacent\"\"\"\n\n if adjacent is None:\n adjacent = set()\n\n assert isinstance(adjacent, set), \\\n \"adjacent must be a set!\"\n\n self.name = name\n self.adjacent = adjacent\n\n def __repr__(self):\n \"\"\"Debugging-friendly representation\"\"\"\n\n return f\"\"\n\n\nclass FriendGraph():\n \"\"\"Graph holding people and their friendships.\"\"\"\n\n def __init__(self):\n \"\"\"Create an empty graph\"\"\"\n\n self.nodes = set()\n\n def __repr__(self):\n return f\"\"\n\n def add_person(self, person):\n \"\"\"Add a person to our graph\"\"\"\n\n self.nodes.add(person)\n\n def set_friends(self, person1, person2):\n \"\"\"Set two people as friends\"\"\"\n\n person1.adjacent.add(person2)\n person2.adjacent.add(person1)\n\n def add_people(self, people_list):\n \"\"\"Add a list of people to our graph\"\"\"\n\n for person in people_list:\n self.add_person(person)\n\n def are_connected(self, person1, person2):\n \"\"\"Are two people connected? Breadth-first search.\"\"\"\n\n possible_nodes = Queue()\n seen = set()\n possible_nodes.enqueue(person1)\n seen.add(person1)\n\n while not possible_nodes.is_empty():\n person = possible_nodes.dequeue()\n print(\"checking\", person)\n if person is person2:\n return True\n else:\n for friend in person.adjacent - seen:\n possible_nodes.enqueue(friend)\n seen.add(friend)\n print(\"added to queue:\", friend)\n return False\n\n\ndef make_three_friends(name1,name2,name3):\n friend1 = Node(name1)\n friend2 = Node(name2)\n friend3 = Node(name3)\n\n friends = FriendGraph()\n friends.add_people([friend1,friend2,friend3])\n\n\n friends.set_friends(friend1,friend2)\n friends.set_friends(friend1,friend3)\n friends.set_friends(friend2,friend3)\n\n return friends\n\ngraph = make_three_friends(\"Jimmy\", \"Dustin\", \"Denver\")\nprint(graph.are_connected(\"Jimmy\", \"Dustin\"))","sub_path":"friendshipgraph.py","file_name":"friendshipgraph.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"52056448","text":"import numpy as np\nfrom numpy.polynomial import Polynomial\n\n# from matplotlib import pyplot as plt\n\n# Hermitian cubic interpolation polynomials\n# https://en.wikipedia.org/wiki/Cubic_Hermite_spline\n\np0 = np.array([1,0,-3,2])\nm0 = np.array([0,1,-2,1])\np1 = np.array([0,0,3,-2])\nm1 = np.array([0,0,-1,1])\n\n\ndef gen_hermite_spline(knots, values, extrapolation='constant'):\n '''Generates cubic Hermite spline interpolating given knots and values.\n\n Parameters:\n knots: (n,) ndarray\n values: (n,) ndarray\n \n Returns:\n spline: (n,4) ndarray\n spline[i] contains four coefficients of the polynomial for the\n half-open interval [knots[i],knots[i+1]) and one extrapolated\n polynomial at the right end\n\n '''\n\n # temporary solution\n # derivatives = np.gradient(values,knots)\n derivatives = np.gradient(values)\n\n left = np.outer(values[:-1],p0) + np.outer(derivatives[:-1],m0)\n right = np.outer(values[1:],p1) + np.outer(derivatives[1:],m1)\n\n spline = np.zeros((len(knots),4), float)\n\n spline[:-1] = left + right\n\n # scaling the polynomials\n for i in range(len(spline)-1):\n x_p = knots[i]\n x_n = knots[i+1]\n p = Polynomial(spline[i], domain=[x_p,x_n], window=[0,1])\n p = p.convert()\n spline[i,:len(p.coef)] = p.coef\n\n # extrapolation to the right depends on the preferred extrapolation method\n if extrapolation=='constant':\n spline[-1] = values[-1], 0, 0, 0\n elif extrapolation=='linear':\n k = Polynomial(spline[-2]).deriv()(knots[-1])\n spline[-1] = values[-1], k, 0, 0\n\n return spline\n","sub_path":"splines.py","file_name":"splines.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107665458","text":"\"\"\"Test network models.\"\"\"\nimport pytest\nimport numpy as np\nfrom numpy.random import uniform\nfrom numba import njit\nfrom sdnet.networks import random_network, make_adjacency_matrix\nfrom sdnet.networks import get_edgelist, rewire_edges\nfrom sdnet.utils import make_dist_matrix\n\n\n@njit\ndef _measure(x, y):\n exp = (x + np.fabs(y)).sum()\n return 2**-exp\n\n@pytest.mark.parametrize('N,p,k', [\n (1000, None, 15),\n (1000, 15/999, None),\n])\n@pytest.mark.parametrize('directed', [ True, False ])\ndef test_random_network(N, p, k, directed):\n np.random.seed(1010)\n X = random_network(N, p, k, directed=directed)\n assert abs(X.sum(axis=1).mean() - 15) < 1\n assert X.shape == (N, N)\n\n\n@pytest.mark.parametrize('X', [np.array([[1, 0], [0, -1], [1, 1]])])\n@pytest.mark.parametrize('symmetric', [True, False])\ndef test_make_dist_matrix(X, symmetric):\n P = make_dist_matrix(X, _measure, symmetric=symmetric)\n if symmetric:\n assert np.array_equal(P, P.T)\n else:\n assert not np.array_equal(P, P.T)\n\n\n@pytest.mark.parametrize('P', [uniform(0, 1, (250, 250))])\n@pytest.mark.parametrize('directed', [True, False])\ndef test_make_adjacency_matrix(P, directed):\n np.random.seed(303)\n A = make_adjacency_matrix(P, directed)\n if not directed:\n assert np.array_equal(A, A.T)\n\n@pytest.mark.parametrize('directed', [False, True])\ndef test_get_edgelist(adj_matrix, directed):\n A = adj_matrix\n E = get_edgelist(A, directed=directed)\n A_edges = set((i, j) for i, j in zip(*np.nonzero(A)))\n E_edges = set((i, j) for i, j in zip(E[:, 0], E[:, 1]))\n assert A_edges == E_edges\n if not directed:\n for i in range(0, E.shape[0], 2):\n i1, j1, u1 = E[i]\n i2, j2, u2 = E[i+1]\n assert i1 == j2\n assert j1 == i2\n assert u1 == u2 + 1\n\n@pytest.mark.parametrize('_A', [\n np.array([[0,1,0],[1,0,0],[0,0,0]]),\n make_adjacency_matrix(np.random.uniform(0, .1, (250, 250)))\n])\n@pytest.mark.parametrize('p', [0, 1])\n@pytest.mark.parametrize('directed', [False, True])\n@pytest.mark.parametrize('copy', [False, True])\ndef test_rewire_edges(_A, p, directed, copy):\n A = _A.copy()\n A0 = A\n A = rewire_edges(A, p=p, directed=directed, copy=copy)\n assert not copy or A0 is not A\n assert p == 1 or np.array_equal(A, _A)\n assert p == 0 or not np.array_equal(A, _A)\n assert directed or np.array_equal(A, A.T)\n","sub_path":"test/test_networks.py","file_name":"test_networks.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"493962880","text":"import os\nimport time\nfrom collections import deque\n\nimport PyQt5.QtCore as qtc\nimport PyQt5.QtGui as qtg\nimport PyQt5.QtWidgets as qtw\nimport pyqtgraph as pygraph\nimport pyqtgraph.exporters as exporters\n\nimport mate.net.nao_data as nao_data\nimport mate.net.utils as net_utils\nimport mate.ui.utils as ui_utils\nfrom mate.net.nao import Nao\nfrom mate.ui.panels._panel import _Panel\nfrom . import util\nfrom mate.debug.colorlog import ColorLog\n\nlogger = ColorLog()\n\npygraph.setConfigOption('background', 'w')\npygraph.setConfigOption('foreground', 'k')\n\n\nclass Main(_Panel):\n name = \"Plot\"\n shortcut = qtg.QKeySequence(\"Ctrl+P\")\n data_received_signal = qtc.pyqtSignal(nao_data.DebugValue, str)\n\n def __init__(self, main_window, nao: Nao, model=None):\n super(Main, self).__init__(main_window, self.name, nao)\n ui_utils.loadUi(__file__, self)\n self.model = ui_utils.load_model(os.path.dirname(__file__) +\n \"/model.json\", model)\n\n \"\"\"\n self.data contains the data of curves.\n each curve data is a deque in this list:\n deque:\n - dict\n - \"y\": value # this key should be called 'y'; pyqtgraph\n - \"timestamp\": time received\n deque: ....\n \"\"\"\n self.data = {}\n self.should_update = False\n self.plots = []\n\n self.cbxKey.completer().setFilterMode(qtc.Qt.MatchContains)\n self.cbxKey.completer().setCompletionMode(\n qtw.QCompleter.PopupCompletion)\n\n self.data_received_signal.connect(self.data_received)\n self.spinFps.valueChanged.connect(self.set_fps)\n self.spinBufferSize.valueChanged.connect(self.set_buffer_size)\n self.legendCheckBox.stateChanged.connect(self.set_show_legend)\n\n self.listWidget.itemSelectionChanged.connect(self.select_curve)\n self.btnAccept.clicked.connect(self.accept)\n self.btnDiscard.clicked.connect(self.discard)\n self.btnAddCurve.clicked.connect(self.add_curve)\n self.btnDeleteCurve.clicked.connect(self.delete_curve)\n self.btnColor.clicked.connect(self.select_color)\n self.btnSnap.clicked.connect(self.snap)\n self.edit_color.returnPressed.connect(\n lambda: ui_utils.reset_textField_color(\n self.edit_color,\n self.edit_color.text()))\n\n self.update_list()\n\n self.timer = qtc.QTimer()\n self.timer.timeout.connect(self.update)\n\n self.reset_fps_spin()\n self.reset_buffer_size_spin()\n self.reset_show_legend()\n\n self.tabWidget.currentChanged.connect(self.tab_changed)\n self.tabWidget.setCurrentIndex(self.model[\"selected_tab\"])\n\n self._init_datalist()\n self._init_plot()\n\n self.data_received_signal.connect(self.data_received)\n\n if self.nao.is_connected():\n self.connect(self.nao)\n\n def set_fps(self):\n self.model[\"fps\"] = self.spinFps.value()\n\n def snap(self):\n # Get size of plotItem and create ImageExporter\n width = self.plot_widget.plotItem.size().width()\n height = self.plot_widget.plotItem.size().height()\n exporter = exporters.ImageExporter(self.plot_widget.plotItem)\n # Set resolution, force int type, new value may not be == to old value\n exporter.params.param('width'). \\\n setValue(int(width * 4), blockSignal=exporter.widthChanged)\n exporter.params.param('height'). \\\n setValue(int(height * 4), blockSignal=exporter.heightChanged)\n # Set filepath and export\n location_suggestion = os.path.join(os.getcwd(), \"plot.png\")\n location, _ = qtw.QFileDialog. \\\n getSaveFileName(self.widget(),\n \"Save snap\",\n location_suggestion,\n options=qtw.QFileDialog.Options())\n if location == '':\n # If export is cancelled, exit gracefully\n logger.debug(__name__ + \": Saving Snapshot aborted.\")\n return\n exporter.export(location)\n\n def reset_fps_spin(self):\n self.spinFps.setValue(self.model[\"fps\"])\n\n def set_buffer_size(self):\n self.model[\"buffer_size\"] = self.spinBufferSize.value()\n\n def reset_buffer_size_spin(self):\n self.spinBufferSize.setValue(self.model[\"buffer_size\"])\n\n def set_show_legend(self):\n self.model[\"show_legend\"] = self.legendCheckBox.isChecked()\n\n def reset_show_legend(self):\n self.legendCheckBox.setChecked(self.model[\"show_legend\"])\n\n def select_color(self):\n ui_utils.pick_color(self.edit_color, self.edit_color.text())\n\n def fill_drop_down(self):\n self.cbxKey.clear()\n for key, data in self.nao.debug_data.items():\n if not data.isImage:\n self.cbxKey.addItem(key)\n\n def connect(self, nao: Nao):\n self.nao = nao\n self.fill_drop_down()\n self.nao.debug_protocol.subscribe_msg_type(\n net_utils.DebugMsgType.list, self.identifier, self.fill_drop_down)\n self.subscribe_keys()\n self.timer.start(1000 / self.model[\"fps\"])\n # self.init_plot()\n # self.init_datalist()\n\n def tab_changed(self, index: int):\n self.model[\"selected_tab\"] = index\n\n if self.model[\"selected_tab\"] == util.TabType.plot.value:\n self.subscribe_keys()\n self._init_datalist()\n self._init_plot()\n self.update()\n if self.nao.is_connected():\n self.timer.start(1000 / self.model[\"fps\"])\n else:\n self.unsubscribe_keys()\n self.timer.stop()\n\n def _init_plot(self):\n self.plot_widget.clear()\n if self.plot_widget.plotItem.legend is not None:\n self.plot_widget.plotItem.legend.scene().removeItem(\n self.plot_widget.plotItem.legend)\n self.plot_widget.plotItem.legend = None\n if self.model[\"show_legend\"]:\n self.plot_widget.addLegend()\n\n self.plots = []\n for curve in self.model[\"curves\"]:\n if curve[\"enabled\"]:\n color = curve[\"color\"]\n else:\n color = \"#555555\"\n self.plots.append(\n self.plot_widget.plot(\n name=curve[\"name\"], pen={\n 'color': color,\n 'width': 2\n }))\n\n def _init_datalist(self):\n self.data = {}\n for curve in self.model[\"curves\"]:\n self.data[curve[\"identifier\"]] = deque()\n\n def update_list(self):\n self.listWidget.clear()\n for curve in self.model[\"curves\"]:\n self.listWidget.addItem(curve[\"name\"])\n\n def update(self):\n if self.should_update:\n for curve, plot in zip(self.model[\"curves\"], self.plots):\n plot.setData(self.data[curve[\"identifier\"]])\n self.should_update = False\n\n def data_received(self, data: net_utils.Data, identifier: str):\n data = self.apply_lambda(data, identifier)\n while len(self.data[identifier]) > 0 and time.time() - self.data[identifier][0][\"timestamp\"] > self.model[\"buffer_size\"]:\n self.data[identifier].popleft()\n if type(data) is list:\n for datum in data:\n self.data[identifier].append({\"y\": datum, \"timestamp\": time.time()})\n else:\n self.data[identifier].append({\"y\": data, \"timestamp\": time.time()})\n self.should_update = True\n\n def apply_lambda(self, data: net_utils.Data, identifier: str):\n scope = {\"input\": data.data, \"output\": None}\n filtered = list(filter(lambda curve: curve[\"identifier\"] == identifier,\n self.model[\"curves\"]))\n if len(filtered):\n exec(filtered[0][\"key_lambda\"], scope)\n else:\n # TODO: Do something useful here\n logger.warning(\"Curve not found by identifier \" + identifier)\n return scope[\"output\"]\n\n def select_curve(self):\n util.select_curve(self.listWidget.currentRow(), self.model)\n if self.model[\"selected_curve\"] is not None:\n self.reset_curve_config()\n self.formWidget.setEnabled(True)\n\n @property\n def selected_curve_config(self):\n return self.model[\"curves\"][self.model[\"selected_curve\"]]\n\n def reset_curve_config(self):\n self.nameLineEdit.setText(self.selected_curve_config[\"name\"])\n self.enabledCheckBox.setChecked(self.selected_curve_config[\"enabled\"])\n self.cbxKey.setCurrentText(self.selected_curve_config[\"key\"])\n self.edit_lambda.setText(self.selected_curve_config[\"key_lambda\"])\n ui_utils.reset_textField_color(self.edit_color,\n self.selected_curve_config[\"color\"])\n\n def accept(self):\n self.model[\"curves\"][self.model[\"selected_curve\"]] = \\\n util.create_curve(self.nameLineEdit.text(),\n self.enabledCheckBox.isChecked(),\n self.cbxKey.currentText(),\n self.edit_lambda.toPlainText(),\n self.edit_color.text())\n self.update_list()\n\n def discard(self):\n self.select_curve()\n\n def add_curve(self):\n self.model[\"curves\"].append(util.create_curve())\n self.update_list()\n\n def delete_curve(self):\n # TODO: Delete does not update config section\n self.model[\"curves\"].pop(self.listWidget.currentRow())\n self.update_list()\n if self.listWidget.count() == 0:\n self.formWidget.setEnabled(False)\n\n def subscribe_keys(self):\n for curve in self.model[\"curves\"]:\n if curve[\"enabled\"]:\n self.subscribe(curve[\"key\"], curve[\"identifier\"])\n\n def subscribe(self, key: str, identifier: str):\n if self.nao.is_connected():\n self.nao.debug_protocol.subscribe(\n key, identifier,\n lambda d: self.data_received_signal.emit(d, identifier))\n\n def unsubscribe_keys(self):\n if self.nao.is_connected():\n for curve in self.model[\"curves\"]:\n if curve[\"enabled\"]:\n self.nao.debug_protocol.unsubscribe(curve[\"key\"],\n curve[\"identifier\"])\n\n def closeEvent(self, event):\n self.unsubscribe_keys()\n self.deleteLater()\n super(Main, self).closeEvent(event)\n","sub_path":"tools/mate/mate/ui/panels/plot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"320833583","text":"# youtube part\nvideo_params_base = {\"part\": \"id,snippet,statistics\",\n \"id\": \"\",\n \"key\": \"\"}\n\nchannel_params_base = {\"part\": \"id,snippet,statistics\",\n \"id\": \"\",\n \"key\": \"\"}\n\ncomment_params_base = {\"part\": \"id,snippet\",\n \"videoId\": \"\",\n \"key\": \"\",\n \"order\": \"relevance\"}\n\n\ndef gen_video_param(video_id, key):\n ret_res = video_params_base\n ret_res[\"id\"] = video_id\n ret_res[\"key\"] = key\n return ret_res\n\n\ndef gen_channel_param(channel_id, key):\n ret_res = channel_params_base\n ret_res[\"id\"] = channel_id\n ret_res[\"key\"] = key\n return ret_res\n\n\ndef gen_comment_param(video_id, key):\n ret_res = comment_params_base\n ret_res.update({\"maxResults\": 1})\n ret_res[\"videoId\"] = video_id\n ret_res[\"key\"] = key\n return ret_res\n\n\n# twitter part\n","sub_path":"NoVTBs/param_generator.py","file_name":"param_generator.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"99222818","text":"import dash_html_components as html\r\nimport dash_core_components as dcc\r\n\r\n\r\ndef Header(app):\r\n return html.Div([get_header(app), html.Br([]), get_menu()])\r\n\r\n\r\ndef get_header(app):\r\n header = html.Div(\r\n [\r\n html.Div(\r\n [\r\n html.Img(\r\n src=app.get_asset_url(\"lumen_logo_dark.jpg\"),\r\n className=\"logo\",\r\n ),\r\n html.A(\r\n html.Button(\"InsideLink\", id=\"learn-more-button\"),\r\n href=\"https://centurylink.sharepoint.com\",\r\n ),\r\n ],\r\n className=\"row\",\r\n ),\r\n html.Div(\r\n [\r\n html.Div(\r\n [html.H5(\"Newsletter\")],\r\n className=\"seven columns main-title\",\r\n ),\r\n ],\r\n className=\"twelve columns\",\r\n style={\"padding-left\": \"0\"},\r\n ),\r\n ],\r\n className=\"row\",\r\n )\r\n return header\r\n\r\n\r\ndef get_menu():\r\n menu = html.Div(\r\n [ \r\n html.H5(\"Helpful HR Links:\", style={\"color\": \"#ffffff\"}),\r\n html.Br(),\r\n html.A(\r\n \"U.S. 2021 Holiday Calendar\",\r\n href=\"https://centurylinkenterprise.us.newsweaver.com/centurylinkhumanresources.16yj0vo8jm/x4hs10nc4zthrtishrij6e/external?email=true&a=6&p=4405827&t=680337\",\r\n className=\"tab first\",\r\n ),\r\n html.A(\r\n \"COVID-19 Resources\",\r\n href=\"https://centurylinkenterprise.us.newsweaver.com/centurylinkhumanresources.2f5cdlil3r/j2fewl5v158hrtishrij6e/external?email=true&a=5&p=4318228&t=1402038\",\r\n className=\"tab\",\r\n ),\r\n html.A(\r\n \"Internal Jobs\",\r\n href=\"https://internaljobs.centurylink.com/?locale=en_US\",\r\n className=\"tab\",\r\n ),\r\n html.A(\r\n \"HealthVUE App\",\r\n href=\"https://centurylink.sharepoint.com/SitePages/HealthVUE-Launch.aspx\",\r\n className=\"tab\",\r\n ),\r\n html.A(\r\n \"Richard Batelaan Replay of Jan. 19 All-Hands\",\r\n href=\"https://web.microsoftstream.com/video/b26ebeb5-e6d4-4c34-9d69-4ebe6184be1f\",\r\n className=\"tab\",\r\n ),\r\n ],\r\n className=\"row all-tabs\",\r\n )\r\n return menu\r\n\r\n\r\ndef make_dash_table(df):\r\n \"\"\" Return a dash definition of an HTML table for a Pandas dataframe \"\"\"\r\n table = []\r\n for index, row in df.iterrows():\r\n html_row = []\r\n for i in range(len(row)):\r\n html_row.append(html.Td([row[i]]))\r\n table.append(html.Tr(html_row))\r\n return table\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37323915","text":"from prototype import *\nimport time\n\nstart_time = time.time()\n\nhome_dir = '/home/chengte'\ntarget_root = 'targets/cb-multios'\n\n#prepare stage\nopen_qemu_mode('init')\nscp_guest('crax_exploit/guest_need', True)\nscp_guest('crax_exploit/guest_need2', True)\nssh_guest('cd ' + home_dir + '/guest_need && make')\nssh_guest('cd ' + home_dir + '/guest_need2 && make')\nssh_guest('cd ' + home_dir + ' && mkdir cb-multios')\nscp_guest(target_root + '/build', True)\nscp_guest(target_root + '/processed-challenges/On_Sale', True)\nssh_guest('mv build cb-multios')\nssh_guest('mv On_Sale cb-multios')\nvm_name = 'on_sale_t'\ncontrol_qemu('savevm ' + vm_name)\ncontrol_qemu('quit')\n\nprint('Execution time:', time.time() - start_time, 'second(s)')\n","sub_path":"run/py_codes/on_sale.py","file_name":"on_sale.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"599155954","text":"\"\"\"\nCopyright 2020 EraseKesu (class Erase#0027)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport discord\nimport datetime\n\nfrom discord.ext import commands, timers\n\n\nclass Meta(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def source(self, ctx):\n embed = discord.Embed(\n title=\"Source\",\n description=\"https://github.com/EraseKesu/Chorus\"\n )\n await ctx.send(embed=embed)\n\n @commands.command()\n async def feedback(self, ctx, *feedback):\n msg = ' '.join(feedback)\n\n embed = discord.Embed(\n title=\"Feedback\",\n description=f\"\"\"\n```css\n[ {msg} ] ~{ctx.author}\n``` \"\"\",\n colour=0x0EF7E2\n )\n emb = discord.Embed(\n title=\"Thanks For Your Feedback!\",\n description=\"Thanks for your feedback! We will try to improve as soon as possible!\",\n colour=0x0EF7E2\n )\n emb.set_footer(\n text=\"Join our support server! `https://discord.gg/YUm2sBD`\",\n icon_url=self.bot.user.avatar_url_as(static_format=\"png\")\n )\n\n channel = await self.bot.fetch_channel(694887120669507635)\n await channel.send(embed=embed)\n await ctx.send(embed=emb)\n\n @commands.command()\n async def invite(self, ctx):\n await ctx.send(\"https://discordapp.com/api/oauth2/authorize?client_id=685521236646035490&permissions=8&scope=bot\")\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def setup(self, ctx):\n staff = await ctx.guild.create_role(name=\"staff\")\n muted = await ctx.guild.create_role(name=\"Muted\")\n await staff.edit(administrator=True)\n await muted.edit(send_messages=False)\n embed = discord.Embed(\n title=\"Setup complete\",\n description=\"I have created the 'staff' and the 'Muted' role please change their permissions to your liking\"\n )\n await ctx.send(embed=embed)\n\n @commands.command()\n async def remind(self, ctx, time, timeval=None, *, text):\n x = \"\"\n unit = \"\"\n if \"/\" in time:\n date = datetime.datetime(*map(int, time.split(\"/\")))\n if timeval is not None:\n if timeval == \"week\":\n x = \"in \"\n unit = \"week\"\n date = datetime.timedelta(weeks=time)\n if timeval == \"weeks\":\n x = \"in \"\n unit = \"weeks\"\n date = datetime.timedelta(weeks=time)\n if timeval == \"month\":\n x = \"in \"\n unit = \"month\"\n date = datetime.timedelta(weeks=time*4)\n if timeval == \"months\":\n x = \"in \"\n unit = \"months\"\n date = datetime.timedelta(weeks=time*4)\n if timeval == \"year\":\n x = \"in \"\n unit = \"year\"\n date = datetime.timedelta(weeks=time*52)\n if timeval == \"years\":\n x = \"in \"\n unit = \"years\"\n date = datetime.timedelta(weeks=time*52)\n if timeval == \"day\":\n x = \"in \"\n unit = \"day\"\n date = datetime.timedelta(days=time)\n if timeval == \"days\":\n x = \"in \"\n unit = \"days\"\n date = datetime.timedelta(days=time)\n else:\n text = timeval + \" \" + text\n if time == \"tomorrow\":\n unit = \"\"\n x = \"\"\n date = datetime.timedelta(days=1)\n timers.Timer(self.bot, \"reminder\", date, args=(ctx.channel.id, ctx.author.id, text)).start()\n await ctx.send(f\"Ok, {ctx.author.mention}, i will remind you {x}{time}{unit}: {text}\")\n\n @commands.Cog.listener()\n async def on_reminder(self, channel_id, author_id, text):\n channel = self.bot.get_channel(channel_id)\n author = self.bot.get_user(author_id)\n await channel.send(f\"Hey {author.mention}, Im just pinging you so you don't forget to {text}\")\n\n\ndef setup(bot):\n bot.add_cog(Meta(bot))\n","sub_path":"cogs/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328647505","text":"import random\nglobal lives_remaining\nglobal display_word\nglobal display_word\n\nwords=[\"chicken\", \"dog\", \"cat\",\" mouse\",\"frog\"]\n\nlives_remaining=14\nguessed_letters=\"\"\n\ndef say_hello(sentence):\n print(sentence+\"^^\")\n return\n\ndef pick_a_word():\n return random.choice(words)\n\ndef print_word_with_blanks(word):\n display_word=\"\"\n for letter in word:\n if guessed_letters.find(letter) > -1:\n display_word = display_word + letter\n else:\n display_word = display_world + '-'\n print(display_word)\n\ndef get_guess(word):\n print_word_with_blanks(word)\n print('Live Remaining:'+str(lives_remaining))\n guess = input('Guess a letter or whole word?')\n return guess\n\ndef single_letter_guess(guess, word): \n if word.find(guess) == -1:\n lives_remaining = lives_remaining -1\n guessed_letters = guessed_letters + guess\n if all_letters_guessed(word):\n return True\n return False\n\ndef all_letters_guess(guess, word): \n global guessed_letters\n for letter in word:\n if guessed_letters.find(letter) == -1:\n return False\n return True\n\ndef whole_word_guess(guess, word):\n global lives_remaining \n if guess == word:\n return True\n else:\n lives_remaining = lives_remaining -1\n return False\n \n guessed_letters = guessed_letters + guess\n return False\n\n\ndef process_guess(guess, word):\n global lives_remaining\n global guessed_letters\n lives_remaining = lives_remaining - 1\n guessed_letters = guessed_letters + guess\n return False\n \n\ndef play():\n word = pick_a_word()\n while True:\n guess = get_guess(word)\n if process_guess(guess, word):\n print('You win')\n break\n if live_remaing==0:\n print('you are end')\n print('The word was :'+word)\n break\n \nplay()\n","sub_path":"py/basic/say_hello.py","file_name":"say_hello.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187679215","text":"from any_worksheet import *\nfrom sumrule import sumrule\n\ndef solve_for_2d(my_question):\n\tc_my_q = cleanpar(my_question,'x')\n\tycount = []\n\tfor i in range(0,38):\n\t\tycount.append(0)\n\tfdsl = fullderivative_y(c_my_q,'x',ycount,'y')\n\tycount = fdsl[1]\n\tycount_intl = ''\n\tfor i in range(0,38):\n\t\tycount_intl = ycount_intl+str(ycount[i])\n\tfdsl = fdsl[0]\n\n\tycount = []\n\tfor i in range(0,38):\n\t\tycount.append(0)\n\tfdsr = fullderivative_y(fdsl,'x',ycount,'y')\n\tycount = fdsr[1]\n\tycount_intr = ''\n\tfor i in range(0,38):\n\t\tycount_intr = ycount_intr+str(ycount[i])\n\tfdsr = fdsr[0]\n\n\treturn fdsr,ycount_intl,ycount_intr\n\ndef get_question(q_id):\n\ttrig_fns = ['cos(x)','sin(x)','tan(x)','cot(x)','sec(x)','csc(x)']\n\ttrig_fns_l = ['\\cos{(x)}','\\sin{(x)}','\\\\tan{(x)}','\\cot{(x)}','\\sec{(x)}','\\csc{(x)}']\n\tinv_trigs = ['arccos(x)','arcsin(x)','arctan(x)','arccot(x)','arcsec(x)','arccsc(x)']\n\tpolys = ['x^2+1','x^3+x-1','x+3','x^2-2x+3','x^5','x^4-x^2+x','2x^3','2x^2+x+1','x^3+5x^2-3x+2','2x-1']\n\n\tif q_id == 'One':\n\t\tq_1 = str(get_rand(range(2,11),[.25,.25,.15,.1,.05,.05,.05,.05,.05]))\n\n\t\tin_fs = [get_rand_poly('x'),get_rand_poly('x'),'ln(x)','e^x+'+str(random.randint(1,9)),get_rand(trig_fns,[.25,.25,.15,.15,.1,.1])]\n\t\tx_r = random.randint(0,1)\n\t\tin_fn = in_fs[x_r]\n\n\t\treturn ''+in_fn, ''+in_fn\n\telif q_id == 'Two':\n\t\tq_1 = get_rand_poly('x')\n\t\treturn ''+q_1, ''+q_1\n\telif q_id == 'Three':\n\t\tq_1 = get_rand(trig_fns,[.25,.25,.15,.15,.1,.1])\n\t\tq_2 = get_rand_poly('x')\n\t\tq_1 = q_1.replace('x','y')\n\t\treturn q_2,q_2\n\telif q_id == 'Four':\n\t\tif random.random()<.3:\n\t\t\treturn get_question('One')\n\t\telse:\n\t\t\tif random.random()<.4:\n\t\t\t\treturn get_question('Three')\n\t\t\telse:\n\t\t\t\treturn get_question('Two')\n\telif q_id == 'Five':\n\t\tif random.random()<.3:\n\t\t\treturn get_question('One')\n\t\telse:\n\t\t\tif random.random()<.6:\n\t\t\t\treturn get_question('Two')\n\t\t\telse:\n\t\t\t\treturn get_question('Three')\n\nclass WorksheetForm(forms.Form):\n\tyour_name = forms.CharField(label='',widget=forms.TextInput(attrs={'placeholder': 'Enter answer here.','size':'30','onKeyPress':\"checkSubmit(event)\",'onKeyUp':\"setTimeout(doLatex.bind(null,event,this.value),500)\"}))\nimport traceback\ndef any_worksheet(form,sheet_name,new_q,my_type):\n\tsend_message = 'something wrong!'\n\tif(form.is_valid()):\n\t\tnew_data = form.cleaned_data['your_name'].replace('\\\\','||')\n\t\tsend_message = json.loads(new_data)\n\t\tmy_answer = addpar(escape(send_message['yn']))\n\t\tmy_question = send_message['yq']\n\n\t\tif my_question != 'LATEX':\n\t\t\ttry:\n\t\t\t\tt1 = time.time()\n\t\t\t\tmy_question_l = send_message['yq_l'].replace('||','\\\\')\n\t\t\t\tmy_type = send_message['yt']\n\t\t\t\tnew_q = get_question(my_type)\n\t\t\t\tfor i in range(0,10):\n\t\t\t\t\tif new_q[0]==my_question:\n\t\t\t\t\t\tnew_q = get_question(my_type)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\tt2 = time.time()\n\t\t\t\tfds = solve_for_2d(my_question)\n\t\t\t\tycount_intl = fds[1]\n\t\t\t\tycount_intr = fds[2]\n\t\t\t\tfds = fds[0]\n\n\t\t\t\n\t\t\t\tt3 = time.time()\n\t\t\t\tc_my_answer = cleanpar(my_answer,'x')\n\t\t\t\tc_fds = cleanpar(fds,'x')\n\t\t\t\tif checksame(c_my_answer,c_fds,'x'):\n\t\t\t\t\tmessage=get_rand([\"That's it!\",'Got it!','Nailed it!','Right on!','Good job!','Way to go!','Nice!','Correct!','',''],[.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])\n\t\t\t\telse:\n\t\t\t\t\tmessage= 'NO!'\n\t\t\t\tt4 = time.time()\n\n\t\t\t\tmy_function= {'var':'x','q':my_question}\n\t\t\t\tmy_function = urllib.parse.urlencode(my_function)\n\t\t\t\ttarget = open('/home/django/data/'+sheet_name+'_ders_'+my_type+'.txt','a')\n\t\t\t\tmy_target = File(target)\n\t\t\t\tif message == 'NO!':\n\t\t\t\t\ttarget.write(my_question+','+c_my_answer+','+c_fds+','+ycount_intl+','+ycount_intr+','+'N'+','+str(round(t2-t1,3))+','+str(round(t3-t2,3))+','+str(round(t4-t3,3))+'\\n')\n\t\t\t\telse:\n\t\t\t\t\ttarget.write(my_question+','+c_my_answer+','+c_fds+','+ycount_intl+','+ycount_intr+','+'Y'+','+str(round(t2-t1,3))+','+str(round(t3-t2,3))+','+str(round(t4-t3,3))+'\\n')\n\t\t\t\ttarget.close()\n\n\t\t\t\tsend_message = {'message':message,'equation_python':new_q[0],'equation_latex':new_q[1],'my_q':my_question_l,'my_a':slatex(c_my_answer,'x'),'c_a':slatex(c_fds,'x'),'my_function':my_function}\n\t\t\texcept Exception as e:\n\t\t\t\tmessage = \"Error reading answer: \"+my_answer+\". Try again.\"\n\t\t\t\ttarget = open('/home/django/data/'+sheet_name+'_ders_'+my_type+'.txt','a')\n\t\t\t\tmy_target = File(target)\n\t\t\t\ttarget.write(my_question+','+my_answer+','+str(e)+','+'error'+','+'E'+',-1,-1,-1\\n')\n\t\t\t\ttarget.close()\n\t\t\t\tsend_message= {'message':message}\n\t\telse:\n\t\t\ttry:\n\t\t\t\tmessage = slatex(cleanpar(addpar(my_answer),'x'),'x')\n\t\t\texcept:\n\t\t\t\ttry:\n\t\t\t\t\tif my_answer == '':\n\t\t\t\t\t\tmessage = ''\n\t\t\t\t\telse:\n\t\t\t\t\t\tmessage = '\\\\text{Preview unavailable...}'\n\t\t\t\texcept:\n\t\t\t\t\tmessage = '\\\\text{Preview unavailable...}'\n\n\t\t\tsend_message= {'message':message}\n\n\treturn HttpResponse(json.dumps(send_message))\n\ndef second_derivative_worksheet(request):\n\tif request.method == \"POST\":\n\t\tform = WorksheetForm(request.POST)\n\t\tif (form.is_valid()):\n\t\t\tnew_data = form.cleaned_data['your_name'].replace('\\\\','||')\n\t\t\tsend_message = json.loads(new_data)\n\t\t\tmy_question = send_message['yq']\n\t\t\tif my_question != 'LATEX':\n\t\t\t\ttry:\n\t\t\t\t\tmy_type = send_message['yt']\n\t\t\t\t\tnew_q = get_question(my_type)\n\t\t\t\t\tfor i in range(0,10):\n\t\t\t\t\t\tif new_q[0]==my_question:\n\t\t\t\t\t\t\tnew_q = get_question(my_type)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\treturn any_worksheet(form,'imp_diff',new_q,my_type)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\treturn any_worksheet(form,'imp_diff','noq','Zero')\n\t\t\n\tq_id = 'One'; gq = get_question(q_id)\n\tvsections = [{'title':'Implicit Differentiation','subsections':[{'title':'Powers','id':q_id,'form':WorksheetForm(),'equation_python':gq[0],'equation_latex':gq[1],'classinit':'BB'}]}]\n\tq_id = 'Two'; gq = get_question(q_id)\n\tvsections[0]['subsections'].append({'title':'Logarithms','id':q_id,'form':WorksheetForm(),'equation_python':gq[0],'equation_latex':gq[1],'classinit':'B'})\n\tq_id = 'Three'; gq = get_question(q_id)\n\tvsections[0]['subsections'].append({'title':'Trigonometry','id':q_id,'form':WorksheetForm(),'equation_python':gq[0],'equation_latex':gq[1],'classinit':'B'})\n\tq_id = 'Four'; gq = get_question(q_id)\n\tvsections[0]['subsections'].append({'title':'Exponentials','id':q_id,'form':WorksheetForm(),'equation_python':gq[0],'equation_latex':gq[1],'classinit':'B'})\n\t\n\tq_id = 'Five'; gq = get_question(q_id)\n\tvsections.append({'title':'Advanced','subsections':[{'title':'Double Chain','id':q_id,'form':WorksheetForm(),'equation_python':gq[0],'equation_latex':gq[1],'classinit':'B'}]})\n\n\tnum_subsections = 0\n\tfor i in vsections:\n\t\tnum_subsections = num_subsections+len(i['subsections'])\n\tfrac_q = str(round(1./num_subsections,5))\n\trcarr = [{'href':'second_derivative_lesson.html','title':'Second Derivative Lesson'},{'href':'product_rule_worksheet.html','title':'Product Rule Worksheet'},{'href':'quotient_rule_worksheet.html','title':'Quotient Rule Worksheet'},{'href':'#','title':'Chain Rule Video'},{'href':'#','title':'Chain Rule Explained'}]\n\tmeta_title = 'Second Derivative Worksheet - Learn Second Derivatives by working examples with Calculus College.'\n\tmeta_des = \"Infinitely many second derivative problems with step-by-step solutions if you make a mistake. Progress through several types of problems that help you improve.\"\n\treturn render(request,'base_worksheet_2d.html',{'related_content':rcarr,'meta-des':meta_des,'title':meta_title,'header_1':'Second Derivative Worksheet','sections':vsections,'fraction_questions':frac_q})\n\n\n","sub_path":"calculus/lessons/second_derivative_worksheet.py","file_name":"second_derivative_worksheet.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"447465499","text":"import random\n\nclass mob:\n def __init__(self, name_, weapon_, hp_, ac_lower_range_, ac_upper_range_):\n self.name = name_\n self.weapon = weapon_\n self.hp = hp_\n self.ac_lower = ac_lower_range_\n self.ac_upper = ac_upper_range_\n \n def ac(self):\n ac = random.randrange(self.ac_lower, self.ac_upper)\n return ac\n \n def fight(self, opponent):\n print(f\"{self.name} took a swing at {opponent.name}\")\n hit = self.ac() - opponent.ac()\n\n if(hit > 0):\n dmg = hit + wepDmg[self.weapon]\n print(f\"You hit the {opponent.name} for \" + str(dmg))\n opponent.hp -= dmg\n else:\n print(\"You missed\")\n \n def flight(self, opponent):\n print(f\"{self.name} tries to run away from {opponent.name}\")\n hit = self.ac() - opponent.ac()\n\n if(hit > 0):\n print(\"You escaped\")\n return False\n\n else:\n fight(self, opponent)\n\n\nwepDmg = {\n \"Great Axe\": 20,\n \"Sword\": 10,\n \"Bow\": 15\n}\n\n\ndef encounter(hero, mob):\n\n print(f\"{hero.name} encountered a {mob.name} wielding a {mob.weapon}\")\n print(\"Type the a key and then RETURN to attack.\")\n\n state = True\n while state:\n action = input()\n\n if action.lower() == \"a\":\n hero.fight(mob)\n\n if action.lower() == \"e\":\n state = hero.flight(mob)\n\n if mob.hp < 1:\n print(\"You killed your foe!\")\n state = False\n\n else:\n print(f\"The {mob.name} has {mob.hp} HP remaining\")\n\n\nfoe = mob(\"Troll\", \"Great Axe\", 200, 30, 40)\nhero = mob(\"Hero\", \"Sword\", 100, 35, 45)\n\n# encounter(hero, foe)\n","sub_path":"game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"278452272","text":"# This file is part of the pyBinSim project.\n#\n# Copyright (c) 2017 A. Neidhardt, F. Klein, N. Knoop, T. Köllmer\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\nimport multiprocessing\n\nimport numpy as np\nimport pyfftw\nfrom scipy.io.wavfile import read\n\nfrom pybinsim.utility import pcm2float\n\nnThreads = multiprocessing.cpu_count()\n\n\nclass FilterStorage(object):\n \"\"\" Class for storing all filters mentioned in the filter list \"\"\"\n\n def __init__(self, irSize, block_size, filter_list_name):\n print('FilterStorage: init')\n\n self.ir_size = irSize\n self.ir_blocks = irSize // block_size\n self.block_size = block_size\n # self.filterListPath=os.path.join(os.path.dirname(__file__),filterListName)\n self.filter_list_path = filter_list_name\n self.filter_list = open(self.filter_list_path, 'r')\n\n # Filter format: [nBlocks,blockSize*4]\n # 0 to blockSize*2: left filter\n # blockSize*2 to blockSize*4: right filter\n self.default_filter = np.zeros([self.ir_blocks, 2 * (block_size + 1)], np.dtype(np.float32))\n\n self.fftw_plan = pyfftw.builders.rfft(np.zeros(block_size * 2), overwrite_input=True,\n planner_effort='FFTW_MEASURE',\n threads=nThreads)\n\n # format: [key,{filterLeft,filterRight}]\n self.filter_dict = {}\n\n # Start to load filters\n self.load_filters()\n\n def load_filters(self):\n \"\"\"\n Load filters from files\n\n :return: None\n \"\"\"\n for line in self.filter_list:\n # Read line content\n line_content = line.split()\n\n filter_value_list = tuple(line_content[0:-1])\n filter_path = line_content[-1]\n\n # Extend value list to support older filter lists\n # if (len(filter_value_list) < 6):\n # filter_value_list = (filter_value_list + (0,) * 6)[:6]\n # print(\"filter value list incomplete\")\n\n # load filter\n print('Loading ' + filter_path)\n # _,current_filter = read(os.path.join(os.path.dirname(__file__),filter_path))\n _, current_filter = read(filter_path)\n current_filter = pcm2float(current_filter, 'float32')\n filter_size = np.shape(current_filter)\n\n # Fill filter with zeros if to short\n if filter_size[0] < self.ir_size:\n print('Filter to short: Fill up with zeros')\n current_filter = np.concatenate((current_filter, np.zeros((self.ir_size - filter_size[0], 2))), 0)\n\n # Transform filter to freq domain before storing\n transformed_filter = self.transform_filter(current_filter)\n\n # create key and store in dict.\n key = self.create_key_from_values(filter_value_list)\n self.filter_dict.update({key: transformed_filter})\n\n def transform_filter(self, filter):\n \"\"\"\n Transform filter to freq domain\n\n :param filter:\n :return: transformed filter\n \"\"\"\n IR_left = filter[:, 0]\n IR_right = filter[:, 1]\n\n # Split IRs in blocks\n IR_left_blocked = np.reshape(IR_left, (self.ir_blocks, self.block_size))\n IR_right_blocked = np.reshape(IR_right, (self.ir_blocks, self.block_size))\n\n # Add zeroes to each block\n IR_left_blocked = np.concatenate((IR_left_blocked, np.zeros([self.ir_blocks, self.block_size])), axis=1)\n IR_right_blocked = np.concatenate((IR_right_blocked, np.zeros([self.ir_blocks, self.block_size])), axis=1)\n\n TF_left_blocked = np.zeros([self.ir_blocks, self.block_size + 1], np.dtype(np.complex64))\n TF_right_blocked = np.zeros([self.ir_blocks, self.block_size + 1], np.dtype(np.complex64))\n\n for ir_block_count in range(0, self.ir_blocks):\n TF_left_blocked[ir_block_count] = self.fftw_plan(IR_left_blocked[ir_block_count])\n TF_right_blocked[ir_block_count] = self.fftw_plan(IR_right_blocked[ir_block_count])\n\n # Concatenate left an right filter for storage\n transformed_filter = np.concatenate((TF_left_blocked, TF_right_blocked), axis=1)\n return transformed_filter\n\n def get_filter(self, filter_value_list):\n \"\"\"\n Searches in the dict if key is available and return corresponding filter\n When no filter is found, defaultFilter is returned which results in silence\n\n :param filter_value_list:\n :return: corresponding filter for key\n \"\"\"\n\n key = self.create_key_from_values(filter_value_list)\n\n if key in self.filter_dict:\n print('Filter found: key: ' + key)\n return (self.filter_dict.get(key)[:, 0:self.block_size + 1],\n self.filter_dict.get(key)[:, (self.block_size + 1):2 * (self.block_size + 1)])\n else:\n print('Filter not found; key: ' + key)\n return (self.default_filter[:, 0:self.block_size + 1],\n self.default_filter[:, (self.block_size + 1):2 * (self.block_size + 1)])\n\n def create_key_from_values(self, filter_value_list):\n \"\"\"\n Just create the key\n\n :param filter_value_list:\n :return: key created from filter_value_list\n \"\"\"\n key = ','.join(map(str, filter_value_list))\n return key\n\n def close(self):\n print('FilterStorage: close()')\n # TODO: do something in here?\n","sub_path":"pybinsim/filterstorage.py","file_name":"filterstorage.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347249754","text":"\n# coding: utf-8\n\n# In[11]:\n\n\n\"\"\"currency.py: This python checks money exchanging rates.\n\n__author__ = \"Kow Pu Ern\"\n__pkuid__ = \"1700094617\"\n__email__ = \"newbieern2@hotmail.com\"\n\"\"\"\n\nfrom urllib.request import urlopen\n\n#This function locates a string in a list\ndef index_lookup(arr,item):\n return [i for i,a in enumerate(arr) if a==item]\n\n#This function removes unwanted characters in output string\ndef remove(s):\n a = \"b\" + \"'\" + '\"'\n b = \"\"\n for eachChar in s:\n if eachChar not in a:\n b = b + eachChar\n return b\n\n#Currenct exchanging function\ndef exchange(currency_from, currency_to, amount_from): \n doc = urlopen('http://cs1110.cs.cornell.edu/2016fa/a1server.php?from={}&to={}&amt={}'.format(currency_from, currency_to, amount_from))\n doc_line1 = doc.read()\n doc.close()\n doc_list = doc_line1.split()\n n = index_lookup(doc_list,b'\"to\"')\n m = int(n[0]) + 2\n output_raw = str(doc_list[m])\n output_curr = remove(output_raw)\n return(output_curr)\n\n#Testing functions.\ndef test_A():\n assert (exchange('USD','EUR','130') == str(108.95235))\n \ndef test_B():\n assert (exchange('TWD','MYR','100') == str(14.060022109734))\n\ndef testall():\n test_A()\n test_B()\n print(\"All tests passed\")\n \n#Main timeline\ndef main():\n a = input()\n b = input()\n c = input()\n a_str = str(a)\n b_str = str(b)\n c_str = str(c)\n print (exchange(a,b,c))\n\nif __name__ == '__main__':\n testall()\n main()\n\n","sub_path":"pyassign2/currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585117361","text":"import telebot\nfrom bot import constants\nimport re\nimport requests\nfrom time import gmtime, strftime\n\nBot = None\n\nstart_flag = False\nif_alert = False\nlocation = False\n\n\ndef start(message):\n \"\"\"\n registration\n :param message:\n :return:\n \"\"\"\n global Bot\n global start_flag\n Bot.send_message(message.from_user.id,\n 'Введіть дані (українською):\\n'\n '(Прізвище_Ім\\'я_По батькові_Група_Номер телефону)\\n'\n 'Зразок: Шкіцький_Володимир_Володимирович_265_+380951234567')\n start_flag = True\n print('start')\n\n\ndef check_for_correct(text):\n data = text.split('_')\n flag = False\n if data[0].isalpha() and re.match(r'^[А-Я,І,і]', data[0]):\n if data[1].isalpha() and re.match(r'^[А-Я,І,і]', data[1]):\n if data[2].isalpha() and re.match(r'^[А-Я,І,і]', data[2]):\n if data[3].isdigit() and data[3].__len__() == 3:\n if re.match(r'^\\+380[5,6,7,9][0-9]{8}$', data[4]):\n flag = True\n return flag\n\n\ndef add_cadet(message):\n \"\"\"\n add cadet data to database\n :param message:\n :return:\n \"\"\"\n global start_flag\n\n for id_c in constants.db:\n if str(message.from_user.id) == (str(id_c).split())[0]:\n Bot.send_message(message.from_user.id, 'Ви вже додані до бази даних як:\\n' + ((str(id_c).split())[1]))\n start_flag = False\n return\n\n with open('bd.txt', 'a', encoding='utf-8') as fio:\n if check_for_correct(str(message.text)):\n fio.write(str(message.from_user.id) + ' ' + str(message.text) + '\\n')\n user_markup = telebot.types.ReplyKeyboardMarkup(True)\n user_markup.row('Відмітка про перебування поза межами інституту', 'Сповістити про зауваження чи загрозу')\n Bot.send_message(message.from_user.id, 'Вас успішно занесено до бази даних', reply_markup=user_markup)\n start_flag = False\n else:\n Bot.send_message(message.from_user.id, \"Введіть інформацію за поданим зразком\")\n\n\ndef get_location(message):\n global if_alert\n global location\n r = requests.get(constants.google_map_url + str(message.location.latitude) + ',' + str(\n message.location.longitude) + constants.google_map_url_2)\n j = r.json()\n s = ''\n for i in (range(8))[::-1]:\n try:\n s += (str(j['results'][0]['address_components'][i]['long_name']) + ' ')\n except IndexError:\n s += ''\n if if_alert:\n with open('alert.txt', 'a', encoding='utf-8') as fio:\n fio.write(str(message.from_user.id) + '__-__' + s + ' | ' + strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()) + '\\n')\n print(\"Done\")\n Bot.send_message(message.from_user.id, \"Done\")\n if_alert = False\n if location:\n with open('location.txt', 'a', encoding='utf-8') as fio:\n fio.write(str(message.from_user.id) + '__-__' + s + ' | ' + strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()) + '\\n')\n print(\"Done\")\n Bot.send_message(message.from_user.id, \"Done\")\n location = False\n\n\ndef message_alert(message):\n global if_alert\n\n with open('alert_message.txt', 'a', encoding='utf-8') as fio:\n fio.write(str(message.from_user.id) + '__-__' + str(message.text) + ' | ' + strftime(\"%Y-%m-%d %H:%M:%S\",\n gmtime()) + '\\n')\n print(\"Done\")\n Bot.send_message(message.from_user.id, \"Done\")\n\n if_alert = False\n","sub_path":"bot/bussines.py","file_name":"bussines.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94733926","text":"# Imports\nimport gensim\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom gensim.parsing.preprocessing import preprocess_string, strip_tags\nfrom gensim.parsing.preprocessing import strip_punctuation, strip_multiple_whitespaces\nfrom gensim.parsing.preprocessing import stem_text, strip_numeric, strip_short\nfrom gensim.corpora import Dictionary\n\n# Scitkit Learn Imports\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import TruncatedSVD as LSA\nfrom sklearn.decomposition import NMF\nfrom sklearn.decomposition import LatentDirichletAllocation as LDA\n\n\ndef clean_str(string):\n \"\"\"Cleans and tokenizes a string with some functions from gensim.\n\n Input: A string\n Output: A lists of tokenized words\"\"\"\n return preprocess_string(string, filters=[strip_tags, strip_punctuation,\n strip_numeric, strip_multiple_whitespaces,\n strip_short])\n\ndef create_vocabulary(series_of_strings, min_count=20, max_percent=0.05, keep_n=10000):\n \"\"\"Tokenizes words in the list_of_strings and filters extremes.\n Returns a set of words that comprise a vocabulary based on the\n input strings\"\"\"\n # all_words = series_of_strings.apply(lambda row: preprocess_string(row))\n all_words = Dictionary(series_of_strings.apply(lambda row: clean_str(row)))\n all_words.filter_extremes(no_below=min_count, no_above=max_percent, keep_n=keep_n)\n return set(all_words.values())\n\ndef tokenize(string):\n \"\"\"Cleans and tokenizes a string and returns a list of strings that are in\n VOCABULARY\"\"\"\n words_in_string = clean_str(string)\n return [word for word in words_in_string if word in VOCABULARY]\n\ndef run_models(data, vectorizers, models, n_topics, tokenizer, vocabulary):\n \"\"\"Provides a pipeline functionality in order to frun multiple vectorizers,\n models and number of topics.\"\"\"\n for vkey, vectorizer in vectorizers.items():\n vec = vectorizer(tokenizer=tokenizer, stop_words='english', ngram_range=(1,2))\n vectorizer_fit = vec.fit_transform(data)\n for mkey, model in models.items():\n for n in n_topics:\n model_instance = model(n_components=n)\n word_vector = model_instance.fit_transform(vectorizer_fit)\n print('Shape of topics vector:', word_vector.shape)\n print('notes/output_file_{}_{}_{}.txt'.format(vkey,mkey, n))\n if mkey == 'LSA':\n print(model_instance.components_)\n if mkey == 'NMF':\n nmf = model_instance\n\n terms = vec.get_feature_names()\n with open('notes/output_file_{}_{}_{}.txt'.format(vkey,mkey, n), 'w') as notes:\n for idx, comp in enumerate(model_instance.components_):\n terms_in_components = zip(terms, comp)\n sorted_terms = sorted(terms_in_components, key=lambda x: x[1], reverse=True)\n notes.write('Topic {}\\n:'.format(idx))\n for i, term in enumerate(sorted_terms[:10]):\n notes.write('{} '.format(term[0]))\n notes.write('\\n')\n\n print('Pickling Vectorizer...')\n with open('pickles/vectorizer_{}_{}_{}.pkl'.format(vkey,mkey, n), 'wb') as f:\n pickle.dump(vec, f)\n\n print('Pickling model object...')\n with open('pickles/model_{}_{}_{}.pkl'.format(vkey,mkey, n), 'wb') as f:\n pickle.dump(model_instance, f)\n\n print('Pickling document topic object...')\n with open('pickles/doc_topic_{}_{}_{}.pkl'.format(vkey,mkey, n), 'wb') as f:\n pickle.dump(word_vector, f)\n return 0\n\nif __name__ == '__main__':\n\n # Load dataset\n fp = pd.read_csv('~/p4/data/interim/fp_posts.csv')\n fp = fp.drop(['url', 'img', 'created'], axis=1)\n fp['before'] = fp['title'].copy()\n fp['title'] = fp.title.str.replace(r'\\d+', '')\n fp['title'] = fp.title.str.replace(r'\\[.*\\]', '')\n fp['title'] = fp.title.str.replace(r'[^A-Za-z\\s]', '')\n\n # Create a vocabulary. The vocabulary filters out extremes values so that\n # only words that appear more than a set number of times are included.\n VOCABULARY = create_vocabulary(fp.title, min_count=20)\n with open('pickles/vocabulary.pkl', 'wb') as f:\n pickle.dump(VOCABULARY, f)\n\n # Set up test parameters and run models.\n # test_vecs = {'cv': CountVectorizer, 'tfidf': TfidfVectorizer}\n test_vecs = {'tfidf': TfidfVectorizer}\n # test_models = {'LSA': LSA, 'NMF': NMF, 'LDA': LDA}\n test_models = {'NMF': NMF}\n # test_n_topics = [10, 15, 20, 25, 50]\n test_n_topics = [20]\n run_models(fp.title, test_vecs, test_models, test_n_topics, tokenize, VOCABULARY)\n","sub_path":"flask/LSA_LDA_NMF.py","file_name":"LSA_LDA_NMF.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151817772","text":"\n# Housekeeping\n#\nimport os\nimport shutil\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\n\n#\n# Math\n#\nimport numpy as np\nimport math\n\n#\n# Plotting\n#\nimport matplotlib as mpl\nimport matplotlib.pylab as plt\n\n#\n# Materials\n#\nimport ip_dip_dispersion\n\n#\n# Optimizer\n#\nimport NeuralSplitterOptimization2D\n\n\nif len( sys.argv ) < 2:\n\tprint( \"Usage: python \" + sys.argv[ 0 ] + \" { save folder }\" )\n\tsys.exit( 1 )\n\nsave_folder = sys.argv[ 1 ]\n\nrandom_seed = 12341234\n\nmesh_size_nm = 50\ndensity_coarsen_factor = 1#3\nmesh_size_m = mesh_size_nm * 1e-9\n# lambda_min_um = 1.0#1.4\nlambda_min_um = 0.9\nlambda_max_um = 1.5#1.6\nlambda_mid_um = 0.5 * ( lambda_min_um + lambda_max_um )\n\nmin_relative_permittivity = 1.0**2\nmax_relative_permittivity = 1.5**2\n# max_relative_permittivity = 2.4**2\n\nnum_lambda_values = 1#2#3\n\n# lambda_values_um = np.linspace( lambda_min_um, lambda_max_um, num_lambda_values )\nlambda_values_um = np.array( [ lambda_min_um ] )\n# lambda_values_um = np.array( [ lambda_min_um, lambda_max_um ] )\n\n\n# device_width_voxels = 198#300\ndevice_width_voxels = 3 * 198#300\n# device_width_voxels = 204#300\n# device_width_voxels = 150\n# device_height_voxels = 201\n# device_height_voxels = 102\ndevice_height_voxels = 3 * 150\n\n# device_height_voxels = 50\n# device_width_voxels = 50\n\n\ndesign_width = device_width_voxels // density_coarsen_factor\ndesign_height = device_height_voxels // density_coarsen_factor\n\nnum_layers = design_height\n\n\n#\n# we should also probably optimize that each scattering does something different\n# also should get each focal point some intensity to start with\n# and finally should see if it scatters enough\n# also is learning rate high enough - and are different enough profiles properly going inton\n# the optimizations?\n#\n\n\n# focal_length_voxels = device_width_voxels // 2\nfocal_length_voxels = 2 * device_width_voxels // 3\n\n# encapsulation_length_voxels = 60\n# encapsulation_length_voxels = 150\n# encapsulation_length_voxels = 20\nencapsulation_length_voxels = 10\n# encapsulation_length_voxels = 40\n# max_sample_height_voxels = 18#60\n# max_sample_height_voxels = 150\nmax_sample_height_voxels = 80\n\nmax_sample_change_step_voxels = 50#100#20\n\n\n\n# num_focal_points = 11#4\n# num_focal_points = 6\nnum_focal_points = 3\nspace_per_focal_point = 1. / num_focal_points\nfocal_points_x_relative = [ space_per_focal_point * ( idx + 0.5 ) for idx in range( 0, num_focal_points ) ]\n\n\n# sample_coarseness_sensing_voxels = 15\n# sample_coarseness_sensing_voxels = 10\n# sample_coarseness_sensing_voxels = 33\n# sample_coarseness_sensing_voxels = 66\nsample_coarseness_sensing_voxels = 44\n\nangles_deg = [ -5, 0, 5 ]\n\n\nmake_optimizer = NeuralSplitterOptimization2D.NeuralSplitterOptimization2D(\n\t[ device_width_voxels, device_height_voxels ],\n\tdensity_coarsen_factor, mesh_size_nm,\n\t[ min_relative_permittivity, max_relative_permittivity ],\n\tfocal_points_x_relative, focal_length_voxels,\n\tencapsulation_length_voxels, max_sample_height_voxels, max_sample_change_step_voxels,\n\tsample_coarseness_sensing_voxels,\n\tlambda_values_um, angles_deg, random_seed,\n\tnum_layers, save_folder)\n\n# num_iterations = 50#50#20\nnum_iterations = 25#20\n# num_iterations = 25\nnum_internal_iterations = 10\nnum_test_samples = 200#400#100#5#50\nnum_validation_samples = 100#200#25#3#10\n\n\n# num = 5\n# for idx in range( 0, num ):\n# \ttest = make_optimizer.create_test_sample()\n# \tplt.plot( mesh_size_nm * np.linspace( 0, make_optimizer.simulation_width_voxels, make_optimizer.simulation_width_voxels ) / 1000., test, linewidth=3 )\n# \tplt.show()\n\nmake_optimizer.optimize( num_iterations, num_internal_iterations, num_test_samples, num_validation_samples, save_folder )\n\n\n\n\n","sub_path":"inverse_design/Landscape/neural_splitter.py","file_name":"neural_splitter.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"473672294","text":"import json\nfrom flask import Flask, render_template, request\nimport requests\n\nfrom packages.functions import projects_to_timeline, project_to_timeline, get_projects\n\napp = Flask(__name__)\n\nBASEURL = 'http://127.0.0.1:5050'\n\n@app.route('/project/')\ndef project(id):\n project_id = request.args.get('id', id)\n\n r = requests.get('{}/projects/{}'.format(BASEURL, project_id)).json()\n bla = project_to_timeline(r)\n print(bla)\n\n header_data = []\n projects = requests.get('{}/projects'.format(BASEURL)).json()\n for project in projects:\n header_data.append(\n {\n 'id': project['id'],\n 'name': project['project']\n }\n )\n\n return render_template(\n 'project.html', group_data=bla['group_data'],\n item_data=bla, option_data=bla['item_data'],\n api_data=r, header_data=header_data\n )\n\n\n@app.route('/addproject', methods=['POST'])\ndef addproject():\n\n if request.method == 'POST':\n payload = {}\n form = request.form\n\n payload = {\n 'project': form['projectname'],\n 'clientstartdate': form['clientstartdate'].replace('-', ' '),\n 'clientenddate': form['clientenddate'].replace('-', ' ')\n }\n\n post_project = requests.post('{}/projects'.format(BASEURL), params=payload)\n\n r = requests.get('{}/projects'.format(BASEURL)).json()\n bla = projects_to_timeline(r)\n\n employees = requests.get('{}/employees'.format(BASEURL)).json()\n\n return render_template(\n 'overview.html', group_data=bla['group_data'],\n item_data=bla['item_data'], option_data=bla['option_data'],\n employees=employees\n )\n\n\n@app.route('/putproject', methods=['POST'])\ndef putproject():\n\n if request.method == 'POST':\n user_data = {}\n form = request.form\n\n user_data['project_id'] = form['taskproject']\n user_data['group'] = form['taskgroup']\n\n p = requests.put('{}/projects/{}?group={}'.format(BASEURL, user_data['project_id'], user_data['group']))\n\n r = requests.get('{}/projects/{}'.format(BASEURL, 1)).json()\n bla = project_to_timeline(r)\n\n return render_template(\n 'project.html', group_data=bla['group_data'],\n item_data=bla['item_data'], option_data=bla['option_data'],\n api_data=r\n )\n\n\n@app.route('/task/')\ndef task(id):\n\n task_id = request.args.get('id', id)\n task = requests.get('{}/tasks/{}'.format(BASEURL, task_id)).json()[0]\n\n # Build nac header data\n header_data = []\n projects = requests.get('{}/projects'.format(BASEURL)).json()\n for project in projects:\n header_data.append(\n {\n 'id': project['id'],\n 'name': project['project']\n }\n )\n\n return render_template(\n 'task.html', api_data=task, header_data=header_data\n )\n\n\n@app.route('/addtask', methods=['POST'])\ndef addtask():\n # TODO: fix output. also, need to get project id from frorm on the frontend.\n\n if request.method == 'POST':\n form = request.form\n user_task = {}\n\n if 'newgroup' in form:\n user_task['project'] = form['taskproject']\n\n else:\n\n # form = request.form\n user_task['name'] = form['taskname']\n user_task['startdate'] = form['taskstartdate']\n user_task['enddate'] = form['taskenddate']\n user_task['group'] = 2\n user_task['project'] = form['taskproject']\n\n for x in user_task:\n if user_task[x] == '':\n user_task[x] = None\n\n post_task = requests.post(\n '{}/tasks?name={}&group={}&startdate={}&enddate={}&project={}'.format(\n BASEURL, user_task['name'], user_task['group'], user_task['startdate'],\n user_task['enddate'], user_task['project']\n )\n )\n\n r = requests.get('{}/projects/{}'.format(BASEURL, user_task['project'])).json()\n bla = project_to_timeline(r)\n\n employees = requests.get('{}/employees'.format(BASEURL)).json()\n\n return render_template(\n 'project.html', group_data=bla['group_data'], api_data=r,\n item_data=bla['item_data'], option_data=bla['option_data']\n )\n\n\n@app.route('/puttask', methods=['POST'])\ndef puttask():\n user_data = {}\n if request.method == 'POST':\n form = request.form\n\n user_data['name'] = form['taskname']\n user_data['task_id'] = form['task_id']\n user_data['startdate'] = form['taskstartdate']\n user_data['enddate'] = form['taskenddate']\n user_data['project_id'] = form['project_id']\n user_data['group'] = form['taskgroup']\n user_data['taskproject'] = form['taskproject']\n\n payload = {\n 'name': user_data['name'],\n 'group': user_data['group'],\n 'startdate': user_data['startdate'],\n 'enddate': user_data['enddate'],\n 'taskproject': user_data['taskproject']\n }\n\n p = requests.put('{}/tasks/{}'.format(BASEURL, user_data['project_id']), params=payload)\n\n task = requests.get('{}/tasks/{}'.format(BASEURL, user_data['task_id'])).json()[0]\n\n return render_template(\n 'task.html', api_data=task\n )\n\n\n@app.route('/addemployee', methods=['POST'])\ndef addemployee():\n\n if request.method == 'POST':\n form = request.form\n\n employeename = form['employeename']\n\n r = requests.get('{}/projects'.format(BASEURL)).json()\n bla = projects_to_timeline(r)\n\n employees = requests.get('{}/employees'.format(BASEURL)).json()\n\n return render_template(\n 'overview.html', group_data=bla['group_data'],\n item_data=bla['item_data'], option_data=bla['option_data'],\n employees=employees\n )\n\n\n@app.route('/')\ndef overview():\n # TODO: shortcuts to all artist\n\n header_data = []\n r = requests.get('{}/projects'.format(BASEURL)).json()\n timeline_data = projects_to_timeline(r)\n\n # build data for nav bar\n for project in r:\n header_data.append(\n {\n 'id': project['id'],\n 'name': project['project']\n }\n )\n\n employees = requests.get('{}/employees'.format(BASEURL)).json()\n\n return render_template(\n 'overview.html', group_data=timeline_data['group_data'],\n item_data=timeline_data['item_data'], option_data=timeline_data['option_data'],\n employees=employees, header_data=header_data\n )\n\n\n@app.route('/artist/')\ndef artist(id):\n artist_id = request.args.get('id', id)\n artist_data = requests.get('http://127.0.0.1:5050/employees/{}'.format(artist_id)).json()[0]\n\n timeline_data = projects_to_timeline(artist_data['projects'])\n # stripping out all project data from artist_data, as the project data\n # will get sent via timeline_data. So that im sending less data overall?\n # is there a better way?\n del artist_data['projects']\n\n # build current groups\n groups = []\n for x in timeline_data['item_data']:\n if 'id' in x:\n groups.append(x['id'])\n\n # refactor this try/except for something nicer.\n try:\n task_group = max(groups)\n except:\n task_group = 0\n\n for x in artist_data['tasks']:\n task_group += 1\n timeline_data['item_data'].append(\n {\n 'id': task_group,\n 'content': x['content'],\n 'start': x['start'],\n 'title': 'a title',\n 'group': 1\n }\n )\n\n header_data = []\n projects = requests.get('{}/projects'.format(BASEURL)).json()\n for project in projects:\n header_data.append(\n {\n 'id': project['id'],\n 'name': project['project']\n }\n )\n\n\n return render_template(\n 'artist.html', artist=artist_data, group_data=timeline_data['group_data'],\n item_data=timeline_data['item_data'], option_data=timeline_data['option_data'],\n header_data=header_data\n )\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5000)\n\n\n# milestones for timeline\n\"\"\"\n{\n 'id': 2,\n 'content': 'Draft',\n 'start': '2014-01-25',\n 'group': 1,\n 'style': 'background-color:green;'\n},\n{\n 'id': 3,\n 'content': 'First Draft',\n 'start': '2014-01-30',\n 'group': 1,\n 'style': 'background-color:red;'\n},\n{\n 'id': 4,\n 'content': 'Final',\n 'start': '2014-02-09',\n 'group': 1\n},\n\"\"\"\n","sub_path":"slots/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"388871495","text":"#!/usr/bin/env python\n\n# Copyright 2013 Google Inc. All Rights Reserved.\n\n\"\"\"Convenience tool for non .py Cloud SDK commands.\n\nReads a property from config and prints it to stdout.\n\"\"\"\n\n# pylint: disable=g-bad-import-order, Import this first so the python version\n# check happens before anything else.\nimport bootstrapping\n\nimport argparse\nimport sys\n\nfrom googlecloudsdk.core import config\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('item')\n args = parser.parse_args()\n\n project, account = bootstrapping.GetActiveProjectAndAccount()\n\n # pylint:disable=superfluous-parens\n if args.item == 'multistore_path':\n print(config.Paths().LegacyCredentialsMultistorePath(account))\n elif args.item == 'json_path':\n print(config.Paths().LegacyCredentialsJSONPath(account))\n elif args.item == 'gae_java_path':\n print(config.Paths().LegacyCredentialsGAEJavaPath(account))\n elif args.item == 'project':\n print(project)\n else:\n print('Valid keys are multistore_path, json_path, gae_java_path, or '\n 'project.')\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"y/google-cloud-sdk/.install/.backup/bin/bootstrapping/print_env_info.py","file_name":"print_env_info.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232294955","text":"from troposphere import Base64, Join\nfrom troposphere import Parameter, Ref, Template\nfrom troposphere import cloudformation\nimport troposphere.ec2 as ec2\n\nimport json\nimport boto3\nimport sys\nimport argparse\n#from simplesecuritygroups.template import SecurityGroups, SecurityGroup\nfrom troposphere import (Base64,\n cloudformation,\n FindInMap,\n GetAtt,\n GetAZs,\n Join,\n Parameter,\n Output,\n Ref,\n Tags,\nTemplate)\n\n# Loading the config file based on the argument passed\njsondata = ''\nvpcdata = ''\nsgs = ''\nCidrIp = ''\n\n# Fetching values from json given as argument while this python is executed\nparser = argparse.ArgumentParser()\nparser.add_argument('filename')\nargs = parser.parse_args()\nwith open(args.filename) as file:\n jsondata = json.load(file)\n\nt = Template()\nt.add_version(\"2010-09-09\")\nt.add_description(\"CF to create Security Groups for %s\" % jsondata['EnvInfo']['Name'])\n\n#Get VPC ID based on the environment using boto3\nboto_ec2 = boto3.resource('ec2',region_name='%s' % jsondata['Tags']['Region'])\nvpcfilters = [{'Name':'tag-value', 'Values':['%s' % jsondata['Tags']['Name']]}]\ntry:\n vpcdata = list(boto_ec2.vpcs.filter(Filters=vpcfilters))[0]\nexcept IndexError as e:\n print >> sys.stderr, (\"Boto can't find the VPC. Is it there? [%s]\" % e)\n sys.exit(0)\n\nsgs = jsondata['securitygroups']\n\n# Function to create ingress and egress rules from json\ndef make_securitygroup_rules(IpProtocol, FromPort, ToPort, CidrIp, ReferenceSecurityGroup):\n if ReferenceSecurityGroup == \"\":\n return(ec2.SecurityGroupRule(\n CidrIp = CidrIp,\n IpProtocol = IpProtocol,\n FromPort = FromPort,\n ToPort = ToPort\n ))\n else:\n return(ec2.SecurityGroupRule(\n SourceSecurityGroupId = Ref(ReferenceSecurityGroup),\n IpProtocol = IpProtocol,\n FromPort = FromPort,\n ToPort = ToPort\n ))\n\n# Security Group Creation\n# Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html\nfor sg in sgs:\n sgname = sg['Name']\n t.add_resource(ec2.SecurityGroup(\n sgname,\n GroupDescription = sg['Description'],\n SecurityGroupIngress = [make_securitygroup_rules(**rules) for rules in sg['iRules']],\n SecurityGroupEgress = [make_securitygroup_rules(**rules) for rules in sg['eRules']],\n VpcId = vpcdata.vpc_id,\n Tags = Tags(**{\n 'Name': '%s' % sg['Name'],\n 'wltkkeas:environment': '%s' % jsondata['Tags']['Env']\n }) \n ))\n\nprint(t.to_json())\n\n","sub_path":"troposphere-scripts/trop_sg.py","file_name":"trop_sg.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129332350","text":"data = []\r\ncount = 0\r\nwith open('original.txt', 'r') as f:\r\n for line in f:\r\n data.append(line)\r\n count = count + 1\r\n if count % 1000 == 0:\r\n print(len(data))\r\nprint('檔案讀取完了', '總共有', len(data), '筆資料')\r\n\r\nsum_len = 0\r\nfor d in data:\r\n sum_len = sum_len + len(d)\r\nprint('平均留言長度', sum_len/len(data))\r\n\r\nnew = []\r\nfor d in data:\r\n if len(d) < 100:\r\n new.append(d)\r\nprint('一共有', len(new), '留言長度小於100')\r\nprint(new[0])\r\n\r\ngood = []\r\nfor d in data:\r\n if 'good' in d:\r\n good.append(d)\r\nprint('一共有',len(good),'留言提到good')\r\nprint(good[0])\r\n","sub_path":"reviews-analysis.py","file_name":"reviews-analysis.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24424178","text":"from math import sqrt\n\nnum = int(input(\"请输入需要校验的正整数:\"))\nk = int(sqrt(num))\nis_prime = True\n\nfor i in range(2, k+1):\n if num % i == 0:\n is_prime = False\n break\n\nif is_prime and num >= 2:\n print(\"您输入的是素数\")\nelse:\n print(\"您输入的不是素数\")","sub_path":"python-3/day4-4.py","file_name":"day4-4.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"82641599","text":"from django.urls import include, path\nfrom rest_framework import routers\n# from tutorial.quickstart import views\nfrom api_kdcmp import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'villages', views.villagenameViewSet)\nrouter.register(r'complaints', views.complaintsViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path('', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n # # path('', include('complaints.urls')),\n]\n","sub_path":"api_kdcmp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370536566","text":"import argparse\nimport csv\nimport re\n\nparser = argparse.ArgumentParser(description='Parse Address')\nparser.add_argument('in_file', help='file to parse, provided by juso.go.kr')\nparser.add_argument('out_file', help='csv file to save')\nparser.add_argument('--enc', required=False, default='euc-kr', help='in_file encoding, default:euc-kr')\nargs = parser.parse_args()\n\nif args.in_file: \n print('parsing file :',args.in_file)\n \nwith open(args.in_file, 'rt', encoding=args.enc ) as infile:\n with open(args.out_file, 'w', newline='') as csvfile:\n parse_writer = csv.writer(csvfile, delimiter=',')\n pattern_addr = re.compile('^(.+)\\s([0-9]+)(-([0-9])+)?$')\n pattern_road = re.compile('^(.+)\\s(\\S+)\\s([0-9]+)(-([0-9])+)?\\s*(\\(.+\\))?$')\n for line in infile:\n result = []\n item = line.split(';')\n if(item[0]=='전환성공'):\n addr_name = item[2] \n bobnbubn = pattern_addr.search(addr_name)\n if(bobnbubn):\n result.append(addr_name)\n result.append(bobnbubn.group(1))\n result.append(bobnbubn.group(2))\n result.append(bobnbubn.group(4) if bobnbubn.group(4) else '0')\n else:\n result.append('parsing error:',addr)\n \n road_name = item[3]\n road = pattern_road.match(road_name)\n if(road):\n result.append(road_name)\n result.append(road.group(2))\n result.append(road.group(3))\n result.append(road.group(5) if road.group(5) else '0') \n else:\n result.append('road parsing error:',road)\n print(result)\n parse_writer.writerow(result) ","sub_path":"addrparse.py","file_name":"addrparse.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376669477","text":"from PyQt5 import QtCore\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport pyqtgraph as pg\n\n#from Testing.SORN.SORN_Helper import *\nfrom NetworkBehaviour.Recorder.Recorder import *\n#from Testing.Common.Classifier_Helper import *\nfrom Testing.Common.Grammar_Helper import *\n\nclass sidebar_grammar_module():\n\n def add_recorder_variables(self, neuron_group, recorder):\n if hasattr(neuron_group, 'output'):\n recorder.add_varable('n.output')\n\n def initialize(self, Network_UI):\n if Network_UI.network['grammar_act', 0] is not None:\n\n self.readout = None\n self.readout_simu = None\n\n # self.Add_Sidebar_Spacing()\n\n def learning_on_off(event):\n Network_UI.network.set_mechanisms(['STDP'], self.stdp_cb.isChecked())\n\n self.stdp_cb = QCheckBox()\n self.stdp_cb.setText('STDP')\n self.stdp_cb.setChecked(True)\n self.stdp_cb.stateChanged.connect(learning_on_off)\n Network_UI.Add_Sidebar_Element(self.stdp_cb)\n\n def grammar_activator_on_off(event):\n Network_UI.network['grammar_act', 0].active = self.input_select_box.currentText() != 'None'\n\n self.input_select_box = QComboBox()\n self.input_select_box.addItem(\"Grammar Act.\")\n self.input_select_box.addItem(\"Prediction\")\n self.input_select_box.addItem(\"None\")\n self.input_select_box.currentIndexChanged.connect(grammar_activator_on_off)\n Network_UI.Add_Sidebar_Element(self.input_select_box)\n\n self.inp_text_label = QLabel(Network_UI.main_window)\n Network_UI.Add_Sidebar_Element(self.inp_text_label, stretch=0.2)\n self.inp_text_label.setText('')\n self.text = []\n\n def train_click(event):\n Network_UI.network.deactivate_mechanisms('STDP')\n\n #Network_UI.network.recording_off()\n\n Network_UI.network.add_behaviours_to_neuron_groups({100: NeuronRecorder(['n.output'], tag='pediction_rec')}, Network_UI.network['prediction_source'])\n Network_UI.network.add_behaviours_to_neuron_groups({101: NeuronRecorder(['n.pattern_index'], tag='index_rec')}, Network_UI.network['text_input_group'])\n\n #for ng in Network_UI.network['prediction_source']:\n # Network_UI.network.add_behaviours_to_neuron_group({100: NeuronRecorder(['n.output'], tag='pediction_rec')}, ng)\n #for ng in Network_UI.network['text_input_group']:\n # Network_UI.network.add_behaviours_to_neuron_group({101: NeuronRecorder(['n.pattern_index'], tag='index_rec')}, ng)\n\n\n Network_UI.network['grammar_act', 0].active = True\n\n steps = 5000\n Network_UI.network.simulate_iterations(steps, 100, measure_block_time=True)\n\n self.readout = train(Network_UI.network['pediction_rec'], 'n.output', Network_UI.network['index_rec', 0], 'n.pattern_index', 0, steps, lag=1)\n self.readout_simu = train_same_step(Network_UI.network['pediction_rec'], 'n.output', Network_UI.network['index_rec', 0], 'n.pattern_index', 0, steps)\n\n\n Network_UI.network.remove_behaviours_from_neuron_groups(Network_UI.network['prediction_source'], tags=['pediction_rec'])\n Network_UI.network.remove_behaviours_from_neuron_groups(Network_UI.network['text_input_group'], tags=['index_rec'])\n\n #Network_UI.network.clear_recorder(['pediction_rec', 'index_rec'])\n #Network_UI.network.deactivate_mechanisms(['pediction_rec', 'index_rec'])\n\n #Network_UI.network.recording_on()\n\n Network_UI.network.activate_mechanisms('STDP')\n\n self.input_select_box.setCurrentIndex(1)\n\n print('training_finished')\n\n self.pred_text_label = QLabel(Network_UI.main_window)\n Network_UI.Add_Sidebar_Element(self.pred_text_label, stretch=0.2)\n self.pred_text_label.mousePressEvent = train_click\n self.pred_text_label.setText('Click to Train...')\n self.pred_text = list(self.pred_text_label.text())\n\n self.pred_simu_text_label = QLabel(Network_UI.main_window)\n Network_UI.Add_Sidebar_Element(self.pred_simu_text_label, stretch=0.2)\n self.pred_simu_text_label.mousePressEvent = train_click\n self.pred_simu_text_label.setText('Click to Train...')\n self.pred_simu_text = list(self.pred_simu_text_label.text())\n\n\n\n def update(self, Network_UI):\n\n # save data timestep\n if not Network_UI.update_without_state_change and Network_UI.network['grammar_act', 0] is not None:\n\n grammar_act = Network_UI.network['grammar_act', 0]\n\n if grammar_act is not None:\n self.inp_text_label.setText('I: ' + ''.join(self.text))\n if self.readout_simu is not None:\n symbol_simu = predict_char(self.readout_simu, Network_UI.network['prediction_source'], 'n.output')\n char = grammar_act.index_to_char(symbol_simu)\n self.pred_simu_text += char\n self.pred_simu_text_label.setText('P_simu: ' + ''.join(self.pred_simu_text))\n\n if self.readout is not None:\n symbol = predict_char(self.readout, Network_UI.network['prediction_source'], 'n.output')\n char = grammar_act.index_to_char(symbol)\n self.pred_text += char\n self.pred_text_label.setText('P: ' + ''.join(self.pred_text))\n\n if self.input_select_box.currentText() == 'Prediction':\n if self.readout is not None:\n grammar_act.set_next_char(char)\n # self.network[self.exc_group_name, ts_group].input += self.network['grammar_act', 0].W[:, symbol]sdfdsfgdsfgdf\n else:\n print('warning: predictor not trained')\n\n if self.input_select_box.currentText() == 'Grammar Act.':\n self.text.append(grammar_act.get_char())\n elif self.input_select_box.currentText() == 'Prediction' and self.readout is not None:\n self.text.append(char)\n else:\n self.text.append('|')\n\n if len(self.text) > 35: self.text.pop(0)\n if len(self.pred_text) > 35: self.pred_text.pop(0)\n if len(self.pred_simu_text) > 35: self.pred_simu_text.pop(0)\n\n","sub_path":"Exploration/UI/Network_UI/Tabs/sidebar_grammar_module.py","file_name":"sidebar_grammar_module.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"133266959","text":"from .base import *\n\n\nSOUTH_TESTS_MIGRATE = False\n\nINSTALLED_APPS += (\n 'django_nose',\n)\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\n\nNOSE_ARGS = [\n '--with-coverage',\n '--cover-branches',\n '--with-progressive',\n '--cover-package=accounts,core,entries,events,fiscalyears,reports'\n]\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'memory://testdb',\n }\n}\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n}\n","sub_path":"acornaccounting/accounting/settings/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649670790","text":"num=int(input())\na=[int(y) for y in input().split()]\ny=[]\nfor i in range(0,len(a)):\n if i==a[i]:\n y.append(i)\nif len(y)==0:\n print(-1)\n \nprint(*y)\n","sub_path":"correctindex.py","file_name":"correctindex.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47137464","text":"#finds the frequency of the \"G\" or \"C\" base in a given nucleotide sequence and returns it in the form of a percentage\r\ndef get_gc_content(gclist):\r\n l=0\r\n result = []\r\n for str in gclist:\r\n l = 0\r\n for i in str:\r\n if(i == 'G' or i == 'C'):\r\n l = l + 1\r\n result.append(100*l/len(str))\r\n return result\r\n\r\n\r\n\r\n\r\n","sub_path":"GCcontent.py","file_name":"GCcontent.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56500243","text":"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#####################################################\n# Camada Física da Computação\n#Carareto\n#17/02/2018\n# Aplicação\n####################################################\n\nfrom enlaceRecepcao import *\nfrom tkinter import filedialog\nfrom tkinter import *\n#from GUI import GUI\nimport time\n\n# voce deverá descomentar e configurar a porta com através da qual ira fazer a\n# comunicaçao\n# Serial Com Port\n# para saber a sua porta, execute no terminal :\n# python -m serial.tools.list_ports\n# se estiver usando windows, o gerenciador de dispositivos informa a porta\n\nserialName = \"/dev/ttyACM4\" # Ubuntu (variacao de)\n#serialName = \"/dev/tty.usbmodem1411\" # Mac (variacao de)\n# serialName = \"COM4\" # Windows(variacao de)\n\n\ndef main():\n # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading\n com = enlace(serialName)\n rx = com.rx\n tx = com.tx\n # Ativa comunicacao\n com.enable()\n rx.clearBuffer()\n\n #verificar que a comunicação foi aberta\n print(\"-------------------------\")\n print(\"Comunicação Aberta\")\n print(\"-------------------------\")\n # a seguir ha um exemplo de dados sendo carregado para transmissao\n # voce pode criar o seu carregando os dados de uma imagem. Tente descobrir\n #como fazer isso\n\n flag2 = True\n flag5 = True\n flag6 = True\n\n while True:\n buffer_tuple, nRx = rx.getNData()\n\n rxbuffer, tipo = buffer_tuple\n if tipo == 1:\n print(\"Recebido solicitação de conexão\")\n break\n if tipo == 7:\n print(\"Encerrando comunicação\")\n flag2 = False\n flag5 = False\n flag6 = False\n break\n\n\n msg2 = False\n while flag2:\n #Synch 2 (Mensagem tipo 2)\n if not msg2:\n print(\"Enviando mensagem tipo 2\")\n data = (0).to_bytes(1, \"big\")\n com.sendData(data,2) #tipo 2\n time.sleep(0.5)\n print(\"Esperando mensagem tipo 3\")\n #Synch 3 (Mensagem tipo 3)\n buffer_tuple, nRx = rx.getNData()\n rxbuffer, tipo = buffer_tuple\n time.sleep(0.3)\n\n if tipo == 3:\n print(\"Conexão estabelecida\")\n msg2 = True\n break\n elif tipo == 0:\n print(\"Erro na recepção do arquivo\")\n if tipo == 7:\n print(\"Encerrando comunicação\")\n flag5 = False\n flag6 = False\n break\n elif tipo == \"\":\n print(\"Nada recebido\")\n else:\n print(\"Mensagem tipo 3 não recebida\")\n\n print(\"Reenviando mensagem tipo 2\")\n print(\"-------------------------\")\n time.sleep(1)\n\n while flag6:\n print(\"Esperando mensagem tipo 4\")\n #Synch 4 (Mensagem tipo 4)\n buffer_tuple, nRx = rx.getNData()\n msg, tipo = buffer_tuple\n if tipo == 4:\n f2 = open('ArquivoRecebido.jpg', 'wb')\n f2.write(msg)\n f2.close()\n break\n if tipo == 3:\n time.sleep(0.3)\n if tipo == 0:\n print(\"Falha no recebimento\")\n print(\"Enviando mensagem tipo 6\")\n data = (0).to_bytes(1, \"big\")\n com.sendData(data,6)\n time.sleep(1)\n if tipo == 7:\n print(\"Encerrando comunicação\")\n flag5 = False\n break\n else:\n print(\"Nada recebido\")\n time.sleep(1)\n\n\n\n start = time.time()\n while flag5:\n #Synch 5 (Mensagem tipo 5)\n print(\"Enviando mensagem tipo 5\")\n data = (0).to_bytes(1, \"big\")\n com.sendData(data,5) #tipo 5\n time.sleep(0.3)\n print(\"Esperando mensagem tipo 7\")\n #Synch 7 (Mensagem tipo 7)\n buffer_tuple, nRx = rx.getNData()\n rxBuffer, tipo = buffer_tuple\n\n time.sleep(0.3)\n\n if tipo == 7:\n break\n elif tipo == \"\":\n print(\"Nada recebido\")\n else:\n print(\"Mensagem tipo 7 não recebida\")\n\n print(\"Reenviando mensagem tipo 5\")\n print(\"-------------------------\")\n time.sleep(1)\n final = time.time() - start\n if final >= 20:\n break\n\n print(\"-------------------------\")\n print(\"Comunicação encerrada\")\n print(\"-------------------------\")\n\n\n com.disable()\n\n #so roda o main quando for executado do terminal ... se for chamado dentro de outro modulo nao roda\nif __name__ == \"__main__\":\n main()\n","sub_path":"Projeto 4/Recepcao/aplicacaoRecepcao.py","file_name":"aplicacaoRecepcao.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248214970","text":"from django.urls import path\nfrom . import views\n\napp_name = \"card2\"\n\nurlpatterns = [\n path('list/', views.post_list, name=\"post_list\"),\n path('wedding/', views.post_detail, name='post_detail'),\n path('gallery/', views.gallery_image, name='gallery_image'),\n path('gallery2//', views.sms_image, name='sms_image'),\n\n\n path('sample/wedding/', views.sample_post_detail, name='sample_post_detail'),\n path('sample/gallery/', views.sample_gallery_image, name='sample_gallery_image'),\n path('sample/gallery2//', views.sample_sms_image, name='sample_sms_image'),\n\n]\n","sub_path":"card2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646437885","text":"# Create a function that takes a filename as string parameter,\n# and counts the occurances of the letter \"a\", and returns it as a number.\n# It should not break if the file not exists just return 0\n\nto_find = 'a'\n\ndef letter_a_frequency_in_file(filename):\n try:\n with open(filename, 'r') as file_to_check:\n file_content = file_to_check.read()\n amount = 0\n for letter in file_content:\n if letter == to_find:\n amount += 1\n return amount\n file_to_check.close()\n except FileNotFoundError:\n return '0'\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78189462","text":"x=list()\na,b=input().split()\ntry:\n p=int(a)\n q=int(b)\nexcept:\n print(\"Invalid Input\")\nelse:\n c=max(p,q)\n d=min(p,q)\n for i in range (d+1,c):\n if(i%2 == 0):\n x.append(str(i))\n else:\n continue\n print(\" \".join(x))\n","sub_path":"Beginner Level/Set2/print the even no's between two intervals.py","file_name":"print the even no's between two intervals.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"341569333","text":"from seawar import Field\nfrom fun import ran_field\n\nif __name__ == \"__main__\":\n user = input(\"Введите ваше имя:\\n>>>\")\n player = Field(user)\n ok = ''\n while ok != 'y' or not ok:\n player.random_ship()\n player.show()\n ok = input(\"Если раскладка устраевает введите 'y'\\n>>>\")\n\n comp = Field(\"computer\")\n comp.random_ship()\n print(\"Начали!!!\")\n turn_side = True\n turn = 0\n while not player.islose() or not comp.islose() or turn == 0:\n turn += 1\n if turn_side:\n comp.show(1)\n target = input(\"Куда стреляем?\\n>>>\")\n shot = comp.shot(target)\n if shot:\n print(\"Попал!\\n\")\n continue\n else:\n print(\"Мимо!\\n\")\n turn_side = False\n else:\n player.show()\n shot = player.shot(ran_field())\n if shot:\n print(\"Попал!\\n\")\n continue\n else:\n print(\"Мимо!\\n\")\n turn_side = True\n","sub_path":"game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517632750","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport struct\n\nwith open(\"stimes.dat\", mode='rb') as file: # b is important -> binary\n spike = file.read()\nfile.close()\n\nspike_list = []\nfor i in struct.iter_unpack('d', spike):\n spike_list.append(i[0])\n\nprint(len(spike_list))\n# start = spike_list[10000]\n# end = spike_list[90000]\n# intvel = (end-start)/80000\nintvel = spike_list[-1]/len(spike_list)\nprint(intvel)\n\ny = np.ones(10000)\n# y = np.ones(len(spike_list))\n\nplt.figure(figsize=(10, 8))\nplt.scatter(spike_list[110000:120000], y, s=10, marker='o')\n# plt.scatter(spike_list, y, s=10, marker='o')\n# Show the boundary between the regions:\nplt.show()\n# last = spike_list[-1]\n# print(last)\n# interval = 0.1\n# length = len(spike_list)\n# # print(spike_list)\n# iter_list = []\n# leng = len(spike_list)\n#\n# nint = int(np.ceil(1000000.0/interval))\n# raster = np.zeros(nint+1)\n# for niter in range(length):\n# ind = int(np.floor(spike_list[niter]/interval))\n# raster[ind] += 1\n#\n# print(raster[:100])\n# num_list = []\n# counter = 0\n# for niter in range(nint+1):\n# num = raster[niter]\n# if num==0 and counter>0:\n# num_list.append(int(counter))\n# counter = 0\n# counter += num\n#\n# print(\"-------------\")\n# print(num_list)\n#\n# cut = 3000\n# size = [0]*cut\n# for item in num_list:\n# if item <= cut:\n# size[item-1] +=1\n# print(size)\n#\n#\n# # for iter in range(1,len(size)-2):\n# # if size[iter-1]+size[iter]+size[iter+1] < 20:\n# # ind = iter\n# # break\n# #\n# # size =size[:ind]\n# #\n# # print(ind)\n#\n# size = np.array(size, dtype=np.float)\n# norm = np.sum(size)\n# size = size/norm\n# xlist = []\n# ylist = []\n# for iter in range(len(size)):\n# xlist.append(iter + 1)\n# if size[iter]>0.0:\n# ylist.append(size[iter])\n# else: ylist.append(np.NaN)\n#\n# N = len(ylist)\n# summation = 0.0\n# lower = min(ylist)\n# for iter in range(N):\n# summation += np.log(ylist[iter]/lower)\n#\n# print(N/summation)\n#\n# xlist = np.array(xlist)\n# ylist = np.array(ylist)\n# plt.figure(figsize=(10, 8))\n# plt.plot(np.log(xlist), np.log(ylist), 'b')\n# plt.show()\n#\n# data=np.array([xlist,ylist])","sub_path":"interval.py","file_name":"interval.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489186520","text":"# -*- coding:utf-8 -*-\n# @Author : 江湖一笑\n# @Time : 2020/4/17 8:24\n# @Software : Web-Autotest-Python\n# @Python_verison : 3.7\nimport unittest,HTMLTestRunner,time\nfrom untils.email_tools import SendMailAttach\nfrom untils.log_cn import make_report\ndir = './case'\nsuite = unittest.defaultTestLoader.discover(start_dir=dir,pattern='test*.py')\n\nif __name__ =='__main__':\n now = time.strftime('%Y_%m_%d %H_%M_%S')\n # now_Ymd = time.strftime('%Y_%m_%d')\n make_report('./report/'+now[:-9])\n filename = ('./report/'+now[:-9]+'/html/'+now[11:]+'.html')\n file = open(filename,mode='wb')\n runner = HTMLTestRunner.HTMLTestRunner(stream=file,title='禅道测试报告',description='测试创建编辑用例和创建编辑bug')\n runner.run(suite)\n time.sleep(3)\n SendMailAttach(filename)","sub_path":"第四章-unittest框架/unittest框架实战_禅道11/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"268288485","text":"import os\nimport sys\n\ndef isprime(n):\n\n isprime = True\n meter = 0\n\n for x in range(1,n+1):\n if n % x == 0:\n meter += 1\n\n if meter != 2:\n isprime = False\n\n return isprime\n\ndef main():\n a = []\n\n print(\"Bienvenido a su medidor de numeros primos!\")\n i = int(input(\"inserte su numero: \"))\n for n in range(i):\n\n if isprime(n) == True:\n print(\"{} es primo!\".format(n))\n a.append(n)\n else:\n print(\"{} no es primo!\".format(n))\n\n print(\"La lista de primos es {}\".format(a))\n\nmain()\n","sub_path":"PY/Aterm/primos.py","file_name":"primos.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377492039","text":"import cv2 as cv\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom sklearn.cluster import KMeans\r\nimport timeit\r\n\r\n\r\ndef preProccess(filename):\r\n image = cv.imread(filename, cv.IMREAD_COLOR)\r\n y, x= image.shape[:2]\r\n if (x >1024 and y > 768):\r\n y = int(y/(x/1024))\r\n image = cv.resize(image, ( 1024, y ))\r\n return image\r\n\r\ndef display(image, windowName):\r\n cv.imshow(windowName,image)\r\n\r\ndef getBoard(img, pts):\r\n (tl, tr, br, bl) = pts\r\n \r\n widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))\r\n widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))\r\n maxWidth = max(int(widthA), int(widthB))\r\n\r\n heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))\r\n heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))\r\n maxHeight = max(int(heightA), int(heightB))\r\n\r\n dst = np.array([[0, 0],[maxWidth - 1, 0],[maxWidth - 1, maxHeight - 1],[0, maxHeight - 1]], dtype=\"float32\")\r\n M = cv.getPerspectiveTransform(pts, dst)\r\n warped = cv.warpPerspective(img, M, (maxWidth, maxHeight))\r\n return warped\r\n#resizes input image\r\ndef resize(img, w):\r\n dim= (w, 678)\r\n return cv.resize(img, dim, interpolation = cv.INTER_AREA)\r\n\r\n# returns dominant colours through k means \r\ndef dominantColors(image, clusters=3):\r\n\timg = cv.imread(image)\r\n\ty, x= img.shape[:2]\r\n\tr = x/y\r\n\tx = int(200*r)\r\n\ty = int(200*r)\r\n\timg = cv.resize(img, ( x, y ))\r\n\timg = cv.cvtColor(img, cv.COLOR_BGR2RGB)\r\n\timg = img.reshape((img.shape[0] * img.shape[1], 3))\r\n\tkmeans = KMeans(n_clusters = clusters)\r\n\tkmeans.fit(img)\t\r\n\tcolours = kmeans.cluster_centers_\r\n\tlabels = kmeans.labels_\r\n\treturn colours.astype(int)\t\r\n\r\n#returns expected colour range of a given tile \r\ndef checkLocC(n):\r\n if (locCols[n] == 'lg'):\r\n colL = lg[0]\r\n colH = lg[1]\r\n elif (locCols[n] == 'y'):\r\n colL = y[0]\r\n colH = y[1]\r\n elif (locCols[n] == 'g'):\r\n colL =g[0]\r\n colH = g[1]\r\n elif (locCols[n] == 'b'):\r\n colL = b[0]\r\n colH = b[1]\r\n elif (locCols[n] == 'r'):\r\n colL = r[0]\r\n colH = r[1]\r\n else:\r\n colL = w[0]\r\n colH = w[1]\r\n return colL, colH\r\n\r\n#returns wether game piece on a game given game tile\r\ndef checkLoc(n, board):\r\n r,g,b =tileColour(board,locs[n])\r\n colL, colH = checkLocC(n)\r\n if r >= colL[0] and r<= colH[0]:\r\n if g >= colL[1] and g<= colH[1]:\r\n if b >= colL[2] and b<= colH[2]:\r\n return False\r\n else:\r\n return True\r\n else:\r\n return True\r\n else:\r\n return True\r\n\r\n\r\n#returns dominant colour of tile at provided ROI\r\ndef tileColour(image, polygon):\r\n height = image.shape[0]\r\n width = image.shape[1]\r\n mask = np.zeros((height, width))\r\n \r\n mask = np.zeros((height, width), dtype=np.uint8)\r\n cv.fillPoly(mask, [polygon], (255))\r\n dst = cv.bitwise_and(image,image,mask = mask)\r\n bg = ~mask\r\n bg= cv.bitwise_not(dst,dst,mask = bg)\r\n\r\n rect = cv.boundingRect(polygon) # returns (x,y,w,h) of the rect\r\n crop = bg[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]\r\n\r\n cv.imwrite(\"dst.jpg\",crop)\r\n colors = dominantColors('dst.jpg', 2)\r\n\r\n if np.sum(colors[0]) >= np.sum(colors[1]):\r\n colors = colors[1]\r\n else:\r\n colors = colors[0]\r\n return colors\r\n\r\ndef selectBoard(n):\r\n if n ==96:\r\n bpts = np.array([[173,39],[960,41],[1023,572],[134,586]], dtype=\"float32\")#96\r\n trains = np.array([3,6])\r\n imageN = \"trains//IMG_2096.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==97:\r\n bpts = np.array([[227,60],[893,186],[851,678],[44,479]], dtype=\"float32\")#97\r\n trains = np.array([3,6,10,11])\r\n imageN = \"trains//IMG_2097.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==95:\r\n bpts = np.array([[182,140],[865,136],[966,603],[109,623]], dtype=\"float32\")#97\r\n trains = np.array([])\r\n imageN = \"trains//IMG_2095.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==94:\r\n bpts = np.array([[202,209],[837,188],[966,620],[140,671]], dtype=\"float32\")#97\r\n trains = np.array([])\r\n imageN = \"trains//IMG_2094.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==93:\r\n bpts = np.array([[507,139],[952,413],[516,721],[190,255]], dtype=\"float32\")#9\r\n trains = np.array([])\r\n imageN = \"IMG_1993.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==92:\r\n bpts = np.array([[96,265],[668,79],[961,320],[234,691]], dtype=\"float32\")#9\r\n trains = np.array([])\r\n imageN = \"IMG_1994.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==91:\r\n bpts = np.array([[162,152],[857,123],[1004,581],[107,656]], dtype=\"float32\")#9\r\n trains = np.array([])\r\n imageN = \"IMG_1995.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==90:\r\n bpts = np.array([[170,237],[741,143],[952,458],[204,660]], dtype=\"float32\")#9\r\n trains = np.array([])\r\n imageN = \"IMG_1996.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==98:\r\n bpts = np.array([[150,90],[876,129],[941,634],[33,592]], dtype=\"float32\")#98\r\n trains = np.array([3,6,10,11,5])\r\n imageN = \"trains//IMG_2098.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==99:\r\n bpts = np.array([[110,77],[876,83],[970,605],[29,622]], dtype=\"float32\")#99\r\n trains = np.array([1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])\r\n imageN = \"trains//IMG_2099.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==100:\r\n bpts = np.array([[161,106],[855,113],[969,577],[56, 584]], dtype=\"float32\")#100\r\n trains = np.array([1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])\r\n imageN = \"trains//IMG_2100.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==101:\r\n bpts = np.array([[305,66],[925,218],[878,674],[81,411]], dtype=\"float32\")#101\r\n trains = np.array([1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])\r\n imageN = \"trains//IMG_2101.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==102:\r\n bpts = np.array([[88,182],[781,44],[990,467],[141,704]], dtype=\"float32\")#102\r\n trains = np.array([1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])\r\n imageN = \"trains//IMG_2102.jpg\"\r\n return bpts, trains, (imageN)\r\n elif n ==103:\r\n bpts = np.array([[216,74],[915,168],[940,669],[56,538]], dtype=\"float32\")#103\r\n trains = np.array([2,4,5,9,11,14,16,20,21,26])\r\n imageN = \"trains//IMG_2103.jpg\"\r\n return bpts, trains, (imageN)\r\n\r\n# runs tests on a given image of a game board\r\ndef checkBoard(n):\r\n folder = \"C://Users//Owen Pantry//project//pictures//Boards//Europe//table//wood//\"\r\n bpts, trains, imagefile = selectBoard(n)\r\n img = preProccess(folder+imagefile)\r\n board = getBoard(img, bpts)\r\n board = resize(board, 1000) \r\n outputimg = board.copy()\r\n tcount = 0\r\n empty = 0\r\n missed = 0\r\n extra = 0\r\n for i in range(0,26):\r\n present= checkLoc(i,board)\r\n \r\n if ((i+1) in trains) == True:\r\n if present == True:\r\n cv.drawContours(outputimg, [locs[i]], 0, (255,255,0), 2)\r\n tcount = tcount+1\r\n else:\r\n missed = missed +1 \r\n else:\r\n if present == True:\r\n cv.drawContours(outputimg, [locs[i]], 0, (255,255,0), 2)\r\n extra = extra +1\r\n else:\r\n empty = empty +1\r\n\r\n #print(\"Train Count\",tcount,\"empty locs\",empty,\"Missed\", missed, \"Extra\",extra, \".\")\r\n #cv.imshow(str(n),outputimg)\r\n\r\n#colour ranges RGB\r\nlg = np.asarray([[115,110,100],[160,160,155]])\r\nw = np.asarray([[130,130,120],[185,170,160]])\r\ng = np.asarray([[130,145,80],[155,165,105]])\r\nb = np.asarray([[60,112,125],[120,155,185]])\r\nr = np.asarray([[140,80,65],[190,115,100]])\r\ny = np.asarray([[170,150,85],[202,185,110]])\r\n\r\n#expected colours of tiles\r\nlocCols = ['lg','lg','y','y','w','b','lg','lg','r','b','r','r','r','lg','lg','r','r','r','g','g','b','b','b','w','w','lg']\r\n\r\n#ROIs for board tiles\r\nlocs = np.array([[[212,214],[225,215],[222,248],[210,246]]], np.int32)#1\r\npts = np.array([[[210,246],[222,248],[218,285],[205,284]]], np.int32)#2\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[272,290],[283,295],[268,327],[257,320]]], np.int32)#3\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[287,258],[298,264],[283,296],[273,290]]], np.int32)#4\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[312,317],[342,300],[347,313],[318,328]]], np.int32)#5\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[227,408],[240,413],[226,447],[214,440]]], np.int32)#6\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[202,496],[213,495],[218,525],[205,526]]], np.int32)#7\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[205,526],[217,526],[222,560],[208,561]]], np.int32)#8\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[558,340],[582,357],[576,368],[549,352]]], np.int32)#9\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[574,311],[598,290],[605,299],[580,322]]], np.int32)#10\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[650,215],[663,185],[674,193],[658,222]]], np.int32)#11\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[672,178],[704,172],[706,184],[674,189]]], np.int32)#12\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[716,172],[740,192],[733,202],[709,184]]], np.int32)#13\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[762,199],[790,217],[782,227],[756,210]]], np.int32)#14\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[783,230],[794,228],[793,262],[782,262]]], np.int32)#15\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[798,266],[831,269],[830,283],[797,283]]], np.int32)#16\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[831,269],[853,244],[862,254],[841,278]]], np.int32)#17\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[843,211],[857,209],[865,240],[854,243]]], np.int32)#18\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[926,320],[961,320],[960,332],[924,331]]], np.int32)#19\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[948,332],[959,332],[960,366],[948,366]]], np.int32)#20\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[686,496],[714,513],[706,523],[679,505]]], np.int32)#21\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[715,512],[745,530],[738,539 ],[709,522]]], np.int32)#22\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[745,527],[775,545],[768,555],[741,540]]], np.int32)#23\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[278,329],[311,320],[318,331],[282,341]]], np.int32)#24\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[341,299],[369,282],[376,291],[348,311]]], np.int32)#25\r\nlocs = np.append(locs, pts, axis = 0)\r\npts = np.array([[[268,397],[276,388],[295,417],[284,424]]], np.int32)#26\r\nlocs = np.append(locs, pts, axis = 0)\r\n\r\n\r\n#Running tests on all test images\r\nmeanTime = 0\r\nfor x in range(90, 104):\r\n start = timeit.default_timer()\r\n print(\"Board :\",x, end=\" \")\r\n checkBoard(x)\r\n stop = timeit.default_timer()\r\n meanTime = meanTime + (stop - start)\r\nmeanTime = meanTime / 14\r\nprint(meanTime)\r\n\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()","sub_path":"Code/detectTrainRGB.py","file_name":"detectTrainRGB.py","file_ext":"py","file_size_in_byte":11476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"442620017","text":"availableExits = ['East','West','North','South']\r\n\r\nchosenExit = \"\"\r\n\r\nwhile chosenExit not in availableExits:\r\n chosenExit = input(\"please choose a direction \\n\")\r\n if chosenExit =='quit':\r\n print(\"Game over\")\r\n break\r\n\r\nelse:\r\n print(\"you found the exit\")\r\n","sub_path":"while_loop_1.py","file_name":"while_loop_1.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331019553","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom threading import Thread\nfrom xml.dom import minidom\nfrom chess import Chess\nimport socket\nimport re\n\n\nclass MainWindow(QGraphicsView):\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.scene = QGraphicsScene(self)\n self.game = Chess(2)\n self.scene.addItem(self.game)\n self.scene.setSceneRect(0, 0, 360, 360)\n\n view = QGraphicsView(self.scene, self)\n layout = QGridLayout()\n\n self.info_window = QTextEdit()\n self.info_window.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding)\n self.info_window.setFocusPolicy(Qt.NoFocus)\n\n self.message_line = QLineEdit()\n self.message_line.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding)\n self.message_line.setFocusPolicy(Qt.StrongFocus)\n self.message_line.returnPressed.connect(self.send_msg)\n\n connect_button = QPushButton(\"Connect\", self)\n connect_button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n connect_button.clicked.connect(self.button_actions)\n connect_button.setFocusPolicy(Qt.NoFocus)\n\n btn_new_game = QPushButton(\"New game\", self)\n btn_new_game.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n btn_new_game.clicked.connect(self.button_actions)\n btn_new_game.setFocusPolicy(Qt.NoFocus)\n\n btn_exit = QPushButton(\"Exit\", self)\n btn_exit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n btn_exit.clicked.connect(self.button_actions)\n btn_exit.setFocusPolicy(Qt.NoFocus)\n\n btn_last_game = QPushButton(\"Resume\", self)\n btn_last_game.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n btn_last_game.clicked.connect(self.button_actions)\n btn_last_game.setFocusPolicy(Qt.NoFocus)\n\n btn_step_resume = QPushButton(\"Step resume\", self)\n btn_step_resume.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n btn_step_resume.clicked.connect(self.button_actions)\n btn_step_resume.setFocusPolicy(Qt.NoFocus)\n\n layout.addWidget(view, 0, 0, 8, 8)\n layout.addWidget(btn_new_game, 8, 0, 1, 8)\n layout.addWidget(btn_exit, 9, 0, 1, 8)\n layout.addWidget(connect_button, 10, 0, 1, 8)\n layout.addWidget(btn_last_game, 11, 0, 1, 8)\n layout.addWidget(btn_step_resume, 12, 0, 1, 8)\n layout.addWidget(self.info_window, 0, 9, 12, 4)\n layout.addWidget(self.message_line, 12, 9, 1, 4)\n\n self.setLayout(layout)\n self.setGeometry(1000, 300, 650, 560)\n self.setCacheMode(QGraphicsView.CacheBackground)\n self.setWindowTitle(\"Chess-server\")\n\n self.socket = None\n self.th1 = None\n self.th2 = None\n self.resume_idx = 0\n\n self.doc = minidom.Document()\n\n self.root = self.doc.createElement('game')\n self.doc.appendChild(self.root)\n\n def write_to_xml(self, move, player):\n move = str(move)\n move = re.findall(r'\\d+', move)\n move = list(map(int, move))\n move_to_xml = self.doc.createElement('move')\n move_to_xml.appendChild(self.doc.createTextNode(str(move)))\n move_to_xml.setAttribute('player', str(player))\n self.root.appendChild(move_to_xml)\n xml_str = self.doc.toprettyxml(indent=\"\\t\")\n file = open('last_game.xml', 'w')\n file.write(xml_str)\n file.close()\n\n def wait_for_move(self):\n while self.socket is not None:\n if self.game.move_to_send:\n move = self.game.send_move()\n self.write_to_xml(move, 2)\n self.info_window.append(str(move))\n self.socket.send(str(move).encode())\n self.game.set_move_to_send()\n\n def button_actions(self):\n sender = self.sender()\n if sender.text() == \"Exit\":\n self.socket.close()\n self.close()\n elif sender.text() == \"New game\":\n self.scene.removeItem(self.game)\n del self.game\n self.game = Chess(2)\n self.scene.addItem(self.game)\n elif sender.text() == \"Connect\":\n self.create_connection()\n elif sender.text() == \"Resume\":\n self.load_last_game()\n elif sender.text() == \"Step resume\":\n self.load_one_move()\n\n def load_last_game(self):\n dom = minidom.parse(\"last_game.xml\")\n moves = dom.getElementsByTagName('move')\n for move_from_xml in moves:\n move = move_from_xml.firstChild.data\n move = re.findall(r'\\d+', move)\n move = list(map(int, move))\n player = move_from_xml.getAttribute(\"player\")\n self.write_to_xml(move, int(player))\n if player == '2':\n self.game.move(move[0], move[1], move[2], move[3])\n self.game.set_turn()\n else:\n self.game.update_move(move)\n\n def load_one_move(self):\n dom = minidom.parse(\"last_game.xml\")\n moves = dom.getElementsByTagName('move')\n if self.resume_idx < len(moves):\n move = moves[self.resume_idx].firstChild.data\n move = re.findall(r'\\d+', move)\n move = list(map(int, move))\n player = moves[self.resume_idx].getAttribute(\"player\")\n # self.write_to_xml(move, int(player))\n if player == '1':\n self.game.move(move[0], move[1], move[2], move[3])\n self.game.set_turn()\n else:\n self.game.update_move(move)\n if self.resume_idx < len(moves):\n self.resume_idx += 1\n self.game.update()\n\n def create_connection(self):\n if self.socket is None:\n TCP_IP = 'localhost'\n TCP_PORT = 50006\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.bind((TCP_IP, TCP_PORT))\n self.socket.listen(1)\n self.socket, self.addr = self.socket.accept()\n self.info_window.append('Connection from: ' + str(self.addr) + '\\n')\n self.th2 = Thread(target=self.wait_for_move)\n self.th1 = Thread(target=self.recv_msg)\n self.th2.start()\n self.th1.start()\n else:\n self.socket.close()\n self.th1.join()\n self.socket = None\n self.th1 = None\n\n def send_msg(self):\n if self.socket:\n msg = self.message_line.text()\n self.info_window.append(\"Me : \" + msg)\n self.socket.send(msg.encode())\n self.message_line.clear()\n\n def recv_msg(self):\n while self.socket is not None:\n msg = str(self.socket.recv(1024).decode())\n self.info_window.append(\"Opponent : \" + msg)\n msg = re.findall(r'\\d+', msg)\n msg = list(map(int, msg))\n if msg:\n self.write_to_xml(msg, 1)\n self.game.update_move(msg)\n\n def keyPressEvent(self, event):\n super(MainWindow, self).keyPressEvent(event)\n\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n mainWindow = MainWindow()\n mainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"online/mainwindowServer.py","file_name":"mainwindowServer.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380418618","text":"class CriteriaCommand:\n @staticmethod\n def build_argparse(subparsers):\n criteria_parser = subparsers.add_parser('criteria', aliases=['crit'], help='Manipulate criteria')\n criteria_parser.set_defaults(func=lambda _: criteria_parser.print_help())\n criteria_subparsers = criteria_parser.add_subparsers()\n\n def build(ctx):\n ctx.modify_static = True\n ctx.categories_svc.build_criteria()\n\n criteria_build_opt = criteria_subparsers.add_parser('build', help='Build criteria database')\n criteria_build_opt.set_defaults(func=build)\n","sub_path":"src/carscanner/cli/cmd_criteria.py","file_name":"cmd_criteria.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425871734","text":"#!/usr/bin/env python\n\nimport sys\n# Always prefer setuptools over distutils\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n print(\"xii requires setuptools in order to be installed.\")\n sys.exit(1)\n\n\nsetupdict = dict(\n name=\"xii\",\n keywords=[\"xii\", \"virtualization\"],\n version=\"1.0.0\",\n description=\"A easy to use virtual machine manager\",\n url=\"https://github.com/xii/xii\",\n author=\"Felix Schnizlein\",\n author_email=\"xii@schnizle.in\",\n license=\"GPL-3.0\",\n classifiers=[\n \"Development Status :: 3 - Alpha\"\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"Operating System :: POSIX\",\n \"Topic :: Utilities\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n ],\n install_requires=[\"paramiko\", \"PyYAML\", \"pycrypto\", \"jinja2\", \"futures\"],\n include_package_data=True,\n packages=find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n entry_points={\"console_scripts\": [\"xii=xii:main\"]}\n )\nsetup(**setupdict)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"641668194","text":"import csv\nimport random\nimport numpy\nfrom random import randint\nimport operator\nimport math\nimport matplotlib.pyplot as plt\n\ndef normalize(dataset=[]):\n dataset = numpy.array(dataset)\n mu =[]\n sd = []\n mu = numpy.mean(dataset, 0)\n sd = numpy.std(dataset, axis=0)\n \n for x in range(len(dataset)):\n for y in range(1,14):\n dataset[x][y] = float(dataset[x][y]-mu[y])/sd[y]\n return dataset\n\ndef main():\n # prepare data\n with open('wine.data.txt', 'rb') as csvfile:\n lines = csv.reader(csvfile)\n dataset = list(lines)\n \n for x in range(len(dataset)):\n for y in range(14):\n dataset[x][y] = float(dataset[x][y])\n dataset = normalize(dataset)\n totalWrong = dataSet = 0\n A = []\n B = []\n for k in range(1,10):\n for i in range(1,10):\n trainingSet=[]\n testSet=[]\n trainingSet, testSet = loadDataset(dataset, trainingSet, testSet)\n #print 'Train set: ' + repr(len(trainingSet))\n #print 'Test set: ' + repr(len(testSet))\n\n # generate predictions\n predictions=[]\n for x in range(len(testSet)):\n neighbors = getNeighbors(trainingSet, testSet[x], k)\n result = getResponse(neighbors)\n predictions.append(result)\n #print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][0]))\n wrong = getError(testSet, predictions)\n totalWrong += wrong\n dataSet += len(testSet)\n prob = (totalWrong/float(dataSet)) * 100.0\n print('Error Probability for k = '+ repr(k) +' is ' + repr(prob) + '%')\n A.append(k)\n B.append(prob)\n plt.plot(A,B)\n plt.show()\n\ndef getError(testSet, predictions):\n wrong = 0\n for x in range(len(testSet)):\n if testSet[x][0] != predictions[x]:\n wrong += 1\n #print 'Wrongly Classified:' + repr(wrong)\n return wrong\n\ndef getResponse(neighbors):\n classVotes = {}\n for x in range(len(neighbors)):\n response = neighbors[x][0]\n if response in classVotes:\n classVotes[response] += 1\n else:\n classVotes[response] = 1\n sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True)\n return sortedVotes[0][0]\n\ndef euclideanDistance(instance1, instance2, length):\n distance = 0\n for x in range(1,length):\n distance += pow((float(instance1[x]) - float(instance2[x])), 2)\n return math.sqrt(distance)\n\ndef getNeighbors(trainingSet, testInstance, k):\n distances = []\n length = len(testInstance)\n for x in range(len(trainingSet)):\n dist = euclideanDistance(testInstance, trainingSet[x], length)\n distances.append((trainingSet[x], dist))\n distances.sort(key=operator.itemgetter(1))\n neighbors = []\n for x in range(k):\n neighbors.append(distances[x][0])\n return neighbors\n\ndef loadDataset(dataset=[], trainingSet=[] , testSet=[]):\n class1=[]\n class2=[]\n class3=[]\n for x in range(len(dataset)):\n if dataset[x][0] == 1:\n class1.append(dataset[x])\n elif dataset[x][0] == 2:\n class2.append(dataset[x])\n elif dataset[x][0] == 3:\n class3.append(dataset[x])\n\n l1 = len(class1)\n l2 = len(class2)\n l3 = len(class3)\n class1 = numpy.array(class1)\n class2 = numpy.array(class2)\n class3 = numpy.array(class3)\n \n training_idx = numpy.random.randint(l1, size=l1-5)\n test_idx = numpy.random.randint(l1, size=5)\n training, test = class1[training_idx,:], class1[test_idx,:]\n testSet = testSet + test.tolist()\n trainingSet = trainingSet + training.tolist()\n\n training_idx = numpy.random.randint(l2, size=l2-5)\n test_idx = numpy.random.randint(l2, size=5)\n training, test = class2[training_idx,:], class2[test_idx,:]\n testSet = testSet + test.tolist()\n trainingSet = trainingSet + training.tolist()\n\n training_idx = numpy.random.randint(l3, size=l3-5)\n test_idx = numpy.random.randint(l3, size=5)\n training, test = class3[training_idx,:], class3[test_idx,:]\n testSet = testSet + test.tolist()\n trainingSet = trainingSet + training.tolist()\n return trainingSet, testSet\n\nmain()\n","sub_path":"kNN_Normalized.py","file_name":"kNN_Normalized.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"70793675","text":"\"\"\"\nWavefront path planning algorithm.\n\"\"\"\n\nimport numpy as np\nimport heapq\nfrom math import ceil, cos, sin\nfrom .transform import wrap_angle\nfrom .rrt_shapes import *\n\nclass WaveFront():\n def __init__(self, square_size=10, grid_size=(100,100)):\n self.square_size = square_size\n self.grid_size = grid_size\n self.grid = np.ndarray(grid_size, dtype=np.int32)\n self.goal_marker = 2**31 - 1\n\n def initialize_grid(self,bbox=None,inflate_size=5):\n if bbox:\n self.grid_size = (int(bbox[1][0]-bbox[0][0]+2*inflate_size),\n int(bbox[1][1]-bbox[0][1]+2*inflate_size))\n self.grid = np.zeros(self.grid_size, dtype=np.int32)\n\n def convert_coords(self,xcoord,ycoord):\n \"Convert world map coordinates to grid subscripts.\"\n x = int(round((xcoord/self.square_size+self.grid_size[0]/2)))\n y = int(round((ycoord/self.square_size+self.grid_size[1]/2)))\n if x >= 0 and x < self.grid_size[0] and \\\n y >= 0 and y < self.grid_size[1]:\n return (x,y)\n else:\n return (None,None)\n\n def set_obstacle(self,xcoord,ycoord):\n (x,y) = self.convert_coords(xcoord,ycoord)\n if x:\n self.grid[x,y] = -1\n\n def set_goal(self,xcoord,ycoord):\n (x,y) = self.convert_coords(xcoord,ycoord)\n if x:\n self.grid[x,y] = self.goal_marker\n else:\n raise ValueError('Coordinates (%s, %s) are outside the wavefront grid' % ((xcoord,ycoord)))\n\n def add_obstacle(self, obstacle, inflate_size):\n if isinstance(obstacle, Rectangle):\n centerX, centerY = obstacle.center[0,0], obstacle.center[1,0]\n width, height = obstacle.dimensions[0]+inflate_size*2, obstacle.dimensions[1]+inflate_size*2\n theta = wrap_angle(obstacle.orient)\n for x in range(int(round(centerX-width/2)), int(ceil(centerX+width/2))):\n for y in range(int(round(centerY-height/2)), int(ceil(centerY+height/2))):\n new_x = ((x - centerX) * cos(theta) - (y - centerY) * sin(theta)) + centerX\n new_y = ((x - centerX) * sin(theta) + (y - centerY) * cos(theta)) + centerY\n self.set_obstacle(new_x, new_y)\n elif isinstance(obstacle, Polygon):\n pass\n elif isinstance(obstacle, Circle):\n pass\n elif isinstance(obstacle, Compound):\n pass\n else:\n raise Exception(\"%s has no add_obstacle() method defined for %s.\" % (self, obstacle))\n\n def propagate(self,xstart,ystart):\n \"\"\"\n Propagate the wavefront in eight directions from the starting coordinates\n until a goal cell is reached or we fill up the grid.\n \"\"\"\n grid = self.grid\n (x,y) = self.convert_coords(xstart,ystart)\n if grid[x,y] != 0:\n raise ValueError(\"Start collides\")\n \n goal_marker = self.goal_marker\n fringe = [(1,(x,y))]\n heapq.heapify(fringe)\n xmax = self.grid_size[0] - 1\n ymax = self.grid_size[1] - 1\n while fringe:\n dist,(x,y) = heapq.heappop(fringe)\n if grid[x,y] == 0:\n grid[x,y] = dist\n else:\n continue\n dist10 = dist + 10\n dist14 = dist + 14\n if x > 0:\n cell = grid[x-1,y]\n if cell == goal_marker: return (x-1,y)\n elif cell == 0:\n heapq.heappush(fringe, (dist10,(x-1,y)))\n if y > 0:\n cell = grid[x-1,y-1]\n if cell == goal_marker: return (x-1,y-1)\n elif cell == 0:\n heapq.heappush(fringe, (dist14,(x-1,y-1)))\n if y < ymax:\n cell = grid[x-1,y+1]\n if cell == goal_marker: return (x-1,y+1)\n elif cell == 0:\n heapq.heappush(fringe, (dist14,(x-1,y+1)))\n if x < xmax:\n cell = grid[x+1,y]\n if cell == goal_marker: return (x+1,y)\n elif cell == 0:\n heapq.heappush(fringe, (dist10,(x+1,y)))\n if y > 0:\n cell = grid[x+1,y-1]\n if cell == goal_marker: return (x+1,y-1)\n elif cell == 0:\n heapq.heappush(fringe, (dist14,(x+1,y-1)))\n if y < ymax:\n cell = grid[x+1,y+1]\n if cell == goal_marker: return (x+1,y+1)\n elif cell == 0:\n heapq.heappush(fringe, (dist14,(x+1,y+1)))\n if y > 0:\n cell = grid[x,y-1]\n if cell == goal_marker: return (x,y-1)\n elif cell == 0:\n heapq.heappush(fringe, (dist10,(x,y-1)))\n if y < ymax:\n cell = grid[x,y+1]\n if cell == goal_marker: return (x,y+1)\n elif cell == 0:\n heapq.heappush(fringe, (dist10,(x,y+1)))\n return None\n\n def extract(self,search_result):\n \"Extract the path once the goal is found, and convert back to worldmap coordinates.\"\n (x,y) = search_result\n maxdist = self.goal_marker + 1\n grid = self.grid\n xmax = self.grid_size[0] - 1\n ymax = self.grid_size[1] - 1\n path = []\n while maxdist > 1:\n path.append((x,y))\n if x > 0:\n if 0 < grid[x-1,y] < maxdist:\n maxdist = grid[x-1,y]\n (newx,newy) = (x-1,y)\n if y > 0:\n if 0 < grid[x-1,y-1] < maxdist:\n maxdist = grid[x-1,y-1]\n (newx,newy) = (x-1,y-1)\n if y < ymax:\n if 0 < grid[x-1,y+1] < maxdist:\n maxdist = grid[x-1,y+1]\n (newx,newy) = (x-1,y+1)\n if x < xmax:\n if 0 < grid[x+1,y] < maxdist:\n maxdist = grid[x+1,y]\n (newx,newy) = (x+1,y)\n if y > 0:\n if 0 < grid[x+1,y-1] < maxdist:\n maxdist = grid[x+1,y-1]\n (newx,newy) = (x+1,y-1)\n if y < ymax:\n if 0 < grid[x+1,y+1] < maxdist:\n maxdist = grid[x+1,y+1]\n (newx,newy) = (x+1,y+1)\n if y > 0:\n if 0 < grid[x,y-1] < maxdist:\n maxdist = grid[x,y-1]\n (newx,newy) = (x,y-1)\n if y < ymax:\n if 0 < grid[x,y+1] < maxdist:\n maxdist = grid[x,y+1]\n (newx,newy) = (x,y+1)\n (x,y) = (newx,newy)\n path.append((x,y))\n path.reverse()\n square_size = self.square_size\n xmid = self.grid_size[0]/2\n ymid = self.grid_size[1]/2\n path_coords = [((x-xmid)*square_size, (y-ymid)*square_size) for (x,y) in path]\n return path_coords\n\ndef wf_test():\n start = (261,263)\n goal = (402,454)\n #\n wf = WaveFront()\n wf.grid[:,:] = 0\n wf.set_goal(*goal)\n wf.set_obstacle(280,280)\n wf.set_obstacle(280,290)\n wf.set_obstacle(290,280)\n wf.set_obstacle(290,290)\n result1 = wf.propagate(*start)\n result2 = wf.extract(result1)\n print('path length =', len(result2))\n print(result2)\n print(wf.grid[75:85, 75:85])\n return result2\n\n# wf_test()\n","sub_path":"cozmo_fsm/wavefront.py","file_name":"wavefront.py","file_ext":"py","file_size_in_byte":7548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"194896321","text":"import re\nimport requests\nfrom bs4 import BeautifulSoup\n\nre_numbers = re.compile('[0-9]+')\npopup_url = 'http://dart.fss.or.kr/dsaf001/main.do?rcpNo={}'\nreport_url = 'http://dart.fss.or.kr/report/viewer.do?rcpNo={}&dcmNo={}&eleId=0&offset=0&length=0&dtd=HTML'\n\npat1 = re.compile('1\\. ?제목')\n\ndef get_report(rcp_no):\n _url = popup_url.format(rcp_no)\n req = requests.get(_url)\n bs = BeautifulSoup(req.content, 'lxml')\n\n atag = bs.find('div', class_='view_search').find('a')\n dcm_no = re_numbers.findall(atag['onclick'])[1]\n\n _url2 = report_url.format(rcp_no, dcm_no)\n req2 = requests.get(_url2)\n bs2 = BeautifulSoup(req2.content, 'lxml')\n\n table = bs2.find('table').find('tbody')\n trs = table.find_all('tr')\n\n result = ['']\n for tr in trs:\n tds = tr.find_all('td')\n if len(tds) <= 1:\n continue\n\n cell_title = tds[0].get_text().strip()\n\n if pat1.search(cell_title):\n result[0] = tds[1].get_text().strip()\n\n else:\n continue\n \n return result\n\nprint(get_report('20200703800696'))","sub_path":"pys/target4.py","file_name":"target4.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343385428","text":"import sys\n\nimport tensorflow as tf\n\nfrom dataset import SingleImageDataset\nfrom models.vgg_pretrained import SingleImageModel\nfrom train_evaluate_model import freezed_pretrained_train_model\n\n\nWEIGHT_DECAY = 1e-3\nLEARNING_RATE = 5e-4\nFULLY_CONNECTED = [200]\nEPOCHS = 10\nBATCH_SIZE = 10\nINPUT_SHAPE = [280, 700, 3]\n\n\nif __name__ == '__main__':\n vgg_init_dir = sys.argv[1]\n dataset_root = sys.argv[2]\n model_path = sys.argv[3]\n resolution_factor = float(sys.argv[4])\n add_geolocations = eval(sys.argv[5])\n\n dataset = SingleImageDataset(dataset_root, BATCH_SIZE, INPUT_SHAPE, add_geolocations=add_geolocations, is_training=True)\n\n new_width = int(round(resolution_factor * INPUT_SHAPE[1]))\n new_height = int(round(resolution_factor * INPUT_SHAPE[0]))\n dataset.train_images = tf.image.resize_images(dataset.train_images, (new_height, new_width), tf.image.ResizeMethod.AREA)\n dataset.valid_images = tf.image.resize_images(dataset.valid_images, (new_height, new_width), tf.image.ResizeMethod.AREA)\n dataset.test_images = tf.image.resize_images(dataset.test_images, (new_height, new_width), tf.image.ResizeMethod.AREA)\n\n model = SingleImageModel(FULLY_CONNECTED, dataset, weight_decay=WEIGHT_DECAY, vgg_init_dir=vgg_init_dir, is_training=True)\n\n freezed_pretrained_train_model(model, dataset, LEARNING_RATE, EPOCHS, model_path)","sub_path":"convnet_single_train.py","file_name":"convnet_single_train.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"583130558","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-05-24 15:13:31\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nfrom sourcedatadownload import *\ndef main():\n ds = os.listdir('out')\n ds.remove('.DS_Store')\n\n ds = relistDate(ds)\n ds = relistremove0(ds)\n print(ds[0],ds[-1])\n lastdate = ds[-2]\n #获取date的下一天日期,date格式:年_月_日\n dats = timetool.getDateDaysFromOneDate(lastdate)\n print(dats)\n downloadNewDatas(dats)\n # today = timetool.getDateDay()\n # print(today)\n\n#测试\nif __name__ == '__main__':\n main()\n \n","sub_path":"data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79488005","text":"import numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom PyEMD import EMD, Visualisation\nfrom utils.disp.showphases import show_signal, show_csignals # showphases\n\n\ndef hes2(args):\n n = 10000\n t = np.arange(0, n/args.fs, 1/args.fs)\n S = args.singled_out[-1, 0:n]\n args.temp_add = 'emd_raw'\n show_signal(S, args)\n emd = EMD()\n emd.emd(S)\n imfs, res = emd.get_imfs_and_residue()\n\n # In general:\n # components = EEMD()(S)\n # imfs, res = components[:-1], components[-1]\n\n vis = Visualisation()\n vis.plot_imfs(imfs=imfs, residue=res, t=t, include_residue=True)\n vis.plot_instant_freq(t, imfs=imfs)\n\n vis.show()\n return 0\n\ndef hes(args):\n # fs = 10e3\n # N = 1e5\n # amp = 2 * np.sqrt(2)\n # noise_power = 0.01 * fs / 2\n # time = np.arange(N) / float(fs)\n # mod = 500 * np.cos(2 * np.pi * 0.25 * time)\n # carrier = amp * np.sin(2 * np.pi * 3e3 * time + mod)\n # noise = np.random.normal(scale=np.sqrt(noise_power), size = time.shape)\n # noise *= np.exp(-time / 5)\n # x = carrier + noise\n #\n # f, t, Zxx = signal.stft(x, fs, nperseg=10)\n # plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp)\n # plt.title('STFT Magnitude')\n # plt.ylabel('Frequency [Hz]')\n # plt.xlabel('Time [sec]')\n # plt.show()\n\n\n # segment\n for cnt_ch in range(args.singled_out_filtered_notched.shape[0]):\n y2 = args.singled_out_filtered_notched[cnt_ch, :]\n # show_insta_phase(insta_phase_norm)\n\n wind_ = np.zeros([len(args.times), args.win_l + args.win_r])\n for cnti, i in enumerate(args.times):\n i1 = int(i)\n wind_[cnti, :] = y2[i1 - args.win_l: i1 + args.win_r] # faster\n\n\n args.fr_res = 500\n sta = np.zeros([args.len_uc, 100, args.fr_res, args.fr_res, args.win_l + args.win_r])\n\n for i, uclass in enumerate(args.uc):\n ind = (args.uc_ind == i)\n temp = wind_[ind, :]\n for cnti in range(temp.shape[0]):\n what = temp[cnti, :]\n f, t, test = signal.stft(temp[cnti, :], args.fs, nperseg=100) # calc hist wind_[ind, :]\n if cnti == 0:\n stest = test\n else:\n stest += test\n # f, t, Zxx = signal.stft(x, fs, nperseg=10)\n # emd = EMD()\n # IMFs = emd(what)\n\n # plt.plot(np.abs(signal.hilbert(IMFs[1, :])))\n # plt.pcolormesh(t, f, np.abs(test))\n # plt.title('STFT Magnitude')\n # plt.ylabel('Frequency [Hz]')\n # plt.xlabel('Time [sec]')\n # plt.show()\n # plt.waitforbuttonpress(0.1)\n # plt.close('all')\n\n plt.pcolormesh(t, f, np.abs(test))\n plt.title('STFT Magnitude')\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [sec]')\n plt.show()\n plt.waitforbuttonpress(0.1)\n plt.close('all')\n\n # sta[i, cnti, :, :] = np.abs(test)\n\n # step = np.abs(np.mean(phase_reset_wind[ind, :]))\n # mean_step = np.mean()\n\n #sta_mean[i, :, :] = np.abs(np.mean(sta[i, :, :, :], 0))\n #sta_std[i, :, :] = np.abs(np.std(sta[ind, :, :, :], 0))\n\n # testimage = np.squeeze(hist_wind[i, :, :])\n # # fig, ax = plt.subplots(nrows=1, ncols=1)\n # plt.imshow(testimage) # , aspect='auto' ` \n # plt.title(np.max(testimage))\n # # ax.set_adjustable('box-forced')\n # filename = 'histophases' + str(cnt_ch) + 'ch' + str(i) + 'cl' + '.png'\n # plt.savefig(os.path.join(args.output_dir, filename), bbox_inches = 'tight', pad_inches = 0)\n # plt.close()\n # # plt.show()\n # # plt.waitforbuttonpress(0.1)\n # # save_ call show (methods>disp)\n #\n # show_csignals(phase_reset_mean, phase_reset_std, args.output_dir, cnt_ch, 'phase_reset_indx')\n #\n #\n # # imfs = emd(args.)\n # # wavelet\n # # stft\n #\n # # plot hes\n return 0\n\n\ndef stft(signal):\n\n # short time fourier\n\n # wavelet\n\n # emd\n\n return 0\n","sub_path":"utils/methods/emd.py","file_name":"emd.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329589875","text":"# ``\nimport tensorflow as tf\nimport numpy as np\n# 定义训练数据\nx_train = np.array([1.0,2.0,3.0,4.0])\ny_train = np.array([2.0,4.0,6.0,8.0])\n\n# 定义模型参数\nW = tf.Variable(0.0)\nb = tf.Variable(0.0)\n\n# 定义模型\ndef model(x):\n return W * x + b\n # 定义损失函数\ndef loss(y_pred, y_true):\n return tf.reduce_mean(tf.square(y_pred - y_true))\n\n# 定义优化器\noptimizer = tf.optimizers.SGD(learning_rate=0.01)\n\n# 定义训练函数\ndef train(x, y):\n with tf.GradientTape() as tape:\n y_pred = model(x)\n l = loss(y_pred, y)\n gradients = tape.gradient(l, [W, b])\n optimizer.apply_gradients(zip(gradients, [W, b]))\n\n# 训练模型\nfor epoch in range(100):\n for x, y in zip(x_train, y_train):\n train(x, y)\n\n# 打印模型参数\n print(\"W = {}, b = {}\".format(W.numpy(), b.numpy()))\n# ```\n#\n# 在这个示例中,我们首先定义了训练数据x_train和y_train。然后,我们定义了模型参数W和b,并定义了模型函数和损失函数。接下来,我们定义了优化器和训练函数。在训练函数中,我们使用tf.GradientTape记录了模型参数的梯度,并使用优化器更新模型参数。最后,我们使用训练数据训练模型,并打印出模型参数。\n#\n# 这只是一个简单的示例,TensorFlow还有很多其他功能和用法。希望这个示例能够帮助您入门TensorFlow。","sub_path":"LearnDay/quant/tensorflow_test.py","file_name":"tensorflow_test.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"589694430","text":"#playing around with dictionaries\n\nmy_dict = {'key 1': 123, 'key 2': 456, 'key 3': 'A string value'}\n\nmy_dict_two = {'key 1': 673, 'key 2': 732, 'a different key': 'A differnt string value'}\n\nfor common_key in my_dict.keys() & my_dict_two.keys():\n print(my_dict[common_key], my_dict_two[common_key])\n\n\n","sub_path":"Code/Cheryl/Python/practice2.py","file_name":"practice2.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197335648","text":"from os import path\nfrom google.colab import drive\n\nnotebooks_dir_name = 'notebooks'\ndrive.mount('/content/gdrive')\nnotebooks_base_dir = path.join('./gdrive/My Drive/', notebooks_dir_name)\n\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.keras.layers import InputLayer, LSTM, Dense, Activation, TimeDistributed\nfrom tensorflow.python.keras.models import Sequential \n\ndb = 'top'\n\ntroll_X = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/troll_X.npy' % (db))\ntroll_Y = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/troll_Y.npy' % (db))\ntroll_len = np.load('./gdrive/My Drive/notebooks/s11/v02/%s/troll_gamelen.npy' % (db))\n\nX_ragged = tf.RaggedTensor.from_row_lengths(troll_X, row_lengths=troll_len)\nY_ragged = tf.RaggedTensor.from_row_lengths(troll_Y, row_lengths=troll_len)\n\nmodel = Sequential()\n\nmodel.add(InputLayer(input_shape=[None, 3], ragged=True))\nmodel.add(LSTM(8))\nmodel.add(Dense(2, activation='softmax'))\n\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate=0.002, decay_steps=5985, decay_rate=0.3, staircase=True)\n\ncallback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=2)\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule), \n loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])\n \nY_rag = [[0] if sum(np.array(Y_one))<=len(Y_one)/10 else [1] for Y_one in Y_train]\n\nmodel.fit(X_train, np.array(Y_rag)[:train_len], epochs=30, batch_size=128, callbacks=[callback])\n\nmodel.evaluate(X_test, np.array(Y_rag[train_len:]))\n","sub_path":"vv2/troll_rnn_ragged.py","file_name":"troll_rnn_ragged.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112927475","text":"#!/usr/bin/env python\n##\n## smarties\n## Copyright (c) 2018 CSE-Lab, ETH Zurich, Switzerland. All rights reserved.\n## Distributed under the terms of the MIT license.\n##\n## Created by Guido Novati (novatig@ethz.ch).\n##\n\nimport sys, socket, os, os.path, time\nos.environ['DISABLE_MUJOCO_RENDERING'] = '1'\nfrom dm_control import suite\nimport numpy as np\nfrom Communicator import Communicator\n\nclass Communicator_dmc(Communicator):\n def get_env(self):\n assert(self.dmc is not None)\n return self.dmc\n\n def __init__(self):\n self.start_server()\n self.sent_stateaction_info = False\n self.discrete_actions = False\n self.number_of_agents = 1\n print(\"DeepMind Suite environment: \", sys.argv[2], \"task: \", sys.argv[3])\n env = suite.load(sys.argv[2], sys.argv[3])\n act_spec, obs_spec = env.action_spec(), env.observation_spec()\n nAct, nObs = act_spec.shape[0], 0\n for component in obs_spec.values():\n if len(component.shape): nObs = nObs + component.shape[0]\n else: nObs = nObs + 1\n\n actVals = np.zeros([0], dtype=np.float64)\n actOpts = np.zeros([0], dtype=np.float64)\n obsBnds = np.zeros([0], dtype=np.float64)\n\n for i in range(nAct):\n # assume all continuous envs with act space bounded in -1 and 1\n #actOpts = np.append(actOpts, [2.1, 0])\n actOpts = np.append(actOpts, [2.1, 1]) # bounded actions\n actVals = np.append(actVals, [-1, 1])\n\n for i in range(nObs):\n obsBnds = np.append(obsBnds, [1, -1])\n\n print(nAct, nObs, actVals, actOpts, obsBnds)\n self.obs_in_use = np.ones(nObs, dtype=np.float64)\n self.nActions, self.nStates = nAct, nObs\n self.observation_bounds = obsBnds\n self.action_options = actOpts\n self.action_bounds = actVals\n self.send_stateaction_info()\n #if self.bRender==3:\n # env = gym.wrappers.Monitor(env, './', force=True)\n self.dmc = env\n self.seq_id, self.frame_id = 0, 0\n self.seed = sys.argv[1]\n self.actionBuffer = [np.zeros([nAct], dtype=np.float64)]\n\n\nif __name__ == '__main__':\n comm = Communicator_dmc() # create communicator with smarties\n env = comm.get_env()\n\n while True: #training loop\n t = env.reset()\n obsVec = np.zeros([0], dtype=np.float64)\n for oi in t.observation.values(): obsVec = np.append(obsVec, oi)\n #send initial state\n comm.sendInitState(obsVec)\n\n while True: # simulation loop\n #receive action from smarties\n action = comm.recvAction()\n #advance the environment\n t = env.step(action)\n obs, rew, step = t.observation, t.reward, t.step_type.value\n obsVec = np.zeros([0], dtype=np.float64)\n for oi in obs.values(): obsVec = np.append(obsVec, oi)\n #send the observation to smarties\n # DMC suite does not have term condition, just truncated seqs\n comm.sendState(obsVec, rew, truncated = t.last() )\n if t.last(): break\n","sub_path":"source/Communicators/Communicator_dmc.py","file_name":"Communicator_dmc.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"446653907","text":"import pywhatkit, sys, time, itertools, threading, os, random, pytz, json, math\nimport numpy as np\nfrom datetime import datetime\n\n\nclass World:\n \n def singAsong():\n song = \"word.execute(me);\"\n pywhatkit.playonyt(song)\n \n def slow_print(text:str,speed):\n for karakter in text:\n print(karakter,end=\"\",flush=True)\n time.sleep(speed)\n def getPass(pswd):\n passwd = [\"ᛞ\",\"ᚫ\",\"ᛉ\",\"ᚵ\",\"ᛒ\",\"ᛍ\",\"ᛣ\",\"ᛤ\",\"ᛄ\"]\n if pswd == passwd:\n print(\" >>> LOGIN SUCCESS \")\n else:\n sys.exit()\n \n def layDown():\n listx = [\"ᛞ\",\"ᛞᚫ\",\"ᛞᚫᛉ\",\"ᛞᚫᛉᚵ\",\"ᛞᚫᛉᚵᛒ\",\"ᛞᚫᛉᚵᛒᛍ\",\"ᛞᚫᛉᚵᛒᛍᛣ\",\"ᛞᚫᛉᚵᛒᛍᛣᛤ\",\"ᛞᚫᛉᚵᛒᛍᛣᛤᛄ\"]\n count = 0\n for c in listx:\n if count != len(listx):\n sys.stdout.write('\\r' + c)\n time.sleep(0.0001)\n count +=1\n sys.stdout.flush()\n listy = [\"ᛄ\",\" ᛄ\",\" ᛄ\",\" ᛄ\",\" ᛄ\",\" ᛄ\"]\n count2 =0\n for cc in itertools.cycle(listy):\n if count2 == len(listy):\n break\n else:\n sys.stdout.write('\\r' + cc)\n time.sleep(0.1)\n count2 +=1\n sys.stdout.flush()\n def INITIALIZATION():\n listx = [\" ██ 39%\",\" ███ 49%\",\" ████ 76%\",\" █████ 89%\",\" ██████ 100%\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\",\" ██████ INITIALIZATION\"]\n count = 0\n for c in listx:\n if count != len(listx):\n sys.stdout.write('\\r' + c)\n time.sleep(0.1)\n count +=1\n sys.stdout.flush()\n \n def START_SIMULATION():\n obj = \"\"\"\\033[32m \\n________________________________________________________________________________________\n. . * . . . . * . . . . . . * . . . .\n* . . * . . . * . . * . . . * . . .\n. * . . . . . * . . . .-o--. . * .\n. . . . . . . * * . :O o O : . .\n____ * . . . . . . . . : O. Oo; . .\n`. ````.---...___ . * . . . * . `-.O-' . * . .\n\\_ ; \\`.-'```--..__. . . * . . . . .\n,'_,-' _,-' ``--._ . * . . . . * . . .\n-' ,-' `-._ * . . * . . .\n ,-' _,-._ ,`-. . . . . . * . .\n '--. _ _.._`-. `-._ | `_ . * . . . . . .\n ; ,' ' _ `._`._ `. `,-'' `-. . . . . . .\n ,-' \\ `;. `. ;` `._ _/\\___ `. . * . . *\n \\ \\ , `-' ) `':_ ; \\ `. . * . . . *\n \\ _; ` ,; __; `. . . . . .\n '-.; __, ` _,-'-.--''' \\-: `. * . . . * .\n )`-..---' `---'' \\ `. . . . . . . .\n___________________________________________________________________________________________\\033[0m\"\"\"\n for karakter in obj:\n print(karakter,end=\"\",flush=True)\n listx = [\" ██ 39%\",\" ███ 49%\",\" ████ 76%\",\" █████ 89%\",\" ██████ 100%\",\" ██████ GENERATE DATA\",\" ██████ GENERATE OBJECT\",\" ██████ GENERATE FUNCTION\",\" ██████ COLLECTIONG DATA\",\" ██████ DOING WORK\",\" ██████ CONNECTING TO SERVER............\",\" ██████ CONNECTING TO SERVER DONE.............\",\" ██████ S T A R T T H E S I M U L A T I O N\"]\n count = 0\n for c in listx:\n if count != len(listx):\n sys.stdout.write('\\r' + c)\n time.sleep(1)\n count +=1\n sys.stdout.flush()\n \n def set_of_point():\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n setpoint = datetime.strftime(timeNow, \"%H:%M:%S\")\n return setpoint\n \n def prettyPrint(djson, ind=4):\n print(json.dumps(djson, indent=ind, sort_keys=True))\n \n def GiveDimension(data):\n arr = np.array(data)\n print(\"\\n>>> Dimension of set point ::: \"+str(arr))\n \n def giveCIRCUMFERENCE(data):\n luas = math.pi*(data*data)\n keliling = 2*math.pi*data\n print (\"\\n>>> CIRCUMFERENCE of set point ::: \",keliling)\n \n def loopInfinity():\n for c in itertools.cycle(['|', '/', '-', '\\\\',' Then you can be my']):\n sys.stdout.write('\\r' +\"\\033[31m\"+ c+\"\\033[0m\")\n sys.stdout.flush()\n time.sleep(0.0001)\n \n def BlindMYVision():\n blind = \"\"\"\\033[32m\n \n\n 88 88 88 88 \n 88 88 \"\" 88 \n 88 88 88 \n 88,dPPYba, 88 88 8b,dPPYba, ,adPPYb,88 \n 88P' \"8a 88 88 88P' `\"8a a8\" `Y88 \n 88 d8 88 88 88 88 8b 88 \n 88b, ,a8\" 88 88 88 88 \"8a, ,d88 \n 8Y\"Ybbd8\"' 88 88 88 88 `\"8bbdP\"Y8 \n\n\n\n \\033[0m\n \"\"\"\n print(blind)\n \n def GiveAllSumulation():\n return \"Dummy\"\n \n def run_Exec(me):\n if me == \"happy\":\n return \"\\n-- S U C C E S S E X E C U T E --\"\n \n def TRAPPED():\n for c in itertools.cycle(['💀 Though we are trapped', ' Though we are trapped']):\n sys.stdout.write('\\r' +\"\\033[31m\"+ c+\"\\033[0m\")\n sys.stdout.flush()\n time.sleep(0.0001)\n \n def IMTRAPPED():\n for c in itertools.cycle(['❤️ Though IM trapped', ' Though IM trapped']):\n sys.stdout.write('\\r' +\"\\033[31m\"+ c+\"\\033[0m\")\n sys.stdout.flush()\n time.sleep(0.0001)\n \n def GET_NUTRIENTS():\n return \"-- S U C C E S S G E T N U T R I E N T S --\"\n \n def GET_ANTIOXIDANTS():\n return \"-- S U C C E S S A N T I O X I D A N T S --\"\n \n def GET_ENJOYMENT():\n return \"-- S U C C E S S E N J O Y M E N T --\"\n \n def GOD_EXISTENCE():\n return \"-- S U C C E S S U P G R A D E T O [G O D] --\"\n \n def GetTimeNow():\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n localtimes = datetime.strftime(timeNow, \"%a %I.%M \")\n return localtimes\n \n def EnterTrance(target):\n os.system(f\"python -m trace --listfuncs {target}\")\n \n def LeftSystem():\n sys.exit(\"LEFT THE SIMULATION\")\n\n def ChallengingYourGod():\n for c in itertools.cycle(['|', '/', '-', '\\\\',' Challenging your god']):\n sys.stdout.write('\\r' +\"\\033[31m\"+ c+\"\\033[0m\")\n sys.stdout.flush()\n time.sleep(0.0001)\n \n def FxingIllegalArgument():\n for c in itertools.cycle(\n [\"ᛞ Fixing Illegal Arguments\",\"ᛞᚫ Fixing Illegal Arguments\",\"ᛞᚫᛉ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵᛒ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵᛒᛍ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵᛒᛍᛣ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵᛒᛍᛣᛤ Fixing Illegal Arguments\",\"ᛞᚫᛉᚵᛒᛍᛣᛤᛄ Fixing Illegal Arguments\"]\n ):\n sys.stdout.write('\\r' +\"\\033[31m\"+ c+\"\\033[0m\")\n sys.stdout.flush()\n time.sleep(0.0001)\n \n def run_execution():\n print(\"\\n\")\n exec(\"print('SYSTEM TRY ::: EXECUTION!!')\")\n \n def announce(num,say):\n datas = {\"number\":num,\"says\":say}\n print(json.dumps(datas, indent=4, sort_keys=True))\n\n def Execute(me):\n if me != \"\":\n fire = \"\"\"\n _ _ _ _ ___ _ __ _____ _____ __ _ _ ___ ___ _ _ _ ___ _ \n| | | |/ \\| o \\ | | \\ | __\\ V / __/ _|| | ||_ _|| __| //| \\_/ || __|\\\\ \n| V V ( o ) / |_ | o ) | _| ) (| _( (_ | U | | | | _| || | \\_/ || _| |()\n \\_n_/ \\_/|_|\\\\___||__() |___/_n_\\___\\__||___| |_| |___||| |_| |_||___| |()\n \\\\ //V \n\nCREATE BY ALIF BUDIMAN\nMUSIC BY MILI 'WORLD.EXECUTE(ME);'\n \n. . * . . . . * . . . . . . * . . . .\n* . . * . . . * . . * . . . * . . .\n. . * . . . . * . . . . . . * . . . .\n* . . * . . . * . . * . . . * . . .\n. . * . . . . * . . . . . . * . . . .\n* . . * . . . * . . * . . . * . . .\nEXECUTION!!\n\"\"\" \n for karakter in fire:\n print(karakter,end=\"\",flush=True)\n time.sleep(0.001)\n ","sub_path":"objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":9555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"271438804","text":"from mrjob.job import MRJob\nfrom mrjob.step import MRStep\nimport re\n\nclass CTRJob(MRJob):\n '''\n Retruns CTR for each advertisment, and for each advertisement type\n '''\n def mapper(self, _, line):\n temp = line.split(',')\n add_id = temp[0]\n click = int(temp[2])\n add_type = temp[3]\n yield add_id, click\n yield add_type, click\n\n\n def reducer(self, key, value):\n add_id = key\n clicks = 0\n len_v = 0\n for x in value:\n clicks += x\n len_v += 1\n\n yield add_id, clicks/float(len_v)\n\n\n\nif __name__ == '__main__':\n CTRJob.run()\n","sub_path":"ctr/compute_ctr.py","file_name":"compute_ctr.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574568350","text":"# модальный диалог с формой, данные извлекаются до уничтожения окна\n# Если нажать кнопку в главном окне, сценарий создаст окно диало-\n# га с формой, блокирующее остальное приложение\n\n\nfrom tkinter import *\nfrom tk14 import makeform, fetch, fields\n\n\ndef show(entries, popup):\n fetch(entries) # извлечь данные перед уничтожением окна!\n popup.destroy() # если инструкции поменять местами, сценарий будет возбуждать исключение\n\n\ndef ask():\n popup = Toplevel() # отобразить форму в виде модального диалога\n ents = makeform(popup, fields)\n Button(popup, text='OK', command=(lambda: show(ents, popup))).pack()\n popup.grab_set()\n popup.focus_set()\n popup.wait_window() # ждать закрытия окна\n\n\nroot = Tk()\nButton(root, text='Dialog', command=ask).pack()\nroot.mainloop()\n","sub_path":"tk15.py","file_name":"tk15.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316599842","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport pandas as pd\nimport numpy as np\nfrom delphi_utils import GeoMapper\n\ndef detect_date_col(col_name: str):\n \"\"\"determine if column name is a date\"\"\"\n date_match = re.match(r'\\d{1,2}\\/\\d{1,2}\\/\\d{1,2}', col_name)\n if date_match:\n return True\n return False\n\ndef pull_jhu_data(base_url: str, metric: str, pop_df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Pulls the latest Johns Hopkins CSSE data, and conforms it into a dataset\n\n The output dataset has:\n\n - Each row corresponds to (County, Date), denoted (FIPS, timestamp)\n - Each row additionally has a column `new_counts` corresponding to the new\n new_counts (either `confirmed` cases or `deaths`), and a column\n `cumulative_counts`, correspond to the aggregate metric from January 22nd\n (as of April 27th) until the latest date.\n\n Note that the raw dataset gives the `cumulative_counts` metric, from which\n we compute `new_counts` by taking first differences. Hence, `new_counts`\n may be negative. This is wholly dependent on the quality of the raw\n dataset.\n\n We filter the data such that we only keep rows with valid FIPS, or \"FIPS\"\n codes defined under the exceptions of the README. The current exceptions\n include:\n\n - 70002: Dukes County and Nantucket County in Massachusetts, which are\n reported together\n - 70003: Kansas City, Missouri, which reports counts separately from the\n four counties it intesects (Platte, Cass, Clay, Jackson Counties)\n\n Parameters\n ----------\n base_url: str\n Base URL for pulling the JHU CSSE data\n metric: str\n One of 'confirmed' or 'deaths'.\n pop_df: pd.DataFrame\n Read from static file \"fips_population.csv\".\n\n Returns\n -------\n pd.DataFrame\n Dataframe as described above.\n \"\"\"\n\n # Read data\n df = pd.read_csv(base_url.format(metric=metric))\n\n # FIPS are missing for some nonstandard FIPS\n date_cols = [col_name for col_name in df.columns if detect_date_col(col_name)]\n keep_cols = date_cols + ['UID']\n df = df[keep_cols]\n\n df = df.melt(\n id_vars=[\"UID\"],\n var_name=\"timestamp\",\n value_name=\"cumulative_counts\",\n )\n df[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"])\n\n gmpr = GeoMapper()\n df = gmpr.replace_geocode(df, \"jhu_uid\", \"fips\", from_col=\"UID\", date_col=\"timestamp\")\n\n # Merge in population LOWERCASE, consistent across confirmed and deaths\n # Set population as NAN for fake fips\n pop_df.rename(columns={'FIPS':'fips'}, inplace=True)\n pop_df['fips'] = pop_df['fips'].astype(int).\\\n astype(str).str.zfill(5)\n df = pd.merge(df, pop_df, on=\"fips\", how='left')\n\n # Add a dummy first row here on day before first day\n # code below could be cleaned with groupby.diff\n\n min_ts = min(df[\"timestamp\"])\n df_dummy = df.loc[df[\"timestamp\"] == min_ts].copy()\n df_dummy.loc[:, \"timestamp\"] = min_ts - pd.Timedelta(days=1)\n df_dummy.loc[:, \"cumulative_counts\"] = 0\n df = pd.concat([df_dummy, df])\n # Obtain new_counts\n df.sort_values([\"fips\", \"timestamp\"], inplace=True)\n df[\"new_counts\"] = df[\"cumulative_counts\"].diff() # 1st discrete difference\n # Handle edge cases where we diffed across fips\n mask = df[\"fips\"] != df[\"fips\"].shift(1)\n df.loc[mask, \"new_counts\"] = np.nan\n df.reset_index(inplace=True, drop=True)\n\n # Final sanity checks\n days_by_fips = df.groupby(\"fips\").count()[\"cumulative_counts\"].unique()\n unique_days = df[\"timestamp\"].unique()\n # each FIPS has same number of rows\n if (len(days_by_fips) > 1) or (days_by_fips[0] != len(unique_days)):\n raise ValueError(\"Differing number of days by fips\")\n min_timestamp = min(unique_days)\n max_timestamp = max(unique_days)\n n_days = (max_timestamp - min_timestamp) / np.timedelta64(1, \"D\") + 1\n if n_days != len(unique_days):\n raise ValueError(\n f\"Not every day between {min_timestamp} and \"\n \"{max_timestamp} is represented.\"\n )\n return df.loc[\n df[\"timestamp\"] >= min_ts,\n [ # Reorder\n \"fips\",\n \"timestamp\",\n \"population\",\n \"new_counts\",\n \"cumulative_counts\",\n ],\n ]\n","sub_path":"jhu/delphi_jhu/pull.py","file_name":"pull.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211801494","text":"#!/usr/bin/env python\n# using an LCD with the pifon\n#\n# I use an Adafruit LCD Plate for the Raspi here\n# http://learn.adafruit.com/adafruit-16x2-character-lcd-plus-keypad-for-raspberry-pi \n#\n\nimport time\nfrom contrib.Adafruit_CharLCDPlate import Adafruit_CharLCDPlate\nfrom ui import UI\n\n# user interface class\nclass LCDUI(UI):\n def __init__(self):\n # setup display\n self.lcd = Adafruit_CharLCDPlate()\n self.lcd.begin(16, 2)\n self.lcd.clear()\n # init state\n self.last_mask = 0\n self.num_buttons = 5\n self.last_repeat = []\n self.first_flag = []\n self.start_time = 0.5\n self.repeat_time = 0.2\n self.clear_line = \" \" * 16\n self.last_value_len = 0\n self.last_status_len = 0\n self.last_msg_len = 0\n self.last_back = self.BACK_OFF\n for i in xrange(self.num_buttons):\n self.last_repeat.append([0])\n self.first_flag.append(True)\n # map buttons\n self.map = {\n self.lcd.BUTTON_SELECT : self.EVENT_PICK,\n self.lcd.BUTTON_RIGHT : self.EVENT_INC,\n self.lcd.BUTTON_LEFT : self.EVENT_DEC,\n self.lcd.BUTTON_DOWN : self.EVENT_NEXT,\n self.lcd.BUTTON_UP : self.EVENT_PREV\n }\n # map background\n self.map_back = {\n self.BACK_OFF : self.lcd.OFF,\n self.BACK_WHITE : self.lcd.WHITE,\n self.BACK_RED : self.lcd.RED,\n self.BACK_GREEN : self.lcd.GREEN,\n self.BACK_BLUE : self.lcd.BLUE,\n self.BACK_YELLOW : self.lcd.YELLOW,\n self.BACK_TEAL : self.lcd.TEAL,\n self.BACK_VIOLET : self.lcd.VIOLET\n }\n\n def shutdown(self):\n self.lcd.clear()\n self.lcd.noDisplay()\n self.lcd.backlight(self.lcd.OFF)\n\n def update_background(self, back):\n \"\"\"update background\"\"\"\n if back != self.last_back:\n self.last_back = back\n mapped_back = self.map_back[back]\n self.lcd.backlight(mapped_back)\n \n def show_menu(self, title):\n \"\"\"start showing a menu\"\"\"\n # limit to 8 chars\n t = (title + \" \" * 8)[:8]\n t += \" \" * 8\n self.last_value_len = 0\n self.lcd.setCursor(0,1)\n self.lcd.message(t)\n \n def hide_menu(self):\n self.show_menu(\"\")\n \n def _update_value(self, value, last_len, size, pad_right=False):\n \"\"\"update value and return (txt, pos, new_last_len)\"\"\"\n t = str(value)\n n = len(t)\n # limit to n chars\n if n > size:\n t = t[:size]\n n = size\n # overwrite last value\n if n < last_len: \n d = last_len - n\n if pad_right:\n t = t + (\" \" * d)\n else:\n t = (\" \" * d) + t\n pos = size - len(t)\n return (t, pos, n)\n \n def update_menu_value(self, value):\n \"\"\"update a value change in the menu\"\"\"\n (txt, pos, self.last_value_len) = self._update_value(value, self.last_value_len, 4)\n self.lcd.setCursor(pos + 12,1)\n self.lcd.message(txt)\n\n def update_title(self, title):\n \"\"\"update the title message\"\"\"\n self.lcd.setCursor(0,0)\n self.lcd.message(title)\n\n def update_status(self, status):\n \"\"\"update the status bar\"\"\"\n (txt, pos, self.last_status_len) = self._update_value(status, self.last_status_len, 10)\n self.lcd.setCursor(pos + 6,0)\n self.lcd.message(txt)\n \n def show_message(self, msg):\n \"\"\"if no menu is shown then you can show a message\"\"\"\n self.last_msg_len = 16\n self.update_message(msg)\n \n def update_message(self, msg):\n (txt, pos, self.last_msg_len) = self._update_value(msg, self.last_msg_len, 16, True)\n self.lcd.setCursor(0,1)\n self.lcd.message(txt) \n \n def hide_message(self):\n \"\"\"if a message is shown then hide it\"\"\"\n self.update_message(\"\")\n \n def get_next_event(self):\n \"\"\"return the next button event or 0 if no event occurred\"\"\"\n # check for new press\n mask = self.lcd.buttonRead()\n changes = (self.last_mask ^ mask) & mask\n self.last_mask = mask\n # any button newly pressed\n ts = time.time()\n result = 0\n if changes != 0:\n for i in xrange(self.num_buttons):\n if changes & (1< self.start_time:\n result |= 1< self.repeat_time:\n result |= 1< = menu\")\n while True:\n ev = ui.get_next_event()\n if ev & ui.EVENT_PICK:\n if in_menu:\n ui.hide_menu()\n ui.show_message(\"\\r\\n\\t \\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n","sub_path":"homepage/cached_templates/templates/registration.html.py","file_name":"registration.html.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128643902","text":"class Account:\r\n def __init__(self, owner, balance):\r\n self.owner = owner\r\n self. balance = balance\r\n\r\n def __str__(self):\r\n return(f\"Account holder name: {self.owner}\\nAccount balance: {self.balance}\")\r\n def deposit(self,amount):\r\n if amount> 0:\r\n\r\n self.balance+=amount\r\n print(\"Cash credited to your account.\")\r\n else:\r\n print(\"you cannot enter this try again\")\r\n def withdraw(self, cash):\r\n if cash <= self.balance:\r\n print(f\"This is your Rs {cash}.\")\r\n self.balance-=cash\r\n else:\r\n print(\"Unsufficient funds in your account.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n a1 = Account(\"Aakash_Malhotra\", 100)\r\n print(a1)\r\n\r\n a1.deposit(10000)\r\n print(a1)\r\n a1.withdraw(500)\r\n print(a1.balance)\r\n print(a1)\r\n (a1.withdraw(10000000))\r\n","sub_path":"203_class_and_object_example.py","file_name":"203_class_and_object_example.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432188355","text":"\"\"\"config_manager module\"\"\"\n\nfrom collections import defaultdict\nimport logging\nimport os\nimport voluptuous as vol\n\nfrom homecontrol.dependencies.yaml_loader import YAMLLoader\nfrom homecontrol.exceptions import (\n ConfigDomainAlreadyRegistered,\n ConfigurationNotApproved\n)\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass ConfigManager:\n \"\"\"\n ConfigManager\n\n Manages the configuration with configuration domains\n \"\"\"\n\n def __init__(self, cfg: dict, cfg_path: str) -> None:\n self.cfg = cfg\n self.cfg_path = cfg_path\n self.registered_handlers = {}\n self.registered_domains = set()\n self.domain_schemas = {}\n self.domain_reloadable = defaultdict(bool)\n\n def get(self, key, default=None):\n \"\"\"getter for self.cfg\"\"\"\n return self.cfg.get(key, default)\n\n def __getitem__(self, key):\n return self.cfg[key]\n\n async def reload_config(self) -> None:\n \"\"\"Reloads the configuration and updates where it can\"\"\"\n cfg = YAMLLoader.load(\n open(self.cfg_path), cfg_folder=os.path.dirname(self.cfg_path))\n\n LOGGER.info(\"Updating the configuration\")\n for domain, domain_config in cfg.items():\n if domain_config != self.cfg.get(domain, None):\n LOGGER.info(\"New configuration detected for domain %s\", domain)\n\n if not self.domain_reloadable[domain]:\n LOGGER.error(\n \"Configuration domain %s is not reloadable\", domain)\n continue\n try:\n domain_config = await self.approve_domain_config(\n domain,\n domain_config,\n initial=False)\n except (vol.Error, ConfigurationNotApproved):\n continue\n\n self.cfg[domain] = domain_config\n\n if hasattr(self.registered_handlers.get(domain, None),\n \"apply_new_configuration\"):\n handler = self.registered_handlers[domain]\n await handler.apply_new_configuration(\n domain, domain_config)\n\n LOGGER.info(\"Configuration for domain %s updated\", domain)\n\n LOGGER.info(\"Completed updating the configuration\")\n\n async def approve_domain_config(self,\n domain: str,\n config: dict,\n initial: bool = True) -> dict:\n \"\"\"\n Returns an approved and validated version of config for a domain\n \"\"\"\n if domain in self.domain_schemas: # Validate new configuration\n try:\n config = self.domain_schemas[domain](config)\n except vol.Error as e:\n LOGGER.error(\n \"Configuration for domain %s is invalid\",\n domain,\n exc_info=True)\n raise e\n\n # Check if the domain owner approves\n if hasattr(self.registered_handlers.get(domain, None),\n \"approve_configuration\"):\n handler = self.registered_handlers[domain]\n result = await handler.approve_configuration(config)\n # pylint: disable=singleton-comparison\n # None should be accepted\n if result == False: # noqa: E712\n LOGGER.warning(\n \"Configuration for domain %s not approved\", domain)\n raise ConfigurationNotApproved(domain)\n\n return config\n\n async def register_domain(self,\n domain: str,\n handler: object = None,\n schema: vol.Schema = None,\n allow_reload: bool = False,\n default: dict = None) -> object:\n \"\"\"\n Registers a configuration domain\n\n Objects can register themselves to their own configuration domain and\n subscribe to changes in the configuration\n\n Args:\n domain (str):\n The configuration domain (A top-level key in config.yaml)\n handler (object):\n The object subscribing to this domain.\n Methods it can implement are:\n - approve_configuration(domain, config) -> bool:\n - apply_new_configuration(domain, config) -> None:\n If not specified then your\n configuration domain will not be reloadable\n allow_reload (bool):\n Allow reloading this configuration domain\n schema (voluptuous.Schema):\n Schema to validate the configuration and to fill in defaults\n default (dict):\n A default configuration\n\n Returns:\n A validated and approved version of the configuration\n \"\"\"\n if domain in self.registered_domains:\n raise ConfigDomainAlreadyRegistered(\n f\"The configuration domain {domain} is already registered\")\n\n # If no handler given then prevent every reloading\n if handler:\n self.registered_handlers[domain] = handler\n self.domain_reloadable[domain] = allow_reload\n if schema:\n self.domain_schemas[domain] = schema\n\n return await self.approve_domain_config(\n domain, self.cfg.get(domain, default or {}), initial=True)\n","sub_path":"homecontrol/dependencies/config_manager.py","file_name":"config_manager.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166223174","text":"#!/usr/bin/env python3\n\"\"\"\nDefines function that determines the steady state probabilities of\na regular Markov Chain\n\"\"\"\n\n\nimport numpy as np\n\n\ndef regular(P):\n \"\"\"\n Determines the steady state probabilities of a regular Markov Chain\n\n parameters:\n P [square 2D numpy.ndarray of shape (n, n)]:\n representing the transition matrix\n P[i, j] is the probability of transitioning from state i to state j\n n: the number of state in the Markov Chain\n\n returns:\n [a numpy.ndarray of shape (1, n)]:\n representing the steady state probabilities\n or None on failure\n \"\"\"\n # check that P is the correct type and dimensions\n if type(P) is not np.ndarray or len(P.shape) != 2:\n return None\n # save value of n and check that P is square\n n, n_check = P.shape\n if n != n_check:\n return None\n if not (P > 0).all():\n return None\n Identity = np.identity(n)\n Q = P - Identity\n e = np.ones((n,))\n Qe = np.c_[Q, e]\n QTQ = np.matmul(Qe, Qe.T)\n QbT = np.ones((n,))\n result = np.linalg.solve(QTQ, QbT)\n return np.expand_dims(result, axis=0)\n","sub_path":"unsupervised_learning/0x02-hmm/1-regular.py","file_name":"1-regular.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613514614","text":"import wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title):\n super().__init__(parent, title=title, size=(300, 800))\n\n menubar = wx.MenuBar()\n fileMenu = wx.Menu()\n item = fileMenu.Append(wx.ID_EXIT, \"Выход\\tCtrl+Q\", \"Выход есть!\")\n\n menubar.Append(fileMenu, \"&File\")\n self.SetMenuBar(menubar)\n\n self.Bind(wx.EVT_MENU, self.onQuit, item)\n\n\n def onQuit(self, event):\n self.Close()\n\n \napp = wx.App()\n\nframe = MyFrame(None, \"Fuck you again!\")\nframe.Show()\n\napp.MainLoop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649276501","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nimport requests\r\n\r\ndef APItest_func(url):\r\n headers = {}\r\n params = {}\r\n req = requests.get(url, headers=headers, params=params)\r\n print(req.text)\r\n\r\n\r\nif __name__ == '__main__':\r\n url = \"https://developer.mapquest.com/documentation/geocoding-api/address/get/\"\r\n APItest_func(url)\r\n","sub_path":"题目2.py","file_name":"题目2.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"418680265","text":"import unittest\nimport numpy as np\nimport hungarian_algorithm\n\n\nclass TestHungarianAlgorithm(unittest.TestCase):\n def test_reduction(self):\n test_matrix = np.array(\n [[20, 40, 10, 50], [100, 80, 30, 40], [10, 5, 60, 20], [70, 30, 10, 25]]\n )\n expected_reduced_matrix = np.array(\n [[5, 30, 0, 30], [65, 50, 0, 0], [0, 0, 55, 5], [55, 20, 0, 5]]\n )\n expected_lower_bound = 70\n\n (result_matrix, result_lower_bound) = hungarian_algorithm.reduction(test_matrix)\n self.assertTrue(np.all(expected_reduced_matrix == result_matrix))\n self.assertEqual(expected_lower_bound, result_lower_bound)\n\n def test_search_zeros(self):\n test_matrix = np.array(\n [[5, 30, 0, 30], [65, 50, 0, 0], [0, 0, 55, 5], [55, 20, 0, 5]]\n )\n # (row_number, col_number)\n zeros_set_permutations = [{(2, 0), (1, 3), (3, 2)},\n {(1, 3), (2, 1), (3, 2)},\n {(0, 2), (1, 3), (2, 1)},\n {(0, 2), (1, 3), (2, 0)}]\n result = hungarian_algorithm.search_zeros(test_matrix)\n self.assertIn(set(result), zeros_set_permutations)\n\n def test_get_solution(self):\n test_matrix = np.array(\n [[20, 40, 10, 50], [100, 80, 30, 40], [10, 5, 60, 20], [70, 30, 10, 25]]\n )\n expected_cost = 75\n\n _, result_cost = hungarian_algorithm.get_solution(test_matrix)\n self.assertEqual(result_cost, expected_cost)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_hungarian_algorithm.py","file_name":"test_hungarian_algorithm.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"540485506","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nimport copy\r\n\r\nclass DiscreteSquareMap:\r\n\r\n # -----------→ width (Y)\r\n # |\r\n # |\r\n # |\r\n # |\r\n # ↓ height (X)\r\n\r\n def __init__(self, width=5, height=5):\r\n self.BLOCKED = -1\r\n self.UNVISITED = 0\r\n self.VISITED = 1\r\n\r\n self.width = width\r\n self.height = height\r\n\r\n self.data = np.zeros((height, width), dtype=int)\r\n\r\n\r\n def block_area(self, start, end):\r\n for i in range(start[0], end[0]+1):\r\n for j in range(start[1], end[1]+1):\r\n self.data[i][j] = -1\r\n\r\n\r\n def access(self, locX, locY):\r\n if locX >= self.height or locX < 0:\r\n return self.BLOCKED\r\n if locY >= self.width or locY < 0:\r\n return self.BLOCKED\r\n return self.data[locX][locY]\r\n\r\n\r\n def visit(self, locX, locY):\r\n assert self.data[locX][locY] != self.BLOCKED\r\n self.data[locX][locY] = self.VISITED\r\n\r\n\r\nclass DiscreteSquareMapCounter:\r\n def __init__(self, map):\r\n self.BLOCKED = -1\r\n\r\n self.width = map.width\r\n self.height = map.height\r\n\r\n self.data = map.data.copy()\r\n\r\n def update(self, map):\r\n self.data = map.data.copy()\r\n\r\n def visit(self, locX, locY):\r\n assert self.data[locX][locY] != self.BLOCKED\r\n self.data[locX][locY] += 1\r\n\r\n def get_data(self, max_count=None):\r\n data = self.data.copy()\r\n\r\n if max_count is not None:\r\n data[self.data > max_count] = max_count\r\n\r\n return data\r\n\r\n def visualize(self):\r\n print(self.data)\r\n\r\n\r\nclass DiscreteSquareMapEnv():\r\n def __init__(self, map_dim=(5, 5), block_area=None, start=(0, 0), preset=None):\r\n if preset is not None:\r\n self.preset_map(preset)\r\n return\r\n\r\n self.map = DiscreteSquareMap(map_dim[0], map_dim[1])\r\n\r\n if block_area is not None:\r\n assert isinstance(block_area, tuple), \"block_area must be a tuple of ((x1, y1), (x2, y2))\"\r\n for i, v in enumerate(block_area):\r\n self.map.block_area(v[0], v[1])\r\n\r\n self.counter = DiscreteSquareMapCounter(self.map)\r\n\r\n self.UP = 0\r\n self.DOWN = 1\r\n self.LEFT = 2\r\n self.RIGHT = 3\r\n\r\n self.agentX = start[0]\r\n self.agentY = start[1]\r\n\r\n self.agent_turns = 0\r\n self.agent_distance = 1\r\n self.agent_episode = []\r\n self.path = [[self.agentX, self.agentY]]\r\n self.block_area = block_area\r\n\r\n self.last_action = None\r\n\r\n assert self.map.access(start[0], start[1]) != self.map.BLOCKED, \"invalid starting location\"\r\n\r\n self.map.visit(start[0], start[1])\r\n self.counter.visit(start[0], start[1])\r\n\r\n\r\n def preset_map(self, id):\r\n if id == 1:\r\n self.__init__((5,5), (((1,1), (3,3)),), (0,0))\r\n if id == 2:\r\n self.__init__((5,5), (((1,2), (3,2)),), (0,0))\r\n if id == 3:\r\n self.__init__((5,5), None, (0,0))\r\n if id == 4:\r\n self.__init__((10,3), (((0, 3), (0, 6)), ((2, 3), (2, 6))))\r\n if id == 5:\r\n self.__init__((10,4), (((0, 3), (0, 6)), ((3, 3), (3, 6))))\r\n if id == 6:\r\n self.__init__((10,10), (((6, 0), (9, 3)), ((0, 4), (2, 9))))\r\n if id == 7:\r\n self.__init__((6,6),(((1,2),(3,3)),((4,4),(5,5))),(0,0))\r\n\r\n if id == 101:\r\n self.__init__((10,10),\r\n ( ((1,1), (1,2)),\r\n ((1,2), (3,2)),\r\n ((6,1), (8,1)),\r\n ((8,1), (8,3)),\r\n ((6,3), (8,3)),\r\n ((3,4), (4,4)),\r\n ((4,4), (4,5)),\r\n ((6,6), (6,7)),\r\n ((1,7), (2,8)),\r\n ),\r\n (0,0))\r\n\r\n\r\n def entire_map(self):\r\n return self.map.data.copy()\r\n\r\n\r\n def local_map(self, width, height, center=None):\r\n assert width % 2 == 1, \"width must be an odd number\"\r\n assert height % 2 == 1, \"height must be an odd number\"\r\n\r\n if center is None:\r\n locX = self.agentX\r\n locY = self.agentY\r\n else:\r\n locX = center[0]\r\n locY = center[1]\r\n\r\n x_offset = locX - int(height / 2)\r\n y_offset = locY - int(width / 2)\r\n\r\n lmap = np.zeros((height, width), dtype=int)\r\n\r\n for i in range(x_offset, x_offset + height):\r\n for j in range(y_offset, y_offset + width):\r\n lmap[i-x_offset][j-y_offset] = self.map.access(i, j)\r\n\r\n return lmap.copy()\r\n\r\n\r\n def travel_distance(self):\r\n return self.agent_distance\r\n\r\n\r\n def num_turns(self):\r\n return self.agent_turns\r\n\r\n\r\n def current_episode(self):\r\n return self.agent_episode.copy()\r\n\r\n\r\n def agent_location(self):\r\n return (self.agentX, self.agentY)\r\n\r\n\r\n def available_actions(self):\r\n actions = []\r\n if self.map.access(self.agentX-1, self.agentY) != self.map.BLOCKED:\r\n actions.append(self.UP)\r\n if self.map.access(self.agentX+1, self.agentY) != self.map.BLOCKED:\r\n actions.append(self.DOWN)\r\n if self.map.access(self.agentX, self.agentY-1) != self.map.BLOCKED:\r\n actions.append(self.LEFT)\r\n if self.map.access(self.agentX, self.agentY+1) != self.map.BLOCKED:\r\n actions.append(self.RIGHT)\r\n return actions.copy()\r\n\r\n\r\n def num_unvisited_successors(self, action):\r\n sum = 0\r\n if self.map.access(self.agentX-1, self.agentY) == self.map.UNVISITED:\r\n sum += 1\r\n if self.map.access(self.agentX+1, self.agentY) == self.map.UNVISITED:\r\n sum += 1\r\n if self.map.access(self.agentX, self.agentY-1) == self.map.UNVISITED:\r\n sum += 1\r\n if self.map.access(self.agentX, self.agentY+1) == self.map.UNVISITED:\r\n sum += 1\r\n return sum\r\n\r\n\r\n def next_location(self, action):\r\n if action == self.UP:\r\n return (self.agentX-1, self.agentY)\r\n elif action == self.DOWN:\r\n return (self.agentX+1, self.agentY)\r\n elif action == self.LEFT:\r\n return (self.agentX, self.agentY-1)\r\n elif action == self.RIGHT:\r\n return (self.agentX, self.agentY+1)\r\n\r\n raise Exception(\"invalid action entered\")\r\n\r\n\r\n def remaining_nodes(self):\r\n nodes = []\r\n\r\n for i in range(self.map.height+1):\r\n for j in range(self.map.width+1):\r\n if self.map.access(i, j) == self.map.UNVISITED:\r\n nodes.append((i, j))\r\n\r\n return nodes.copy()\r\n\r\n\r\n def num_unvisited_nodes(self):\r\n return len(self.map.data[self.map.data == 0])\r\n\r\n\r\n def step(self, action):\r\n assert action in self.available_actions(), \"invalid action\"\r\n\r\n self.agentX, self.agentY = self.next_location(action)\r\n\r\n self.map.visit(self.agentX, self.agentY)\r\n self.counter.visit(self.agentX, self.agentY)\r\n\r\n self.agent_distance += 1\r\n\r\n if self.last_action is not None and self.last_action != action:\r\n self.agent_turns += 1\r\n\r\n self.agent_episode.append(action)\r\n self.path.append([self.agentX, self.agentY])\r\n\r\n self.last_action = action\r\n\r\n return\r\n\r\n\r\n def next_entire_map(self, action):\r\n assert action in self.available_actions(), \"invalid action\"\r\n\r\n m = self.entire_map()\r\n agentX, agentY = self.next_location(action)\r\n m[agentX][agentY] = self.map.VISITED\r\n\r\n return m\r\n\r\n\r\n def visualize(self):\r\n temp = self.map.data.copy().astype(str)\r\n temp[temp == '-1'] = 'B'\r\n temp[self.agentX][self.agentY] = 'A'\r\n print(temp)\r\n\r\n\r\n def plot_path(self, label_data=None):\r\n plt.figure(figsize=(15, 15), dpi=80)\r\n\r\n ax = plt.gca()\r\n ax.grid(zorder=0)\r\n ax.set_axisbelow(True)\r\n ax.set_aspect('equal', 'box')\r\n\r\n path = np.array(self.path)\r\n\r\n ## plot border\r\n plt.xlim([0, self.map.height])\r\n plt.ylim([0, self.map.width])\r\n\r\n plt.xticks(np.arange(0, self.map.height+ .1, 1.0))\r\n plt.yticks(np.arange(0, self.map.width+ .1, 1.0))\r\n\r\n plt.plot([0, 0, self.map.height, self.map.height, 0], [0, self.map.width, self.map.width, 0, 0], color=\"brown\", linewidth=5, zorder=1)\r\n\r\n ## plot obstacles\r\n if self.block_area is not None:\r\n for b in self.block_area:\r\n blk = patches.Rectangle(b[0], b[1][0] - b[0][0] + 1, b[1][1] - b[0][1] + 1, facecolor=\"grey\", linewidth=5, zorder=1)\r\n bd = patches.Rectangle(b[0], b[1][0] - b[0][0] + 1, b[1][1] - b[0][1] + 1, color=\"brown\", linewidth=5, fill=False, zorder=1)\r\n ax.add_patch(blk)\r\n ax.add_patch(bd)\r\n\r\n ## plot grid label\r\n if label_data is not None:\r\n for i in range(self.map.height):\r\n for j in range(self.map.width):\r\n plt.text(i+0.4, j+0.4, label_data[i][j], fontsize=24, zorder=2, alpha=0.5)\r\n\r\n\r\n ## plot path\r\n if path is not None:\r\n for i in range(len(path)-1):\r\n offset = 0.5\r\n x1 = path[i][0] + offset\r\n x2 = path[i+1][0] + offset\r\n y1 = path[i][1] + offset\r\n y2 = path[i+1][1] + offset\r\n plt.plot([x1, x2], [y1, y2], color=\"blue\", linewidth=30, alpha=0.3, zorder=1)\r\n\r\n for i in range(len(path)-1):\r\n offset = 0.5\r\n x1 = path[i][0] + offset\r\n x2 = path[i+1][0] + offset\r\n y1 = path[i][1] + offset\r\n y2 = path[i+1][1] + offset\r\n plt.arrow(x1, y1, x2-x1, y2-y1, head_width=0.1, head_length=0.1, fc='white', ec='white', alpha=0.2, zorder=4)\r\n\r\n plt.show()\r\n\r\n\r\ndef main():\r\n # env = DiscreteSquareMapEnv(map_dim=(6, 6), block_area=(((1, 2), (3, 3)), ((4, 4), (5, 5))))\r\n env = DiscreteSquareMapEnv(preset=6)\r\n\r\n # print(\"Initial map:\")\r\n # env.visualize()\r\n # print(env.local_map(3, 3))\r\n\r\n env.step(env.DOWN)\r\n # env.visualize()\r\n # env.counter.visualize()\r\n\r\n env.step(env.RIGHT)\r\n # env.visualize()\r\n # env.counter.visualize()\r\n\r\n env.step(env.LEFT)\r\n\r\n for i in range(40):\r\n env.step(env.DOWN)\r\n env.step(env.UP)\r\n\r\n env.visualize()\r\n print(env.counter.get_data(max_count=10))\r\n\r\n env.plot_path()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"codalab/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":10743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300240765","text":"# 两层简单神经网络(全连接)\n\nimport tensorflow as tf\n\n# 定义输入和参数\n# 用placeholder实现输入定义(sess.run中喂如一组数据)\n\nx = tf.placeholder(tf.float32, shape = (None,2))\nw1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))\nw2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))\n\n# 定义前向传播过程\na = tf.matmul(x, w1)\ny = tf.matmul(a, w2)\n\n\n# 用会话计算结果\nwith tf.compat.v1.Session() as sess:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n print(\"rusult is : \", sess.run(y, feed_dict=({x: [[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]})))\n \n print(\"w1: \", sess.run(w1))\n print(\"w2: \", sess.run(w2))\n","sub_path":"tensorflow_example/tensorflow_forward_03.py","file_name":"tensorflow_forward_03.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381420218","text":"#!/usr/bin/python\n#-*-coding:utf-8-*-\n\nimport os\nimport ipdb\n\n#db = ipdb.Reader(os.path.abspath('./') + '\\\\utils\\mydatatest.ipdb')\n\ndef ip2location(ip, type='city'):\n #db = ipdb.Reader('ipiptest.ipdb')\n db = ipdb.Reader(os.path.abspath('./') + '\\\\utils\\ipiptest.ipdb')\n try:\n if type == 'city':\n return(db.find_map(ip)['city_name'])\n elif type == 'province':\n return(db.find_map(ip)['region_name'])\n elif type == 'province,city':\n return(db.find_map(ip)['region_name'] + ',' + db.find_map(ip)['city_name'])\n except Exception as e:\n #print(e)\n return('Unknown')\n #print(db.find(\"202.205.73.249\"))\n #print(db.find_map(\"202.205.73.249\")['city_name'])\n\n#info = db.find_info(\"202.205.73.249\")\n#print(info.country_name, info.region_name, info.city_name, info.owner_domain, info.isp_domain, info.latitude, info.longitude, info.timezone, info.utc_offset)\n\nif __name__ == '__main__':\n #geo_ip.1.py\n # print(ip2location('202.205.73.249'))\n print('Testing: ' + ip2location(\"125.224.69.223\", 'province,city'))","sub_path":"utils/geo_ipip.py","file_name":"geo_ipip.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80291106","text":"# Input: 'This is a pen, This is an apple. Applepen.'\n# Output: ('p', 6)\nfrom collections import Counter\nimport operator\nfrom typing import Tuple\n\n\ndef count_chars_v1(strings: str) -> Tuple[str, int]:\n strings = strings.lower()\n # l = []\n # for char in strings:\n # if not char.isspace():\n # l.append((char, strings.count(char)))\n l = [(char, strings.count(char)) for char in strings if not char.isspace()]\n return max(l, key=operator.itemgetter(1))\n\n\ndef count_chars_v2(strings: str) -> Tuple[str, int]:\n strings = strings.lower()\n d = {}\n # d = dict{}\n for char in strings:\n if not char.isspace():\n d[char] = d.get(char, 0) + 1\n # print(d)\n max_key = max(d, key=d.get)\n return max_key, d[max_key]\n\n\ndef count_chars_v3(strings: str) -> Tuple[str, int]:\n strings = strings.lower()\n d = Counter()\n for char in strings:\n if not char.isspace():\n d[char] += 1\n max_key = max(d, key=d.get)\n return max_key, d[max_key]\n\n\nif __name__ == '__main__':\n words = 'This is a pen, This is an apple. Applepen.'\n print(count_chars_v3(words))\n\n\n\n\n\n\n","sub_path":"42_count_quiz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522644337","text":"import socket\nfrom socket import socket as Socket\nimport argparse\nimport sys\nimport threading\n\ndef listen(connection_socket, addr):\n request = connection_socket.recv(1024).decode('ascii')\n reply = http_handle(request)\n connection_socket.send(reply.encode('ascii'))\n connection_socket.close()\n\n\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', '-p', default=2080, type=int, help='Port to use')\n args = parser.parse_args()\n\n # Create the server socket (to handle tcp requests using ipv4), make sure\n # it is always closed by using with statement.\n with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:\n\n # The socket stays connected even after this script ends. So in order\n # to allow the immediate reuse of the socket (so that we can kill and\n # re-run the server while debugging) we set the following option. This\n # is potentially dangerous in real code: in rare cases you may get junk\n # data arriving at the socket.\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n server_socket.bind(('127.0.0.1', args.port))\n server_socket.listen(1)\n\n print(\"Server is ready\", file=sys.stderr)\n\n while True:\n connection_socket, addr = server_socket.accept()\n threading.Thread(target=listen, args=(connection_socket, addr)).start()\n\ndef http_handle(request_string):\n \"\"\"Given a http request return a response\n Both request and response are unicode strings with platform standard\n line endings.\n \"\"\"\n filename = request_string.split()[1]\n filename = \"index.html\" if filename == '/' else filename[1:]\n\n print(\"filename {}\".format(filename))\n\n with open(filename) as f:\n output_data = f.read()\n return output_data\n\nif __name__ == '__main__':\n main()","sub_path":"python/http/threaded-web-server.py","file_name":"threaded-web-server.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487867518","text":"#\n# Define data structures\n#\n\nclass Graph:\n def __init__(self):\n self.vertices = {}\n # self.vertices = {\n # 3: {1,2},\n # 6: {3,5},\n # 7: {5},\n # 5: {4},\n # 8: {4,11},\n # 9: {8},\n # 1: {10},\n # }\n \n def add_vertex(self, parent, child):\n if child not in self.vertices:\n self.vertices[child] = set()\n\n self.vertices[child].add(parent)\n\n#\n# Define search utility\n#\n\ndef earliest_ancestor(ancestors, starting_node):\n graph = Graph()\n\n for relationship in ancestors:\n graph.add_vertex(relationship[0], relationship[1])\n\n # print(f\"graph.vertices {graph.vertices}\")\n #=> {3: {1, 2}, 6: {3, 5}, 7: {5}, 5: {4}, 8: {11, 4}, 9: {8}, 1: {10}}\n\n if starting_node not in graph.vertices:\n return -1\n\n current_vertex = starting_node\n next_vertex = min(graph.vertices[current_vertex])\n while next_vertex in graph.vertices:\n current_vertex = next_vertex\n next_vertex = min(graph.vertices[current_vertex])\n \n return next_vertex\n\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635726774","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfund = pd.read_csv('fund_20190223.csv', encoding='GBK',dtype={'Net_value': np.float64,\n 'Gross_value': np.float64,\n 'Day_rate': np.float64,\n 'One_week': np.float64,\n 'One_month': np.float64,\n 'Three_month': np.float64,\n 'Six_month': np.float64,\n 'One_year': np.float64,\n 'Two_year': np.float64,\n 'Three_year': np.float64,\n 'From_this_y': np.float64,\n 'From_establish': np.float64},\n parse_dates=['Establish_date'])\n\nfund['Establish_rate'] = fund['From_establish'] / 100\n\nnet = fund.sort_values(by='Net_value', ascending=False)\n\ngross = fund.sort_values(by='Gross_value', ascending=False)\n\nprofit = fund.sort_values(by='Establish_rate', ascending=False)\n\ntop_20_net = net.iloc[0:20]\n\ntop_20_gross = gross.iloc[0:20]\n\ntop_20_profit = profit.iloc[0:20]\n\n# Visualization Part\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\nsns.barplot(x='Net_value', y='Name', data=top_20_net)\n\nsns.barplot(x='Gross_value', y='Name', data=top_20_gross)\n\nsns.barplot(x='Establish_rate', y='Name', data=top_20_profit)\n\n# sns.scatterplot(x='Net_value', y='Name', data=fund)\n","sub_path":"Visualization_fund.py","file_name":"Visualization_fund.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369375999","text":"import collections\n# Definition for binary tree with next pointer.\n\n\nclass TreeLinkNode:\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n self.next = None\n\n\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n\n def connct(self, node):\n tail = dummy = TreeLinkNode(0)\n while node:\n tail.next = node.left\n if tail.next: # if exist, move on.\n tail = tail.next\n tail.next = node.right # point\n if tail.next:\n tail = tail.next\n node = node.next\n if not node:\n tail = dummy # next level\n node = dummy.next\n\n def connect_2(self, root):\n if not root:\n return\n queue, level = collections.deque([root]), collections.deque()\n while queue:\n node = queue.popleft()\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n node.next = queue[0] if queue else None\n if not queue and level:\n queue, level = level, queue\n","sub_path":"LeetCode/117_Populating_Next_Right_Pointers_in_Each_Node_II.py","file_name":"117_Populating_Next_Right_Pointers_in_Each_Node_II.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240920828","text":"# Implementar la función es_palindromo(), que devuelva un booleano en base a\n# si palabra se lee igual de corrido como al revés.\n\n\n# Ejemplos: arenera, radar, ojo, oso, salas.\n# Resolver sin utilizar loops (for/while), sino con slicing.\ndef es_palindromo(palabra):\n rever = palabra[::-1]\n if palabra == rever:\n return True\n return False\n\nassert (es_palindromo('eliana')) == False\nassert (es_palindromo('arenera')) == True\n\n","sub_path":"practico_01/ejercicio-09.py","file_name":"ejercicio-09.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"557377821","text":"import numpy as np\nfrom itertools import combinations\n\ndef matrixGeneration(nodeNumber, s):\n myList = s.split()\n numRows = nodeNumber - 1\n numCols = nodeNumber\n myArray = np.empty((numRows, numCols))\n myArray[:] = np.nan\n shift = 0\n index = 0\n for i in range(numRows):\n shift += 1\n for j in range(shift, numCols):\n myArray[i, j] = myList[index]\n index += 1\n return myArray\n\ndef removeDuplicate(myList):\n finalList = []\n for element in myList:\n if element not in finalList:\n finalList.append(element)\n return finalList\n\ndef getAllEdges(nodeNumber):\n nodeList = []\n for i in range(1, nodeNumber+1):\n nodeList.append(i)\n comb = combinations(nodeList, 2)\n edgeList = []\n for i in list(comb):\n edgeList.append(i)\n return edgeList","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223799075","text":"from cement.utils.shell import Prompt\n\nclass GenericSelectionPrompt(Prompt):\n class Meta:\n numbered = True\n default = 'no'\n clear = False\n\n def read(self):\n return self.input\n\nclass GenericInputPrompt(Prompt):\n class Meta:\n clear = False\n\n def read(self):\n return self.input\n\ndef fetch_info_prompt(type_text, options):\n type = GenericSelectionPrompt(text=\"Select %s type\" %type_text,\n options=options, clear=True).read()\n url = GenericInputPrompt(text=\"Provide %s URL: \" %type_text).read()\n token = GenericInputPrompt(text=\"Enter %s access token: \" %type_text).read()\n\n return {\"type\" : type,\n \"url\" : url,\n \"token\" : token\n }","sub_path":"fusion/src/cli/user_prompts.py","file_name":"user_prompts.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"480139026","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 25 06:08:39 2022\n\n@author: jced0001\n\"\"\"\n\nfrom Panel import Panel\nimport customtkinter as ctk\nimport numpy as np\nimport numpy.linalg as npl\n\nclass BandStructure3D(Panel):\n numBands = 1\n ###########################################################################\n # Constructor\n ###########################################################################\n def __init__(self, master, width, height, dpi, mainPanel):\n super().__init__(master, width, height, dpi, mainPanel=mainPanel,length=8,btnSize=2,plotType='3d')\n self.buttons()\n \n ###########################################################################\n # Panel\n ###########################################################################\n def buttons(self):\n self.btn = {\n \"Add\": ctk.CTkButton(self.master, text=\"Add band\", command=self.addBand),\n \"Remove\": ctk.CTkButton(self.master, text=\"Remove band\", command=self.removeBand),\n \"PNG\": ctk.CTkButton(self.master, text=\"Exp PNG\", command=super().exportPNG), # Export the canvas to png\n \"Close\": ctk.CTkButton(self.master, text=\"Close\", command=self.destroy)\n }\n \n def buttonHelp(self):\n helpStr = \"Close this panel\"\n self.btn['Close'].bind('',lambda event, s=helpStr: self.updateHelpLabel(s))\n \n helpStr = \"Add a band to the plot\"\n self.btn['Add'].bind('',lambda event, s=helpStr: self.updateHelpLabel(s))\n \n helpStr = \"Remove a band from the plot\"\n self.btn['Remove'].bind('',lambda event, s=helpStr: self.updateHelpLabel(s))\n \n helpStr = \"Export the main panel plot as a png\"\n self.btn['PNG'].bind('',lambda event, s=helpStr: self.updateHelpLabel(s))\n \n ###########################################################################\n # Update and Plotting\n ###########################################################################\n def update(self):\n if(not self.active): return\n \n self.ax.cla() # Clear the axis\n self.ax.set_position([0.09, 0.07, 0.87, 0.9]) # Make it take up the whole canvas\n self.showBandStructure()\n self.canvas.figure = self.fig # Assign the figure to the canvas\n self.canvas.draw()\n \n def showBandStructure(self):\n if(self.mainPanel.sim and self.mainPanel.sim.valid):\n a = self.mainPanel.sim.a\n lim = np.pi/npl.norm(a,axis=1)\n k1,k2 = self.mainPanel.sim.K\n K1,K2 = np.meshgrid(k1,k2)\n for b in range(self.numBands):\n Ekb = self.mainPanel.sim.Ek[b]\n self.ax.plot_surface(K1/lim[0], K2/lim[1], Ekb, linewidth=0, antialiased=True)\n self.ax.set_xlim([-1.5,1.5])\n self.ax.set_ylim([-1.5,1.5])\n self.ax.view_init(elev=10., azim=45)\n \n ###########################################################################\n # Misc\n ###########################################################################\n def load(self):\n pass\n \n def addBand(self):\n if(self.mainPanel.sim and self.mainPanel.sim.valid):\n self.numBands += 1\n self.update()\n \n def removeBand(self):\n if(self.numBands == 1): return\n if(self.mainPanel.sim and self.mainPanel.sim.valid):\n self.numBands -= 1\n self.update()\n ","sub_path":"Central-Equation-Solver/BandStructure3D.py","file_name":"BandStructure3D.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499745046","text":"class Queue:\r\n def __init__(self): \r\n self.s1 = []\r\n self.s2 = []\r\n\r\n def enQueue(self,data): #fuction is for inserting elements into the Queue in FIFO manner\r\n while len(self.s1)!=0:\r\n self.s2.append(self.s1[-1])\r\n self.s1.pop()\r\n self.s1.append(data)\r\n while len(self.s2)!=0:\r\n self.s1.append(self.s2[-1])\r\n self.s2.pop()\r\n\r\n print(\"%d appended\"%data)\r\n\r\n def deQueue(self): #fuction is for deleting elements from the Queue in FIFO manner\r\n if len(self.s1) == 0:\r\n print(\"Q is Empty\")\r\n\r\n x = self.s1[-1]\r\n self.s1.pop()\r\n return x\r\n\r\nob = Queue()\r\nob.enQueue(12)\r\nob.enQueue(17)\r\nprint(ob.deQueue())\r\n","sub_path":"queueusingstack.py","file_name":"queueusingstack.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47012428","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/08/11\n# @Author : kingsley kuang\n# @Site : https://github.com/kingsley-gl/planbar.git\n# @File : Stirrup.py 箍筋文件\n# @Software: \n# @Function: \n\n\n\n\ndef steel_modify(total_length,diameter,distance,head_cover,end_cover):\n '''\n 判断顶端根数修正函数\n '''\n end_pos = total_length - end_cover\n last_pos = int((total_length - head_cover - end_cover - diameter) / distance) * distance + head_cover\n print('end_pos',end_pos)\n print('last_pos',last_pos)\n if end_pos - last_pos < distance + diameter and end_pos - last_pos > distance / 2:\n return True\n else:\n return False\n","sub_path":"内梅切克构件组/墙/JunheModels/util/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"409455962","text":"\nfrom django import forms\n\nfrom .models import TaskModel, CommentModel\n\n\nclass CreateTaskForm(forms.ModelForm):\n\n class Meta:\n model = TaskModel\n fields = [\n 'title',\n 'text',\n 'image',\n 'deadline_at',\n 'slug',\n 'people',\n 'active'\n ]\n widgets = {\n 'title': forms.TextInput(attrs={\n 'placeholder': 'Please add a title. Max: 65 characters',\n 'size': 65}),\n 'text': forms.Textarea(attrs={\n 'cols': 80,\n 'rows': 10,\n 'placeholder': 'Starting typing your task...'}),\n 'slug': forms.TextInput(attrs={\n 'placeholder': 'Please add a slug',\n 'size': 65}),\n 'deadline_at': forms.DateInput(format='%m/%d/%Y', attrs={\n 'placeholder':'Input date mm/dd/yyyy'}),\n 'people': forms.CheckboxSelectMultiple,\n 'active': forms.RadioSelect}\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = CommentModel\n fields = ['text']\n widgets = {\n 'text': forms.TextInput(attrs={\n 'placeholder': 'Please enter your comment.'}),\n }\n","sub_path":"manager/project/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"336861291","text":"from PIL import Image\nimport numpy as np\nimport os\nimport cv2\n\n\ndef main():\n \"\"\"\n Normalizes an Image and saves it as well as its individual channels\n (In this case, the channels are RGB)\n :return: None\n \"\"\"\n # Define path:\n MYPATH = os.getcwd()\n print(MYPATH)\n\n filenames = os.listdir(MYPATH + '/img_orig')\n for file in filenames:\n print(file)\n\n # read-in files\n img = cv2.imread(MYPATH + '/img_orig/' + file)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = np.asarray(img, dtype=np.uint8)\n\n # Cut off watermark\n img = img[:2104, :, :]\n\n new_comp = img\n for i in range(3):\n print(i)\n new_img = cv2.GaussianBlur(img[:, :, i], (31, 31), sigmaX=0)\n new_img = normalize(new_img)\n\n # Combine normalized channels to complete image\n new_comp[:, :, i] = new_img\n\n # save image of each channel\n newIm = Image.fromarray(new_img)\n new_fname = MYPATH + '/' + 'img_norm' + '/' + str(i + 1) + '_norm_' + file\n newIm.save(new_fname)\n\n # Save complete image\n newIm_comp = Image.fromarray(new_comp)\n comp_fname = MYPATH + '/img_norm/0_norm_' + file\n newIm_comp.save(comp_fname)\n\n\ndef normalize(img):\n \"\"\"\n Normalizes an Image to the range of 0-255.\n :param img: a 2D-array\n :return: a 2D-array\n \"\"\"\n img_min = np.min(img)\n img_max = np.max(img)\n print(img_min, img_max)\n img_new = ((img-img_min) * (1/(img_max - img_min))) ** 2 * 255\n return np.asarray(img_new, dtype=np.uint8)\n\n\nmain()\n","sub_path":"normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561547470","text":"from sklearn.datasets import load_iris\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\ndef iris_predicting():\r\n \"\"\"\r\n 鸢尾花预测\r\n :return:\r\n \"\"\"\r\n # 获取数据\r\n data = load_iris()\r\n\r\n feature_data = data.data\r\n target_data = data.target\r\n\r\n # 划分数据集 ,特征训练,特征测试,目标训练,目标测试\r\n feature_train, feature_test, target_train, target_test = train_test_split(feature_data, target_data, test_size=0.25)\r\n\r\n # 特征工程,标准化\r\n std = StandardScaler()\r\n feature_train = std.fit_transform(feature_train)\r\n feature_test = std.transform(feature_test)\r\n\r\n # knn, K邻近\r\n knn = KNeighborsClassifier()\r\n knn.fit(feature_train, target_train) # fit 输入训练数据\r\n predict = knn.predict(feature_test)\r\n\r\n # print(\"输入测试特征值,获取预测结果:\", predict)\r\n\r\n # 非标准化:0.8947368421052632 多次运行出现不同正确率结果: 这是因为划分 训练集 与 测试集 时每次划分数据不一样导致\r\n # 标准化:0.9736842105263158\r\n # print(\"预测结果的准确率\", knn.score(feature_test, target_test))\r\n\r\n accuracy = knn.score(feature_test, target_test)\r\n\r\n return accuracy\r\n\r\n\r\nif __name__ == '__main__':\r\n acc_lsit = []\r\n for i in range(20):\r\n acc = iris_predicting()\r\n acc_lsit.append(acc)\r\n\r\n acc_df = pd.Series(acc_lsit)\r\n print(acc_df)\r\n\r\n x = acc_df.index\r\n y = acc_df.values\r\n\r\n plt.figure(figsize=(20, 8), dpi=60)\r\n\r\n plt.plot(x, y)\r\n\r\n plt.xticks(range(len(x)), x)\r\n plt.yticks([0.01*i for i in range(80, 100)][::2])\r\n\r\n plt.show()\r\n\r\n\r\n\r\n","sub_path":"Machine learning/model/KNN/iris_predict.py","file_name":"iris_predict.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574818744","text":"from datetime import datetime\nimport discord\nimport math\nimport typing\n\nfrom discord.ext import commands\n\nfrom cogs.boards import MockPlayer\nfrom cogs.utils.db_objects import SlimDummyBoardConfig\nfrom cogs.utils.paginator import (\n SeasonStatsPaginator, StatsAttacksPaginator, StatsDefensesPaginator, StatsGainsPaginator, StatsDonorsPaginator\n)\nfrom cogs.utils.formatters import CLYTable, get_render_type\nfrom cogs.utils.cache import cache, Strategy\nfrom cogs.utils.emoji_lookup import misc\n\nmock = MockPlayer('Unknown', 'Unknown')\n\n\nclass SeasonStats(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @cache(strategy=Strategy.lru)\n async def get_board_fmt(self, guild_id, season_id, board_type):\n board_config = await self.bot.utils.get_board_configs(guild_id, board_type)\n if not board_config:\n board_config = SlimDummyBoardConfig(board_type, 2, f\"{board_type.capitalize()}Board\", None, 'donations' if board_type == \"donation\" else \"trophies\")\n else:\n board_config = board_config[0]\n\n clans = await self.bot.get_clans(guild_id)\n\n players = []\n for n in clans:\n players.extend(p for p in n.itermembers)\n\n top_players = await self.bot.donationboard.get_top_players(\n players, board_type, board_config.sort_by, False, season_id=season_id\n )\n\n if not top_players:\n e = discord.Embed(colour=self.bot.colour,\n title='No Data Found.')\n return [e]\n\n players = {n.tag: n for n in players if n.tag in set(x['player_tag'] for x in top_players)}\n\n message_count = math.ceil(len(top_players) / 20)\n\n embeds = []\n for i in range(message_count):\n player_data = top_players[i*20:(i+1)*20]\n table = CLYTable()\n\n for x, y in enumerate(player_data):\n index = i*20 + x\n if board_config.render == 2:\n table.add_row([index,\n y[1],\n players.get(y['player_tag'], mock).name])\n else:\n table.add_row([index,\n y[1],\n y[2],\n players.get(y['player_tag'], mock).name])\n\n render = get_render_type(board_config, table)\n fmt = render()\n\n e = discord.Embed(colour=self.bot.donationboard.get_colour(board_type, False),\n description=fmt,\n timestamp=datetime.utcnow()\n )\n e.set_author(name=board_config.title,\n icon_url=board_config.icon_url or 'https://cdn.discordapp.com/'\n 'emojis/592028799768592405.png?v=1')\n e.set_footer(\n text=f'Historical {board_type.capitalize()}Board; Season {season_id} - Page {i+1}/{message_count}'\n )\n embeds.append(e)\n\n return embeds\n\n @commands.group(invoke_without_subcommand=True)\n async def seasonstats(self, ctx):\n \"\"\"[Group] command to manage historical stats for seasons past.\"\"\"\n if ctx.invoked_subcommand is None:\n await ctx.send_help(ctx.command)\n\n @seasonstats.command(name='donationboard')\n async def seasonstats_donationboard(self, ctx, season: typing.Optional[int] = None):\n \"\"\"Get historical donationoard stats.\n\n *Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+seasonstats donationboard`\n :white_check_mark: `+seasonstats donationboard 2`\n \"\"\"\n embeds = await self.get_board_fmt(ctx.guild.id, season or (await self.bot.seasonconfig.get_season_id()) - 1,\n 'donation')\n p = SeasonStatsPaginator(ctx, entries=embeds)\n await p.paginate()\n\n @seasonstats.command(name='trophyboard')\n async def seasonstats_trophyboard(self, ctx, season: int = None):\n \"\"\"Get historical trophyboard stats.\n\n *Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+seasonstats trophyboard`\n :white_check_mark: `+seasonstats trophyboard 2`\n \"\"\"\n embeds = await self.get_board_fmt(ctx.guild.id, season or (await self.bot.seasonconfig.get_season_id()) - 1,\n 'trophy')\n p = SeasonStatsPaginator(ctx, entries=embeds)\n await p.paginate()\n\n @seasonstats.command(name='attacks')\n async def seasonstats_attacks(self, ctx, season: typing.Optional[int] = None):\n \"\"\"Get attack wins for all clans.\n\n **Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+season stats attacks`\n :white_check_mark: `+season stats attacks 2`\n \"\"\"\n season = season or await self.bot.seasonconfig.get_season_id() - 1\n\n clans = await ctx.get_clans()\n query = \"\"\"SELECT player_tag, ABS(end_attacks - start_attacks) as attacks, trophies \n FROM players \n WHERE player_tag = ANY($1::TEXT[])\n AND season_id = $2\n ORDER BY attacks DESC\n NULLS LAST\n \"\"\"\n\n players = []\n for clan in clans:\n players.extend((n.tag for n in clan.itermembers))\n\n fetch = await ctx.db.fetch(query, players, season)\n if not fetch:\n return await ctx.send(\"No data found. Sorry.\")\n\n title = f\"Attack wins for Season {season}\"\n key = f\"**Key:**\\n{misc['attack']} - Attacks\\n{misc['trophygold']} - Trophies\"\n\n p = StatsAttacksPaginator(ctx, fetch, title, key=key, page_count=math.ceil(len(fetch) / 20))\n await p.paginate()\n\n @seasonstats.command(name='defenses', aliases=['defense', 'defences', 'defence'])\n async def seasonstats_defenses(self, ctx, season: typing.Optional[int] = None):\n \"\"\"Get defense wins for all clans.\n\n **Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+season stats defenses`\n :white_check_mark: `+season stats defenses 3`\n \"\"\"\n season = season or await self.bot.seasonconfig.get_season_id() - 1\n clans = await ctx.get_clans()\n query = \"\"\"SELECT player_tag, end_defenses - start_defenses as defenses, trophies \n FROM players \n WHERE player_tag = ANY($1::TEXT[])\n AND season_id = $2\n ORDER BY defenses DESC\n NULLS LAST\n \"\"\"\n\n players = []\n for clan in clans:\n players.extend((n.tag for n in clan.itermembers))\n\n fetch = await ctx.db.fetch(query, players, season)\n if not fetch:\n return await ctx.send(\"No data found. Sorry.\")\n\n title = f\"Defense wins for Season {season}\"\n key = f\"**Key:**\\n{misc['defense']} - Defenses\\n{misc['trophygold']} - Trophies\"\n\n p = StatsDefensesPaginator(ctx, fetch, title, key=key, page_count=math.ceil(len(fetch) / 20))\n await p.paginate()\n\n @seasonstats.command(name='gains', aliases=['trophies'])\n async def seasonstats_gains(self, ctx, season: typing.Optional[int] = None):\n \"\"\"Get trophy gains for all clans.\n\n **Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+season stats gains`\n :white_check_mark: `+season stats gains 1`\n \"\"\"\n\n season = season or await self.bot.seasonconfig.get_season_id() - 1\n clans = await ctx.get_clans()\n query = \"\"\"SELECT player_tag, trophies - start_trophies as gain, trophies \n FROM players \n WHERE player_tag = ANY($1::TEXT[])\n AND season_id = $2\n ORDER BY gain DESC\n NULLS LAST\n \"\"\"\n\n players = []\n for clan in clans:\n players.extend((n.tag for n in clan.itermembers))\n\n fetch = await ctx.db.fetch(query, players, season)\n if not fetch:\n return await ctx.send(\"No data found. Sorry.\")\n\n title = f\"Trophy Gains for Season {season}\"\n key = f\"**Key:**\\n{misc['trophygreen']} - Trophy Gain\\n{misc['trophygold']} - Total Trophies\"\n\n p = StatsGainsPaginator(ctx, fetch, title, key=key, page_count=math.ceil(len(fetch) / 20))\n await p.paginate()\n\n @seasonstats.command(name='donors', aliases=['donations', 'donates', 'donation'])\n async def seasonstats_donors(self, ctx, season: typing.Optional[int] = None):\n \"\"\"Get donations for all clans.\n\n **Parameters**\n :key: Season ID (optional - defaults to last season)\n\n **Example**\n :white_check_mark: `+season stats donors`\n :white_check_mark: `+season stats donations 4`\n \"\"\"\n\n season = season or await self.bot.seasonconfig.get_season_id() - 1\n clans = await ctx.get_clans()\n query = \"\"\"SELECT player_tag, (end_friend_in_need + end_sharing_is_caring) - (start_friend_in_need + start_sharing_is_caring) as donations\n FROM players \n WHERE player_tag = ANY($1::TEXT[])\n AND season_id = $2\n ORDER BY donations DESC\n NULLS LAST \n \"\"\"\n\n players = []\n for clan in clans:\n players.extend((n.tag for n in clan.itermembers))\n\n fetch = await ctx.db.fetch(query, players, season)\n if not fetch:\n return await ctx.send(\"No data found. Sorry.\")\n\n title = f\"Donations for Season {season}\"\n\n p = StatsDonorsPaginator(ctx, fetch, title, page_count=math.ceil(len(fetch) / 20))\n await p.paginate()\n\n\ndef setup(bot):\n bot.add_cog(SeasonStats(bot))\n","sub_path":"cogs/stats/seasonstats.py","file_name":"seasonstats.py","file_ext":"py","file_size_in_byte":10080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"322797246","text":"\"\"\" Run it from the terminal. Takes two arguments: input file and output file names. The output\nfile is a record of the number of times each character occurs in the text of the input file\"\"\"\n\nfrom sys import argv\n\ninput_file = argv[1]\noutput_file = argv[2] \n\ndef display(i):\n if i == 10: return 'LF'\n if i == 13: return 'CR'\n if i == 32: return 'SPACE'\n return chr(i)\n\ninfile = open(input_file, 'r')\ntext = infile.read()\ninfile.close()\n\ncounts = 128 * [0]\n\nfor letter in text:\n counts[ord(letter)] += 1\n\noutfile = open(output_file, 'w')\noutfile.write(\"%-12s%s\\n\" % (\"Character\", \"Count\"))\noutfile.write(\"=================\\n\")\n\nfor i in range(len(counts)):\n if counts[i]:\n outfile.write(\"%-12s%d\\n\" % (display(i), counts[i]))\n\noutfile.close()\n","sub_path":"countletter_sys.py","file_name":"countletter_sys.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489125553","text":"import random\ndef LCM(l): # 최소공배수\n myl = l.copy()\n for i in range(len(l) - 1):\n lcm = myl[i] * myl[i + 1] / GCD(myl[i:i + 2])\n myl[i + 1] = lcm\n return int(lcm)\ndef GCD(l): # 최대공약수 \n for k in range(min(l), 0, -1):\n b = 0\n for j in range(len(l)):\n if l[j] % k == 0:\n b += 1\n if b == len(l):\n return k\ndef main():\n a = []\n for i in range(10):\n a.append(random.randint(1, 100)) # 1에서 100 중 정수 하나\n print(a)\n lcm_value = LCM(a)\n gcd_value = GCD(a)\n print('최소공배수: ', lcm_value, ' 최대공약수: ', gcd_value)\nif __name__ == '__main__':\n main()","sub_path":"ai/LCM_GCD.py","file_name":"LCM_GCD.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634539674","text":"'''Checks speed and accuracy of various integration methods implemented\nby Galpy. On Tim's macbook, 4k_6 is fastest (6 times that of odeint, the\nprevious default) and has position errors of 1e-7 and velocity errors of\n3e-9 km/s when calculating the motion of the LSR after 100 Myr'''\nimport numpy as np\nimport sys\nimport time\n\nif sys.version[0] == '2':\n timer = time.clock\nelif sys.version[0] == '3':\n timer = time.perf_counter\n\nsys.path.insert(0, '..')\nfrom chronostar.traceorbit import trace_cartesian_orbit\n\ninteg_methods = [\n 'odeint',\n 'symplec4_c',\n 'rk4_c',\n 'dopr54_c',\n 'rk6_c',\n]\n\n\nxyzuvw_start = [0.,0.,25.,0.,0.,0.]\nmax_time = 1000\norbit_times = np.linspace(0,max_time,100)\n\nniters = 100\n\nprint('Integrating up to {} Myr'.format(max_time))\nprint('Iterating {} times'.format(niters))\n\nprint('----------- Check accuracy ----------')\nxyzuvw_lsr = [0.,0.,0.,0.,0.,0.]\ntraceback_age = 100. #Myr\n\nfor method in integ_methods:\n print('_____ Using {} _____'.format(method))\n xyzuvw_final = trace_cartesian_orbit(xyzuvw_lsr, traceback_age,\n single_age=True,\n method=method)\n diff = xyzuvw_final - xyzuvw_lsr\n pos_error = np.sqrt(np.sum(np.square(diff[:3])))\n vel_error = np.sqrt(np.sum(np.square(diff[3:])))\n print('Position error: {:.3} pc'.format(pos_error))\n print('Velocity error: {:.3} km/s'.format(vel_error))\n\n print('')\n\n\n\nprint('----------- Check timings ----------')\nfor method in integ_methods:\n print('_____ Using {} _____'.format(method))\n duration_times = []\n for i in range(niters):\n start = timer()\n\n trace_cartesian_orbit(xyzuvw_start, orbit_times, single_age=False,\n method=method)\n\n end = timer()\n duration_times.append(end-start)\n print('Average time taken: {:.1f} ms'.format(1000*np.mean(duration_times)))\n print('Best time: {:.1f} ms'.format(1000*np.min(duration_times)))\n print('Worst time: {:.1f} ms'.format(1000*np.max(duration_times)))\n print('')\n\n\n\n\n\n\n","sub_path":"benchmarks/test_galpy_integrator_speed.py","file_name":"test_galpy_integrator_speed.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"428877270","text":"#!/usr/bin/env python3\n# Copyright (C) 2017 Qrama\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 published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n# pylint: disable=c0111,c0103,c0301,c0412\nimport time\nimport stomp\nimport json\nimport feedparser\n\nendpoint = \"https://stackexchange.com/feeds/tagsets/303141/favorite-tags?sort=active\"\n\ndef main():\n recent_id = '0'\n while True:\n d = feedparser.parse(endpoint)\n if recent_id == d.entries[0].id:\n time.sleep(600)\n else:\n recent_id = d.entries[0].id\n conn = stomp.Connection([('{{host}}', {{port}})])\n conn.start()\n conn.connect()\n for entry in d.entries:\n s=json.dumps(entry)\n conn.send(destination='/topic/{{topic}}', body=s)\n conn.disconnect()\n time.sleep(600)\n\nif __name__ == '__main__':\n main()\n","sub_path":"xenial/data-source/templates/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"550816522","text":"from Dataset import Dataset\nimport os\nimport numpy as np\nimport scipy.misc\nimport math\nfrom PIL import Image\nimport json\nfrom lxml import etree\nimport random\nfrom shutil import copyfile\nfrom functools import reduce\n\n# Visualising\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as plticker\nfrom shapely.geometry.polygon import Polygon\nimport xml.etree.ElementTree as ET\n\n\nclass YOLO_Dataset(Dataset):\n \"\"\"\n The 'YOLO_Dataset' class inherits from the parent 'Dataset' class and provides\n functionality to convert the images and annotations into the format required\n by the YOLO architecture (implemented as in Darkflow link: https://github.com/thtrieu/darkflow)\n\n An object of 'YOLO_Dataset' wil provide the following functionality:\n\n\n\n \"\"\"\n\n def __init__(self, data_path, train_val_test=(0.8, 0.1, 0.1)):\n \"\"\"\n Initialises a 'YOLO_Dataset' object by calling the superclass initialiser.\n\n The difference between a YOLO_Dataset object and a Dataset object is the annotation.\n The YOLO_Dataset object will therefore override the self.annotations_path and\n self.annotation_list attributes such that the building labels are in XML format.\n \"\"\"\n assert (train_val_test[0] + train_val_test[1] + train_val_test[2]\n ) == 1, 'Train, val and test percentages should add to 1'\n assert train_val_test[0] > 0 and train_val_test[1] > 0 and train_val_test[\n 2] > 0, 'Train, val and test percentages should be non-negative'\n\n Dataset.__init__(self, data_path)\n\n self.train_val_test = train_val_test\n self.train_path = self.data_path + '/yolo/train'\n self.val_path = self.data_path + '/yolo/val'\n self.test_path = self.data_path + '/yolo/test'\n\n if not os.path.isdir(self.data_path + '/yolo'):\n print(f\"Creating directory to store YOLO formatted dataset.\")\n os.mkdir(self.data_path + '/yolo')\n\n # Create train, validation, test directories, each with an images and annotations\n # sub-directory\n for directory in [self.train_path, self.val_path, self.test_path]:\n if not os.path.isdir(directory):\n os.mkdir(directory)\n\n if not os.path.isdir(directory + '/images'):\n os.mkdir(directory + '/images')\n\n if not os.path.isdir(directory + '/annotations'):\n os.mkdir(directory + '/annotations')\n\n def build_dataset(self):\n \"\"\"\n Helper method only called in build_dataset that splits data into test\n train and validation sets.\n \"\"\"\n data = list(zip(self.img_list, self.annotation_list))\n random.shuffle(data)\n shuffled_img, shuffled_annotations = zip(*data)\n\n train, val, test = self.train_val_test\n\n # index counter i\n i = 0\n while i < len(shuffled_img):\n if i < math.floor(train*len(shuffled_img)):\n # Add to train folder\n copyfile(\n f\"{self.images_path}/{shuffled_img[i]}\", f\"{self.train_path}/images/{i}.jpg\")\n self.json_to_xml(\n f\"{self.annotations_path}/{shuffled_annotations[i]}\", f\"{self.train_path}/annotations/{i}.xml\", f\"{i}.jpg\")\n elif i < math.floor((train+val)*len(shuffled_img)):\n # Add to val folder\n ind = i - math.floor((train)*len(shuffled_img))\n copyfile(\n f\"{self.images_path}/{shuffled_img[i]}\", f\"{self.val_path}/images/{ind}.jpg\")\n self.json_to_xml(\n f\"{self.annotations_path}/{shuffled_annotations[i]}\", f\"{self.val_path}/annotations/{ind}.xml\", f\"{ind}.jpg\")\n else:\n # Add to test folder\n ind = i - math.floor((train+val)*len(shuffled_img))\n copyfile(\n f\"{self.images_path}/{shuffled_img[i]}\", f\"{self.test_path}/images/{ind}.jpg\")\n self.json_to_xml(\n f\"{self.annotations_path}/{shuffled_annotations[i]}\", f\"{self.test_path}/annotations/{ind}.xml\", f\"{ind}.jpg\")\n # increment index counter\n i += 1\n\n def json_to_xml(self, path_to_file, path_to_dest, img_name):\n \"\"\"\n Helper method only called in split_data that takes a json file at\n path_to_file and writes a corresponding xml at path_to_dest.\n \"\"\"\n # Im_size: [width, height, depth] ??? should be squares anyways\n with open(path_to_file) as f:\n try:\n buildings_dict = self.format_coords(json.load(f))\n except:\n buildings_dict = {}\n\n # begin creating annotation\n annotation = etree.Element('annotation')\n\n # Add to xml etree\n filename = etree.Element('filename')\n filename.text = img_name\n\n # Image size\n size = etree.Element('size')\n im_size = self.get_img_size()\n # nested elements in size\n width = etree.Element('width')\n height = etree.Element('height')\n depth = etree.Element('depth')\n width.text = str(im_size[1])\n height.text = str(im_size[0])\n depth.text = str(im_size[2])\n # append nested elements to size element\n size.append(width)\n size.append(height)\n size.append(depth)\n\n # append filename and size to main xml etree\n annotation.append(filename)\n annotation.append(size)\n\n for bbox in buildings_dict.values():\n # object for each bounding box\n obj = etree.Element('object')\n\n # We only have one class for now. (Note: name is label)\n name = etree.Element('name')\n name.text = \"building\"\n\n # Bounding box preocessing. We assume that bboxes are in\n # [centerX, centerY, width, height] format, and convert it to\n # x_min, x_max, y_min, y_max\n bndbox = etree.Element('bndbox')\n xmin = etree.Element('xmin')\n xmin.text = str(bbox[0] - (bbox[2]/2))\n\n ymin = etree.Element('ymin')\n ymin.text = str(bbox[1] - (bbox[3]/2))\n\n xmax = etree.Element('xmax')\n xmax.text = str(bbox[0] + (bbox[2]/2))\n\n ymax = etree.Element('ymax')\n ymax.text = str(bbox[1] + (bbox[3]/2))\n\n # Append xmin, xmax, ymin, ymax to bounding box object\n bndbox.append(xmin)\n bndbox.append(ymin)\n bndbox.append(xmax)\n bndbox.append(ymax)\n\n # append nested elements in obj\n obj.append(name)\n obj.append(bndbox)\n\n # Append the whole obj to the annotation.\n annotation.append(obj)\n\n # Full annotation, ready to be written\n xml_annotation = etree.ElementTree(annotation)\n\n # save annotation in file\n with open(path_to_dest, 'wb') as dest:\n xml_annotation.write(dest)\n\n def format_coords(self, buildings):\n \"\"\"\n Helper method only called in json_to_xml that takes a dictionary of\n building coordinates and converts them to YOLO format, i.e.\n (centerX, centerY, width, height) for each building\n \"\"\"\n\n for k, v in buildings.items():\n minX = reduce(lambda acc, elt: min(elt[0], acc), v, np.inf)\n minY = reduce(lambda acc, elt: min(elt[1], acc), v, np.inf)\n maxX = reduce(lambda acc, elt: max(elt[0], acc), v, -np.inf)\n maxY = reduce(lambda acc, elt: max(elt[1], acc), v, -np.inf)\n width = maxX - minX\n height = maxY - minY\n centerX = minX + width/2.0\n centerY = minY + height/2.0\n buildings[k] = [centerX, centerY, width, height]\n\n return buildings\n\n def visualize_tile(self, index, directory=\"train\"):\n \"\"\"\n Provides a visualization of the tile and its corresponding annotation/ label in one\n of the train/test/val directories as specified. \n \"\"\"\n\n path = self.train_path\n if directory == \"test\":\n path = self.test_path\n elif directory == \"val\":\n path = self.val_path\n\n # Image visualization\n im = Image.open(f'{path}/images/{index}.jpg')\n im_arr = np.array(im)\n plt.imshow(im_arr)\n\n ann = ET.parse(f'{path}/annotations/{index}.xml').getroot()\n \n buildings_in_tile = {}\n i = 0\n for building in ann.iter(\"bndbox\"):\n xmin = float(building.find('xmin').text)\n ymin = float(building.find('ymin').text)\n xmax = float(building.find('xmax').text)\n ymax = float(building.find('ymax').text)\n buildings_in_tile[i] = [(xmin,ymin),(xmin,ymax),(xmax,ymax),(xmax,ymin)]\n i += 1\n \n for building_coords in buildings_in_tile.values():\n poly = Polygon(building_coords)\n x, y = poly.exterior.xy\n plt.plot(x, y)\n\n plt.show()\n","sub_path":"YOLO_Dataset.py","file_name":"YOLO_Dataset.py","file_ext":"py","file_size_in_byte":8085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405223685","text":"# -*- coding: UTF-8 -*-\nfrom readers.SentiWordPlReader import SentiWordPlReader\nfrom nltk.corpus import WordNetCorpusReader\nfrom tools.TextTools import tokenize, lemmatize\nimport nltk\nimport os\n\n\nclass WordNetPolarizer(object):\n def __init__(self):\n wn_path = 'data/plwordnet_2_2_pwn_format'\n senti_word_read = SentiWordPlReader(os.path.abspath('data/SentiWordNetPl/SentiWordNetPl.txt'))\n self.sentiment_words = senti_word_read.data\n self.wn = WordNetCorpusReader(nltk.data.find(os.path.abspath(wn_path)), None)\n\n def evaluateWordSentiment(self, word):\n related_words = []\n positive_count = 0\n negative_count = 0\n\n word_sentiment = self.sentiment_words.get(word, None)\n if word_sentiment is not None:\n return (word_sentiment['positive'], word_sentiment['negative'])\n\n related_words.extend(self.findSynonyms(word))\n related_words.extend(self.findAntonyms(word))\n\n for word in related_words:\n sentiment = self.getSentimentFromDict(word)\n if sentiment == 'positive':\n positive_count += 1\n elif sentiment == 'negative':\n negative_count += 1\n\n positive_factor = 0\n negative_factor = 0\n\n try:\n positive_factor = float(positive_count) / float(len(related_words))\n except ZeroDivisionError:\n pass\n try:\n negative_factor = float(negative_count) / float(len(related_words))\n except ZeroDivisionError:\n pass\n return (positive_factor, negative_factor)\n\n def getSentimentFromDict(self, word):\n sentiment_word = self.sentiment_words.get(word, None)\n\n if sentiment_word is None:\n return None\n\n if sentiment_word['positive'] > sentiment_word['negative']:\n return 'positive'\n elif sentiment_word['positive'] < sentiment_word['negative']:\n return 'negative'\n return None\n\n def polarizeText(self, text, debug=False):\n text_tk = tokenize(text)\n lemmas = [lemmatize(token) for token in text_tk]\n\n sentiments = [self.evaluateWordSentiment(lemma) for lemma in lemmas]\n\n positive_count = 0\n negative_count = 0\n for pos, neg in sentiments:\n if pos == 0 and neg == 0:\n continue\n if pos >= neg:\n positive_count += 1\n else:\n negative_count += 1\n\n result = 0\n try:\n result = float(positive_count) / float(positive_count + negative_count)\n except ZeroDivisionError:\n pass\n debug = dict(zip(lemmas, sentiments))\n return (result, debug)\n\n def findSynonyms(self, word):\n syns = self.wn.synsets(word)\n synonyms = [l.name() for s in syns for l in s.lemmas()]\n return set(synonyms)\n\n def findAntonyms(self, word):\n return []\n","sub_path":"polarizers/WordNetPolarizer.py","file_name":"WordNetPolarizer.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"541116717","text":"\"\"\"A class that creates, manages, updates coronavirus case & death line plots.\n\nThese plots show the number of cases and deaths from COVID-19 by date, in a\ngiven region and with a given level of data granularity.\n\"\"\"\n\nimport plotly.graph_objects as go\nfrom base_figure import Figure\n\n\nclass LineFigure(Figure):\n def __init__(self, data_manager):\n self.traces = [\n go.Scatter(name=\"Cases\", mode=\"lines\",\n line_color=\"rgb(8,48,107)\"),\n go.Scatter(name=\"Deaths\", mode=\"lines\",\n line_color=\"rgb(165,15,21)\")]\n layout = {\n \"title\": {\"text\": \"Building...\"}\n }\n\n super().__init__(data_manager, self.traces, layout)\n\n def update(self, data_manager=None, col=None):\n super().update(data_manager)\n\n self.fig.update_traces(overwrite=True,\n selector={\"name\": \"Cases\"},\n x=self.region_data()[\"date\"],\n y=self.region_data.cases)\n\n self.fig.update_traces(overwrite=True,\n selector={\"name\": \"Deaths\"},\n x=self.region_data()[\"date\"],\n y=self.region_data.deaths)\n\n self.fig.update_layout(\n title=(\"Number of Cases & Deaths from COVID-19
\"\n \"in {}
\"\n \"Click to select the date represented
\"\n \"in the map data.
\"\n ).format(self.region_name),\n xaxis_title=\"Date\",\n yaxis_title=\"Number of Cases/Deaths\",\n hovermode=\"x unified\"\n )\n","sub_path":"src/line_figure.py","file_name":"line_figure.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634382161","text":"\n\"\"\"\nCreate hreflang tags as specified by Google\n\nhttps://support.google.com/webmasters/answer/189077?hl=en\n\"\"\"\n\nfrom django import template\nfrom django.urls.base import resolve\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import get_language\nfrom django.conf import settings\n\nfrom .. import languages, get_hreflang_info, reverse\n\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef translate_url(context, lang, view_name=None, *args, **kwargs):\n\t\"\"\"\n\tTranslate an url to a specific language.\n\t\n\t@param lang: Which language should the url be translated to.\n\t@param view_name: Which view to get url from, current if not set.\n\t\"\"\"\n\tassert 'request' in context, 'translate_url needs request context'\n\tif view_name is None:\n\t\treverse_match = resolve(context['request'].path)\n\t\tview_name = reverse_match.view_name\n\t\targs = reverse_match.args\n\t\tkwargs = reverse_match.kwargs\n\treturn reverse(view_name, lang=lang, *args, **kwargs)\n\n\n@register.simple_tag(takes_context=True)\ndef hreflang_tags(context, indent=0):\n\t\"\"\"\n\tCreate all hreflang tags (which includes the current document as per the standard).\n\t\"\"\"\n\tassert 'request' in context, 'hreflang_tags needs request context'\n\tprotocol = 'https' if context['request'].is_secure() else 'http'\n\thost = '://' + context['request'].META['HTTP_HOST']\n\threflang_info = get_hreflang_info(context['request'].path)\n\threflang_html = []\n\tfor lang, url in hreflang_info:\n\t\threflang_html.append(\n\t\t\t'\\n'.format(\n\t\t\t\tlang, protocol + host + url, languages()[lang] if lang != 'x-default' else 'English'\n\t\t\t)\n\t\t)\n\treturn mark_safe(('\\t' * indent).join(hreflang_html))\n\n\ndef _make_list_html(path, incl_current):\n\threflang_info = get_hreflang_info(path, default=False)\n\threflang_html = ''\n\tfor lang, url in hreflang_info:\n\t\tif lang == get_language() and incl_current:\n\t\t\threflang_html += '
  • {0}
  • \\n'.format(languages()[lang])\n\t\telse:\n\t\t\threflang_html += '
  • {1}
  • \\n'.format(url, languages()[lang])\n\treturn hreflang_html\n\n\n@register.simple_tag(takes_context=True)\ndef lang_list(context):\n\t\"\"\"\n\tHTML list items with links to each language version of this document.\n\tThe current document is included without link and with a special .hreflang_current_language class.\n\t\"\"\"\n\tassert 'request' in context, 'lang_list needs request context'\n\treturn _make_list_html(context['request'].path, incl_current=True)\n\n\n@register.simple_tag(takes_context=True)\ndef other_lang_list(context):\n\t\"\"\"\n\tLike lang_list, but the current language is excluded.\n\t\"\"\"\n\tassert 'request' in context, 'other_lang_list needs request context'\n\treturn _make_list_html(context['request'].path, incl_current=False)\n\n\n","sub_path":"source/apps/hreflang/templatetags/hreflang.py","file_name":"hreflang.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375814433","text":"#Written by Matteo Bjornsson Edited by Nick Stone \n#################################################################### MODULE COMMENTS ############################################################################\n#The purpose of this class is to calculate the hamming distance between two vectors of features, this will be used in KNN to find distance between neighbots #\n#This algorithm is meant ot be used on data sets with only categorical values. #\n#################################################################### MODULE COMMENTS ############################################################################\n\nclass HammingDistance:\n\n #Parameters: a list of features, a list of features \n #Returns: Return an integer value for the distance between 2 data points \n #Function: Take in 2 feature vectors and calculate the hamming distance between the 2 feature vectors \n def Distance(self, x1, x2):\n #Set the distance value to \n distance = 0\n #Loop through all of the data points in the feature vector \n for i in range(len(x1)):\n #If the feature vector value is equal to the same feature value in the second vector \n if x1[i] == x2[i]:\n #Set the value to be 0 \n value = 0\n #Otherwise \n else:\n #Set the value to 1 \n value = 1\n #Increment the distance to be the value calculated above \n distance += value\n #Return the distance \n return distance\n\n####################################### UNIT TESTING #################################################\nif __name__ == '__main__':\n hd = HammingDistance()\n d = hd.Distance([0,1,0],[1,1,1])\n print(d)","sub_path":"Project 2/HammingDistance.py","file_name":"HammingDistance.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169412181","text":"cube2=[[0 for j in range(3)] for i in range(4)]\ncube=[[0 for j in range(3)] for i in range(4)]\ncubei=[[0 for j in range(3)] for i in range(4)]\nsolved=1\nimport random\n\ndef cubecopy():\n for i in range(4):\n for j in range(3):\n cube[i][j]=cube2[i][j];\n\ndef cubecopy2():\n for i in range(4):\n for j in range(3):\n cube2[i][j]=cube[i][j];\n\ndef cubecopyi():\n for i in range(4):\n for j in range(3):\n cubei[i][j]=cube[i][j];\n\ndef cubecheck():\n global solved\n solved=1\n for i in range(4):\n for j in range(3):\n if(cubei[i][j]!=cube[i][j]):\n solved=0\n\ndef changeface(j,i) :\n cube2[i[0]][i[1]]=cube[j[0]][j[1]];\n\n\n\ndef rotateclockwise(a,b,c,d) :\n changeface(d,a);\n changeface(a,b);\n changeface(b,c);\n changeface(c,d);\n \n\ndef rotatecounterclockwise(a,b,c,d) :\n changeface(a,d);\n changeface(b,a);\n changeface(c,b);\n changeface(d,c);\n\n\n\n\ncube[0][1]=1\ncube[1][0]=2\ncube[1][1]=3\ncube[1][2]=4\ncube[2][1]=5\ncube[3][1]=6\n\ndef printcube():\n print()\n for i in range(4):\n print(cube[i])\n print()\n\ncubecopy2()\ncubecopyi()\n\ndef cubecopy(n,m):\n for i in range(n):\n for j in range(m):\n cube[i][j]=cube2[i][j];\n \ndef moves2(x):\n \n if x=='F': # Front\n rotateclockwise([1,0],[0,1],[1,2],[2,1]);\n if x=='f': # Front'\n rotatecounterclockwise([1,0],[0,1],[1,2],[2,1]);\n\n\n\n if x=='B': # Back\n rotateclockwise([1,2],[0,1],[1,0],[2,1]);\n\n\n if x=='b': #Back'\n rotatecounterclockwise([1,2],[0,1],[1,0],[2,1]);\n\n if x=='U': # Up\n rotateclockwise([1,1],[1,0],[3,1],[1,2]);\n\n\n if x=='u': #Up'\n rotatecounterclockwise([1,1],[1,0],[3,1],[1,2]);\n\n if x=='D': # Down\n rotateclockwise([1,1],[1,2],[3,1],[1,0]);\n\n if x=='d': #Down' \n rotatecounterclockwise([1,1],[1,2],[3,1],[1,0]);\n\n if x=='R': # Right\n rotateclockwise([1,1],[0,1],[3,1],[2,1]);\n\n if x=='r': #Right'\n rotatecounterclockwise([1,1],[0,1],[3,1],[2,1]);\n if x=='L': # Left\n rotateclockwise([1,1],[2,1],[3,1],[0,1]);\n\n if x=='l': #Left' \n rotatecounterclockwise([1,1],[2,1],[3,1],[0,1]);\n cubecopy(4,3)\n\n \n\n\nop='F';\n\ndef map2(y):\n global op\n if y==0:\n op='F';\n if y==1:\n op='f';\n if y==2:\n op='B';\n if y==3:\n op='b'; \n if y==4:\n op='U';\n if y==5:\n op='u';\n if y==6:\n op='D';\n if y==7:\n op='d';\n if y==8:\n op='R';\n if y==9:\n op='r';\n if y==10:\n op='L';\n if y==11:\n op='l';\n\n\n\ndef undo(x):\n if(x%2==0):\n return x+1\n else:\n return x-1\n\n\nprintcube()\n\nmoveno=1000\n\nm=[0 for j in range(moveno)]\num=[0 for j in range(moveno)]\nfor i in range(len(m)):\n \n m[i]=random.randint(0,11)\n map2(m[i])\n moves2(op)\nprint(m)\nprintcube()\n\nfor i in range(len(m)):\n \n um[i]=undo(m[len(m)-i-1])\n map2(um[i])\n moves2(op)\nprint(um) \nprintcube()\n\n","sub_path":"1by1cube_solveunscramble_1.py","file_name":"1by1cube_solveunscramble_1.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"12636485","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def deepestLeavesSum(self, root: TreeNode) -> int:\n res = []\n\n def dfs(root, path):\n if root:\n path.append(root.val)\n if not root.left and not root.right:\n # 叶子节点\n res.append(path)\n else:\n dfs(root.left, path[:])\n dfs(root.right, path[:])\n\n dfs(root, [])\n res.sort(key=len, reverse=True)\n deep = len(res[0])\n s = 0\n for item in res:\n if len(item) == deep:\n s += item[-1]\n\n return s\n\n\nif __name__ == '__main__':\n s = Solution()\n from gen_tree import generate_tree\n\n root = [1, 2, 3, 4, 5, None, 6, 7, None, None, None, None, 8]\n tree = generate_tree(root)\n print(s.deepestLeavesSum(tree))\n","sub_path":"二叉树/1302.py","file_name":"1302.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"430323803","text":"\"\"\"\nMichael South\nCracking the Coding Interview - Problem 1.1\nIs Unique: Implement an algorithm to determine if a string has all unique characters.\n\"\"\"\n\n\ndef is_unique(inputString):\n\t# We assume expanded ASCII limit is being used (size = 256)\n\t# Standard ASCII may be used in it's place (size = 128 characters)\n\n\tvalues = set()\n\n\tif len(inputString) > 256:\n\t\treturn False\n\tfor c in inputString:\n\t\tif c in values:\n\t\t\treturn False\n\t\tvalues.add(c)\n\treturn True\n\n\ndef main():\n\t# Input for testing\n\ttest_string = \"1234567890asdfgxcvbe1\"\n\tprint(is_unique(test_string))\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Python/Chapter_01/Problem_1_1.py","file_name":"Problem_1_1.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68339441","text":"\"\"\"\nnew-wea.py - Phenny Weather Module using Dark Sky API\nCopyright 2013, Jin Park - jinpark.net\nLicensed under the Eiffel Forum License 2.\n\nhttp://inamidst.com/phenny/\n\"\"\"\n\nimport urllib, simplejson, apikey, csv\n\ndegc = \"\\xc2\\xb0C \"\ndegf = \"\\xc2\\xb0F \"\nforc = ['f','F','c','C']\n\ndef degree_to_direction(deg):\n if (337.5 <= deg <= 360) or (0 <= deg < 22.5):\n return \"N\"\n elif 22.5 <= deg < 67.5:\n return \"NE\"\n elif 67.5 <= deg < 112.6:\n return \"E\"\n elif 112.6 <= deg < 157.5:\n return \"SE\"\n elif 157.5 <= deg < 202.5:\n return \"S\"\n elif 202.5 <= deg < 247.5:\n return \"SW\"\n elif 247.5 <= deg < 292.5:\n return \"W\"\n elif 292.5 <= deg < 337.5:\n return \"NW\"\n\n# def weajew(phenny, input):\n# \"\"\"Displays weather using Dark Sky API\"\"\"\n# userinput = str(input.group(2))\n# #create dict to search for nick/location\n# with open('nickloc.csv', 'rU') as f:\n# z = csv.reader(f)\n# nickdict = {}\n# for key, val in z:\n# nickdict[key] = val\n# nickname1 = input.nick\n# nickname2 = nickname1.strip().lower()\n# if nickname2 in nickdict:\n# if userinput in forc:\n# loc = nickdict[nickname2] + \" \" + userinput\n# elif userinput == 'None':\n# loc = nickdict[nickname2]\n# else:\n# loc = userinput\n# else:\n# loc = userinput\n# if loc == 'None':\n# urlunits = 'ca' \n# elif loc[-2:] == \" C\" or loc[-2:] == \" c\":\n# urlunits = 'ca'\n# loc = loc[:-2]\n# elif loc[-2:] == \" F\" or loc[-2:] == \" f\":\n# urlunits = 'us'\n# loc = loc[:-2]\n# else:\n# urlunits = 'ca'\n# locinput1 = loc.strip().lower().encode('utf8')\n# htmlinput = urllib.quote(locinput1)\n# url4 = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + htmlinput + '&sensor=true'\n# jsonResponse1 = simplejson.load(urllib.urlopen(url4))\n# longi = jsonResponse1['results'][0]['geometry']['location']['lng']\n# lati = jsonResponse1['results'][0]['geometry']['location']['lat']\n# loca = jsonResponse1['results'][0]['formatted_address']\n# url3 = 'https://api.forecast.io/forecast/' + apikey.darksky + '/' + str(lati) + ',' + str(longi) + '?units=' + urlunits\n# weajson = simplejson.load(urllib.urlopen(url3))\n# nowwea = weajson['currently']\n# units = weajson['flags']['units']\n# if units == 'us':\n# deg = degf\n# windspeedunits = \"mph\"\n# else:\n# deg = degc\n# windspeedunits = \"km/h\"\n# phennyout = str(int(round(nowwea[\"temperature\"]))) + deg + nowwea[\"summary\"] + \", Wind \" + degreeToDirection(nowwea[\"windBearing\"]) + \" \" + str(round(nowwea[\"windSpeed\"],1)) + \" \" + windspeedunits + \" in \" + loca.encode('utf8') + \". \" + \"Feels like \" + str(round(nowwea[\"apparentTemperature\"],1))\n# loca.encode('utf8') + \".\"\n# phenny.say(phennyout)\n# \n# weajew.commands = ['weajew']\n# weajew.priority = 'low'\n# weajew.example = '.weajew n2t1k5'\n\ndef weajew(phenny, input):\n \"\"\"Display weather using Dark Sky API\"\"\"\n\n userinput = str(input.group(2))\n #create dict to search for nick/location\n with open('nickloc.csv', 'rU') as f:\n z = csv.reader(f)\n nickdict = {}\n for key, val in z:\n nickdict[key] = val\n nickname1 = input.nick\n nickname2 = nickname1.strip().lower()\n if nickname2 in nickdict:\n if userinput in forc:\n loc = nickdict[nickname2] + \" \" + userinput\n elif userinput == 'None':\n loc = nickdict[nickname2]\n else:\n loc = userinput\n else:\n loc = userinput\n \n user_location = urllib.quote(loc)\n user_units = 'si'\n \n geocode_url = (\"http://maps.googleapis.com/maps/api/geocode/json?address={location}&sensor=true\"\n .format(location=user_location)\n )\n geocode_data = simplejson.load(urllib.urlopen(geocode_url))\n geocode_first_result = geocode_data['results'][0]\n latitude = geocode_first_result['geometry']['location']['lat']\n longitude = geocode_first_result['geometry']['location']['lng']\n location = geocode_first_result['formatted_address']\n\n weather_url = (\"{api_url}{api_key}/{latitude},{longitude}?units={units}\"\n .format(api_url='https://api.forecast.io/forecast/',\n api_key=apikey.darksky,\n latitude=latitude,\n longitude=longitude,\n units=user_units)\n )\n weather_data = simplejson.load(urllib.urlopen(weather_url))\n weather = weather_data['currently']\n\n degrees_celcius = \"\\xc2\\xb0C\"\n degrees_fahrenheit = \"\\xc2\\xb0F\"\n\n if user_units == 'us':\n temperature_unit = degrees_fahrenheit\n wind_speed_unit = \"mph\"\n elif user_units == 'uk':\n temperature_unit = degrees_celcius\n wind_speed_unit = \"mph\"\n elif user_units == 'ca':\n temperature_unit = degrees_celcius\n wind_speed_unit = \"km/h\"\n elif user_units == 'si':\n temperature_unit = degrees_celcius\n wind_speed_unit = \"m/s\"\n\n output = (\"{temperature}{temperature_unit} ({temperature_feel}) {conditions} | Wind {wind_direction} {wind_speed} {wind_speed_unit} | {location}\"\n .format(temperature=round(weather[\"temperature\"], 1),\n temperature_unit=temperature_unit,\n temperature_feel=round(weather[\"apparentTemperature\"], 1),\n conditions=weather[\"summary\"],\n wind_direction=degree_to_direction(weather[\"windBearing\"]),\n wind_speed=round(weather[\"windSpeed\"], 1),\n wind_speed_unit=wind_speed_unit,\n location=location.encode('utf8'))\n )\n\n phenny.say(output)\n\nweajew.commands = ['weajew', 'weat']\nweajew.priority = 'low'\nweajew.example = '.weajew stockholm, sweden'\n","sub_path":"oldmodules/weatherbob.py","file_name":"weatherbob.py","file_ext":"py","file_size_in_byte":5682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571646897","text":"import json,os,codecs\nclass DSAraby:\n def __init__(self):\n self.load_mapping()\n self.letters_to_ret = set()\n \n \n def load_mapping(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n self.en_to_ar = json.loads(open(dir_path+'/assets/mapping.manual.json', encoding='utf-8').read())\n self.NWORDS = {}\n word_counts = codecs.open(dir_path+'/assets/corpus.txt', encoding='utf-8').read().split(\"\\n\")\n for word_count in word_counts:\n if word_count:\n [word, n] = word_count.split()\n if word is None or n is None:\n pass\n else:\n self.NWORDS[word] = int(n)\n\n \n def transliterate(self,sentence, verbose=False):\n words = sentence.split()\n ret = []\n for word in words:\n candidates = list(self.transliterate_word(word))\n best_candidates = self.sort_by_frequency(candidates)\n if len(best_candidates) > 0:\n ret.append(self.sort_by_frequency(candidates)[0])\n else:\n ret.append(word)\n return ' '.join(ret)\n \n def transliterate_word(self,word):\n ret = self.transliterate_letter(word,'',True)\n self.letters_to_ret = set()\n return ret\n \n def transliterate_letter(self,letters, word, begin='start'):\n if len(letters) == 0:\n self.letters_to_ret.add(word)\n return\n \n if begin == 'start':\n table = self.en_to_ar['start']\n elif begin == 'other':\n table = self.en_to_ar['other']\n else :\n table = self.en_to_ar['end']\n max_key_len = len(max(list(table), key=len))\n for i in range(1, max_key_len + 1):\n l = letters[:i]\n if l in table:\n for ar in table[l]:\n self.transliterate_letter(letters[i:], word + ar,'start')\n \n return self.letters_to_ret\n \n def sort_by_frequency(self,candidates): \n return sorted(candidates, key=lambda k: self.NWORDS.get(k,0), reverse=True)","sub_path":"src/build/lib/dsaraby/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327037718","text":"#!/usr/bin/env python\n# license removed for brevity\n\nimport serial\n\nserial_name = '/'\n\n\n# Absolute route of the port, name of port, side of communication, timeout of readline\ndef serial_initialization(route, port, times):\n lecture = True\n try:\n global serial_name\n serial_name = serial.Serial(route + '/' + port, timeout=times)\n except:\n lecture = False\n return lecture\n\n\ndef write_data(data):\n write_correct = True\n data_send = ''\n global serial_name\n try:\n for key in data: data_send = data_send + key + 'x' + str(data[key]) + 'x'\n data_send = data_send + '\\n'\n serial_name.write(data_send.encode('utf-8'))\n except:\n write_correct = False\n return write_correct\n\n\ndef read_data():\n read_correct = True\n global serial_name\n try:\n data = serial_name.readline()\n data = data.decode('utf-8')\n if data == '': raise Exception\n data = data_format(data[0:-1])\n except:\n read_correct = False\n return read_correct, data\n\n\ndef data_format(data_read):\n data = {}\n d2 = data_read.split('x')\n for i in range(len(d2)):\n if i % 2 != 0: data[d2[i - 1]] = float(d2[i])\n return data\n","sub_path":"SNN_Codes/Spiking_codes/communicate.py","file_name":"communicate.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"86123441","text":"from django.conf.urls import url\nfrom . import views\nurlpatterns = [\n # path('admin/', admin.site.urls),\n url('index/',views.index),\n url('share/',views.share),\n url('list/(?P\\d+)',views.list),\n url('about/',views.about),\n url('gbook/',views.gbook),\n url('info/(?P\\d+)$',views.info),\n url('infopic/(?P\\d+)',views.infopic),\n url('comment',views.comment),\n url('digit',views.digit),\n url('write',views.write),\n url('photo',views.photo),\n url('upload_img',views.upload_img),\n\n\n url('qx',views.qx),\n \n\n\n]","sub_path":"myblog/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"342596636","text":"from django.contrib.auth.models import User\nfrom .models import Profile, Post, Comment\nfrom django import forms\n\nclass UpdateUserForm(forms.ModelForm):\n email = forms.EmailField()\n\n class Meta:\n model = User\n fields = (\n 'username',\n 'first_name',\n 'last_name',\n 'email',) \n\n\nclass UpdateProfileForm(forms.ModelForm):\n class Meta:\n model = Profile\n exclude = ('user',) \n\n\nclass PostCreateForm(forms.ModelForm):\n post_description = forms.CharField(label=\"\", widget=forms.Textarea(attrs={'class':'form-control','placeholder' : 'Write a description...','rows':'3','cols':'40'}))\n class Meta:\n model = Post \n fields = (\n 'post_description',\n 'post_photo',\n 'restrict_comment',\n )\n\nclass PostEditForm(forms.ModelForm):\n post_description = forms.CharField(label=\"\", widget=forms.Textarea(attrs={'class':'form-control','rows':'3','cols':'20',}))\n class Meta:\n model = Post \n fields = (\n 'post_description',\n 'post_photo',\n 'restrict_comment',\n )\n\nclass CommentForm(forms.ModelForm):\n content = forms.CharField(label=\"\", widget=forms.Textarea(attrs={'placeholder' : 'Write a comment...','rows':'2', 'cols' : '40'}))\n class Meta:\n model = Comment\n fields = (\n 'content',\n )","sub_path":"home/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563045097","text":"import json\nfrom django.shortcuts import render\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom halls.models import Hall\n\ndef map(request):\n halls = Hall.objects.all()\n hall_data = [hall.get_preview_dict() for hall in halls]\n for hall in hall_data:\n # Get the actual Django instance\n hall_instance = halls.get(pk=hall.get('id'))\n # And query all the rooms, taking only the formatted_string to pass to the view\n hall['room_descs'] = [roomtype.formatted_string for roomtype in hall_instance.roomtype_set.all()]\n\n hall_data_json = json.dumps(list(hall_data), cls=DjangoJSONEncoder)\n return render(request, 'maps/map.html', {\n 'halls': hall_data,\n 'hall_data_json': hall_data_json\n })\n","sub_path":"honesthalls/maps/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526775538","text":"import numpy as np\nimport copy\nimport time\nfrom Main import Output, Stats, notify_solution_found, notify_end_loop\nimport random\n\n\nclass ForwardChecking:\n def __init__(self, data):\n self.data = data\n self.start_time = 0\n self.back_count = 0\n self.nodes_count = 0\n self.output = Output(data.file_name, \"ForwardChecking\")\n self.board_matrix = np.copy(data.board_matrix)\n self.initial_vars_dict = copy.deepcopy(data.variables_dict)\n self.vars_dicts_stack = [self.initial_vars_dict]\n self.vars_list = list(self.initial_vars_dict)\n self.cons_list = data.constraints_list\n self.curr_var_idx = 0\n\n # self._heuristic_most_cons()\n # self._heuristic_smallest_field()\n self.values_count_dict = {}\n\n def search_solutions(self):\n self.start_time = time.time()\n print(\"FILE NAME: \", self.data.file_name)\n print(\"START FORWARD CHECKING LOOP\")\n while self.curr_var_idx < len(self.vars_list):\n if self.curr_var_idx == -1:\n self._loop_end()\n return self.output\n\n curr_var = self.vars_list[self.curr_var_idx]\n next_value = self._get_next_val(curr_var)\n\n if next_value is None:\n self._go_back(curr_var)\n continue\n\n self.nodes_count += 1\n is_val_correct = self._check_forward(curr_var, next_value)\n if is_val_correct:\n found = self._go_deeper(curr_var, next_value)\n # if found:\n # return self.output\n else:\n self.back_count += 1\n return self.output\n\n def _go_back(self, curr_var):\n self.vars_dicts_stack.pop()\n self.board_matrix[curr_var] = self.data.board_matrix[curr_var].copy()\n self.curr_var_idx -= 1\n\n def _go_deeper(self, curr_var, corr_value):\n self.board_matrix[curr_var] = corr_value\n if curr_var != self.vars_list[len(self.vars_list) - 1]:\n self.curr_var_idx += 1\n return False\n else:\n self._solution_found()\n self.vars_dicts_stack.pop()\n return True\n\n def _get_next_val(self, curr_var):\n curr_dict = self.vars_dicts_stack[len(self.vars_dicts_stack) - 1]\n field = list(curr_dict[curr_var])\n if len(field) <= 0:\n return None\n # next_val = field.pop(0)\n next_val = field.pop(len(field) - 1)\n # next_val = field.pop(random.randint(0, len(field) - 1))\n curr_dict[curr_var] = field\n return next_val\n\n def _check_forward(self, var_to_check, value):\n curr_dict = self.vars_dicts_stack[len(self.vars_dicts_stack) - 1]\n new_dict = copy.copy(curr_dict)\n\n if self._clear_rows_and_cols(var_to_check, value, new_dict):\n if self._clear_global_cons(var_to_check, value, new_dict):\n self.vars_dicts_stack.append(new_dict)\n return True\n return False\n\n def _clear_rows_and_cols(self, var_to_check, value, new_dict):\n vars_to_clear = self._get_vars_in_same_row_or_col(var_to_check)\n for var in vars_to_clear:\n field = list(new_dict[var])\n if value in field:\n field.remove(value)\n new_dict[var] = field\n if len(field) <= 0:\n return False\n return True\n\n def _get_vars_in_same_row_or_col(self, var_to_check):\n linked_vars = []\n for i in range(self.curr_var_idx, len(self.vars_list)):\n var = self.vars_list[i]\n if var != var_to_check and (var[0] == var_to_check[0] or var[1] == var_to_check[1]):\n linked_vars.append(var)\n return linked_vars\n\n def _clear_global_cons(self, var_to_check, value, new_dict):\n cons_with_var = [(x, y) for (x, y) in self.cons_list if x == var_to_check or y == var_to_check]\n if len(cons_with_var) <= 0:\n return True\n\n for (first_var, second_var) in cons_with_var:\n if first_var == var_to_check:\n if self._is_var_forward(second_var):\n not_empty = self._remove_smaller_values(second_var, value, new_dict)\n if not not_empty:\n return False\n elif second_var == var_to_check:\n if self._is_var_forward(first_var):\n not_empty = self._remove_bigger_values(first_var, value, new_dict)\n if not not_empty:\n return False\n return True\n\n def _is_var_forward(self, poss_forward_var):\n poss_forward_var_index = self.vars_list.index(poss_forward_var)\n return poss_forward_var_index > self.curr_var_idx\n\n def _remove_bigger_values(self, var, value, new_dict):\n new_field = [val for val in new_dict[var] if val < value]\n new_dict[var] = new_field\n if len(new_field) <= 0:\n return False\n return True\n\n def _remove_smaller_values(self, var, value, new_dict):\n new_field = [val for val in new_dict[var] if val > value]\n new_dict[var] = new_field\n if len(new_field) <= 0:\n return False\n return True\n\n def _solution_found(self):\n search_time = time.time() - self.start_time\n self.output.solution_matrix = np.copy(self.board_matrix)\n self.output.solution_stats = Stats(float(search_time), int(self.back_count), int(self.nodes_count))\n notify_solution_found(search_time, self.board_matrix, self.back_count, self.nodes_count)\n\n def _loop_end(self):\n end_time = time.time() - self.start_time\n self.output.end_stats = Stats(float(end_time), int(self.back_count), int(self.nodes_count))\n notify_end_loop(end_time, self.back_count, self.nodes_count)\n\n def _heuristic_most_cons(self):\n print(\"HEURISTIC MOST CONS\")\n self.vars_list.sort(key=self._cons_num, reverse=True)\n\n def _cons_num(self, var):\n cons_num = 0\n for con in self.cons_list:\n if var in con:\n cons_num += 1\n return cons_num\n\n def _heuristic_smallest_field(self):\n print(\"HEURISTIC SMALLEST FIELD\")\n self.vars_list.sort(key=self._field_size)\n\n def _field_size(self, var):\n field = self.initial_vars_dict[var]\n return len(field)\n","sub_path":"Futoshiki/ForwardChecking.py","file_name":"ForwardChecking.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"631820785","text":"import Algorithmia\n\napiKey = 'simQAbMR5x/Aw1QuWcRenMEWffU1'\nclient = Algorithmia.client(apiKey)\n\n\nalgo = client.algo('demo/Hello/0.1.1')\nresponse = algo.pipe(\"HAL 9000\")\n\n# input = {\n# \"image\": \"https://s-media-cache-ak0.pinimg.com/originals/de/bd/3d/debd3d0f7478d7a6b0b7215ee779e323.jpg\",\n# \"numResults\": 7\n# }\n\n\ninput = {\n \"image\": \"dropbox:///images/neutral.jpg\",\n \"numResults\": 7\n}\n\n\nalgo = client.algo('deeplearning/EmotionRecognitionCNNMBP/0.1.2')\n\nresult = algo.pipe(input).result\n\nprint(result)","sub_path":"scripts/algorithmia.py","file_name":"algorithmia.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"301217700","text":"from collections import Iterable\nimport sys\n\nclass pysweep_printer(object):\n \"\"\"This function will store the master rank and print given values.\"\"\"\n\n def __init__(self, rank,master_rank):\n self.rank = rank\n self.master = master_rank\n\n def __call__(self, args,p_iter=False,p_ranks=False,end=\"\\n\"):\n\n if (self.rank == self.master or p_ranks) and p_iter:\n if isinstance(args,Iterable):\n for item in args:\n sys.stdout.write(\"[ \")\n for si in item:\n sys.stdout.write(\"%.0f\"%si+\", \")\n sys.stdout.write(\"]\\n\")\n else:\n args = args,\n for item in args:\n print(item,end=end)\n elif self.rank == self.master or p_ranks:\n print(args,end=end)\n\ndef pm(arr,i,ps=\"%d\"):\n for item in arr[i,0,:,:]:\n sys.stdout.write(\"[ \")\n for si in item:\n sys.stdout.write(ps%si+\", \")\n sys.stdout.write(\"]\\n\")\n","sub_path":"distributed/decomposition/ccore/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328549750","text":"# (C) Copyright IBM Corp. 2018. 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\"\"\"\nThis program resizes prediction files from one directory tree and writes\nthem to another directory tree.\n\nFor example `python 192 prediction128 prediction192` will resize all the\nprediction.nii.gz files it finds in the prediction128 directory tree to a\ncube of size 192 and writes the resized prediction in the same subpath under\nthe prediction192 directory.\n\"\"\"\n\nimport sys\nimport os\nimport glob\nimport nibabel as nib\nfrom unet3d.utils.utils import resize\n\ndef main():\n if len(sys.argv) < 2:\n print('Usage: ')\n print('Example: 192 prediction prediction192')\n\n return\n target_dim = int(sys.argv[1])\n target_shape = (target_dim, target_dim, target_dim)\n source_dir = sys.argv[2]\n target_dir = sys.argv[3]\n\n for case_folder in glob.glob('%s/*' % source_dir):\n if not os.path.isdir(case_folder):\n continue\n\n truth_file = os.path.join(case_folder, \"prediction.nii.gz\")\n target_file = os.path.join(case_folder.replace(source_dir, target_dir),\n \"prediction.nii.gz\")\n print('Processing %s' % truth_file)\n image = nib.load(truth_file)\n new_img = resize(image, target_shape, interpolation=\"nearest\")\n new_img.to_filename(target_file)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"brats/resize_predictions.py","file_name":"resize_predictions.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"227924458","text":"from rest_framework import status\nfrom rest_framework.parsers import FormParser, MultiPartParser\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework.generics import GenericAPIView\nfrom mintstore.models import Product, RefProductType, RefOrderStatusCode, \\\n RefOrderItemStatusCode, RefInvoiceStatusCodes, CurrentInventory, RefPaymentMethod\nfrom mintstore.serializer import RefProductTypeSerializer, ProductSerializer, \\\n InventorySerializer\n\n\nRefProductType.objects.get_or_create(category='D')\nRefOrderStatusCode.objects.get_or_create(status='Cancelled')\nRefOrderStatusCode.objects.get_or_create(status='Completed')\nRefOrderStatusCode.objects.get_or_create(status='Being Processed')\nRefOrderItemStatusCode.objects.get_or_create(status='Delivered')\nRefOrderItemStatusCode.objects.get_or_create(status='Out of Stock')\nRefOrderItemStatusCode.objects.get_or_create(status='In Stock')\nRefInvoiceStatusCodes.objects.get_or_create(status='Issued')\nRefInvoiceStatusCodes.objects.get_or_create(status='Paid')\nRefPaymentMethod.objects.get_or_create(description='CC')\n\n\nclass ProductAPIView(GenericAPIView):\n \"\"\"Creates and returns the products\"\"\"\n permission_classes = (AllowAny,)\n parser_classes = ([FormParser, MultiPartParser])\n\n def post(self, request):\n product_name = request.POST.get('product_name')\n try:\n Product.objects.get(product_name=product_name)\n context = {'message': 'Product already exists'}\n return Response(context, status=status.HTTP_409_CONFLICT)\n except:\n product_serializer = ProductSerializer(data=request.data)\n if product_serializer.is_valid():\n product_serializer.save()\n context = {'message': 'Product added successfully'}\n return Response(context, status=status.HTTP_200_OK)\n else:\n return Response(product_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n products = Product.objects.all()\n serializer = ProductSerializer(products, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass ProductCategoryAPIView(GenericAPIView):\n \"\"\"Adds and returns List of all the category types\"\"\"\n permission_classes = (AllowAny,)\n parser_classes = ([FormParser, MultiPartParser])\n\n def post(self, request):\n category = request.POST.get('category')\n try: # Checks if the product category exists\n RefProductType.objects.get(category=category)\n context = {'message': 'Category already exists'}\n return Response(context, status=status.HTTP_409_CONFLICT)\n except:\n serializer = RefProductTypeSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n types = RefProductType.objects.all()\n serializer = RefProductTypeSerializer(types, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass ProductsByCategoryAPIView(GenericAPIView):\n permission_classes = (AllowAny,)\n\n def post(self, request):\n category = RefProductType.objects.filter(category=request.POST.get('category'))\n products = Product.objects.filter(category=category)\n serializer = ProductSerializer(products, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass ProductByIDAPIView(GenericAPIView):\n \"\"\"GET with header that will get a specific Product\"\"\"\n permission_classes = (AllowAny,)\n queryset = Product.objects.all()\n\n def get(self, request):\n raw_data = request.GET.copy()\n product_id = raw_data.get('product_id')\n try:\n product = Product.objects.get(id=product_id)\n serializer = ProductSerializer(product)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except:\n context = {'message': 'Product not found'}\n return Response(context, status=status.HTTP_404_NOT_FOUND)\n\n\nclass InventoryAPIView(GenericAPIView):\n \"\"\"\"Gets and creates inventory\"\"\"\n permission_classes = (AllowAny,)\n queryset = CurrentInventory\n parser_classes = ([FormParser, MultiPartParser])\n\n def post(self, request):\n raw_data = request.POST.copy()\n product_id = raw_data.get('product_id')\n quantity = raw_data.get('quantity')\n try:\n # Checks to see if the product exists\n product = Product.objects.get(id=product_id)\n CurrentInventory.objects.create(product=product, quantity=quantity).save()\n context = {'message': 'Inventory Updated'}\n return Response(context, status=status.HTTP_200_OK)\n except: # Product not found\n print('product does not exist with this ID')\n context = {'message': 'No Product with that ID'}\n return Response(context, status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n inventory = CurrentInventory.objects.all()\n serializer = InventorySerializer(inventory, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass TestAPIView(GenericAPIView):\n permission_classes = (AllowAny,)\n\n def post(self, request):\n products = request.data.get('products')\n\n for i in range(0, len(products)):\n print(products[i].get('id'))\n print(products[i].get('quantity'))\n\n '''\n customer_id = request.data.get('customer_id')\n product_id = request.data.get('product').get('id')\n quantity = request.data.get('product').get('quantity')\n location = request.data.get('location')\n order = Order.objects.create(customer_id=customer_id, status_id=2)\n\n order_item = OrderItem.objects.create(order=order,\n product_id=product_id,\n order_item_status_code_id=3,\n item_quantity=quantity)\n\n print('Done')\n context = {'message': \"Done\"}\n '''\n return Response(status=status.HTTP_200_OK)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"mintstore/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"9479406","text":"from collections import OrderedDict\n\ndef convert_to_list_of_ordered_dicts(list_of_dicts):\n if len(list_of_dicts) == 0:\n return []\n keys = list(list_of_dicts[0].keys()) # arbitrary key order\n list_of_ordered_dicts = []\n for element in list_of_dicts:\n ordered_dict = OrderedDict()\n for key in keys:\n ordered_dict[key] = element[key]\n list_of_ordered_dicts.append(ordered_dict)\n\n return list_of_ordered_dicts\n\ngenome_data = {\n \"sample_id1\": [\n {\n \"sample_id\": \"sample_id1\",\n \"aws_uri\": \"aws_uri_1\",\n \"gcp_uri\": \"gcp_uri_1\",\n \"md5\": \"md5_1\",\n \"file_size\": \"file_size_1\",\n }\n ],\n \"sample_id2\": [\n {\n \"sample_id\": \"sample_id2\",\n \"aws_uri\": \"aws_uri_2\",\n \"gcp_uri\": \"gcp_uri_2\",\n \"md5\": \"md5_2\",\n \"file_size\": \"file_size_2\",\n },\n {\n \"aws_uri\": \"aws_uri_2\",\n \"gcp_uri\": \"gcp_uri_2\",\n \"md5\": \"md5_2\",\n \"file_size\": \"file_size_2\",\n },\n ],\n}\n\ndbgap_data = {\n \"sample_id1\": [\n {\n \"sample_id\": \"sample_id1\",\n \"biosample_id\": \"biosample_id1\",\n \"sra_sample_id\": \"sra_sample_id1\",\n },\n {\n \"sample_id\": \"sample_id2\",\n \"biosample_id\": \"biosample_id1_2\",\n \"sra_sample_id\": \"sra_sample_id1_2\",\n },\n ],\n \"sample_id2\": [\n {\n \"sample_id\": \"sample_id2\",\n \"biosample_id\": \"biosample_id2\",\n \"sra_sample_id\": \"sra_sample_id2\",\n }\n ],\n \"sample_id3\": [\n {\n \"sample_id\": \"sample_id3\",\n \"biosample_id\": \"biosample_id3\",\n \"sra_sample_id\": \"sra_sample_id3\",\n }\n ],\n}\n\n# Duplicate submitted_sample_ids with matching md5 hashes, so this is invalid data\nindexable_data_with_duplicates = [\n {\n 'submitted_sample_id': 'NWD1',\n 'submitted_subject_id': 'Gene_1234a',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/w==',\n 'md5_hex': '5c9e1e4544c80f43c1844978569e31ff'\n },\n {\n 'submitted_sample_id': 'NWD2',\n 'submitted_subject_id': 'Gene_1234b',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/w==',\n 'md5_hex': '5c9e1e4544c80f43c1844978569e31ff'\n },\n {\n 'submitted_sample_id': 'NWD2',\n 'submitted_subject_id': 'Gene_1234c',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/w==',\n 'md5_hex': '5c9e1e4544c80f43c1844978569e31ff'\n }\n]\nindexable_data_with_duplicates = convert_to_list_of_ordered_dicts(indexable_data_with_duplicates)\n\n# Duplicate submitted_sample_ids, but the md5 hashes for these are unique, so this is valid data\nindexable_data_with_no_duplicates = [\n {\n 'submitted_sample_id': 'NWD1',\n 'submitted_subject_id': 'Gene_1234a',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/w==',\n 'md5_hex': '5c9e1e4544c80f43c1844978569e31ff'\n },\n {\n 'submitted_sample_id': 'NWD2',\n 'submitted_subject_id': 'Gene_1234b',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/w==',\n 'md5_hex': '5c9e1e4544c80f43c1844978569e31ff'\n },\n {\n 'submitted_sample_id': 'NWD2',\n 'submitted_subject_id': 'Gene_1234c',\n 'aws_uri': 's3://bucket/file.csi',\n 'gcp_uri': 'gs://bucket/file.csi',\n 'md5': 'XJ4eRUTID0PBhEl4Vp4x/z==',\n 'md5_hex': '5c9e1e4544c80f43c1944978569e31ff'\n }\n]\n\nindexable_data_with_no_duplicates = convert_to_list_of_ordered_dicts(indexable_data_with_no_duplicates)","sub_path":"scripts/tests/test_data/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"493699868","text":"import time\n#二分法要找的列表一定是有序的\nlist = [1,3,5,8,10,20,21,30,34,47,89]\nkey = 21\ncenter = int(len(list)/2)\n\n#第一步 判断要找的在不在\n\nif key in list:\n\tstart = time.time()\n\twhile True:\n\t\tif list[center] > key:\n\t\t\tcenter = center - 1\n\t\telif list[center]< key:\n\t\t\tcenter = center + 1\n\t\telif list[center] == key:\n\t\t\tprint(\"要找的是数字是%d在索引%d\"%(key,center))\n\t\t\tend = time.time()\n\t\t\tprint(end-start)\n\t\t\tbreak\n","sub_path":"18day/1-二分法.py","file_name":"1-二分法.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"99186690","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 30 17:11:19 2018\n\n@author: Simon.Rhee\n\"\"\"\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine\nfrom config import Config\n\nimport os\nimport os.path\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\n# Setup database object\ndb = SQLAlchemy(app)\n\nfile = os.path.expanduser(r'~\\Desktop\\ClimateView\\Databases\\projects.db')\n\nexistingfile = os.path.expanduser(r'~\\Desktop\\ClimateView\\Databases\\projects.db')\n#os.remove(existingfile)\n#print('removed')\n\n\n# Climate Classes\nclass Geocode(db.Model):\n __tablename__ = 'geocode'\n id = db.Column(db.Integer, primary_key=True)\n country = db.Column(db.String)\n state = db.Column(db.String)\n name = db.Column(db.String, unique=True)\n latitude = db.Column(db.Float)\n longitude = db.Column(db.Float)\n elevation = db.Column(db.Float)\n timezone = db.Column(db.String)\n utcoffset = db.Column(db.String)\n ashraes = db.relationship('Ashrae', backref='project', lazy='dynamic')\n thirtyyearstations = db.relationship('ThirtyYearStation', backref='project2', lazy='dynamic')\n ncdc2010s = db.relationship('NCDC2010', backref='project3', lazy='dynamic')\n tmys = db.relationship('TMY', backref='project4', lazy='dynamic')\n psmv3s = db.relationship('PSMv3', backref='psmv3_ref', lazy='dynamic')\n scenarios = db.relationship('Scenario', backref='scenario_ref', lazy='dynamic')\n solargis_tmys = db.relationship('SolarGIS_TMY', backref='solargis_tmy_ref', lazy='dynamic')\n solargis_timeseriess = db.relationship('SolarGIS_Timeseries', backref='solargis_timeseries_ref', lazy='dynamic')\n\n def __init__(self,\n country,\n state,\n name,\n latitude,\n longitude,\n elevation,\n timezone,\n utcoffset):\n self.country = country\n self.state = state\n self.name = name\n self.latitude = latitude\n self.longitude = longitude\n self.elevation = elevation\n self.timezone = timezone\n self.utcoffset = utcoffset\n\n\nclass Ashrae(db.Model):\n __tablename__ = 'ashrae'\n id = db.Column(db.Integer, primary_key=True)\n nominal_inverter_rating = db.Column(db.Float)\n site_design_temperature = db.Column(db.Float)\n station = db.Column(db.String)\n cities = db.Column(db.PickleType)\n latitudes = db.Column(db.PickleType)\n longitudes = db.Column(db.PickleType)\n distances = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n nominal_inverter_rating,\n site_design_temperature,\n station,\n cities,\n latitudes,\n longitudes,\n distances,\n project_id):\n self.nominal_inverter_rating = nominal_inverter_rating\n self.site_design_temperature = site_design_temperature\n self.station = station\n self.cities = cities\n self.latitudes = latitudes\n self.longitudes = longitudes\n self.distances = distances\n self.project_id = project_id\n\n\nclass ThirtyYearStation(db.Model):\n __tablename__ = 'thirty_year_station'\n id = db.Column(db.Integer, primary_key=True)\n station = db.Column(db.String)\n latitude = db.Column(db.Float)\n longitude = db.Column(db.Float)\n distance = db.Column(db.Float)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n station,\n latitude,\n longitude,\n distance,\n project_id):\n self.station = station\n self.latitude = latitude\n self.longitude = longitude\n self.distance = distance\n self.project_id = project_id\n\n\nclass NCDC2010(db.Model):\n __tablename__ = 'ncdc2010'\n id = db.Column(db.Integer, primary_key=True)\n station = db.Column(db.String)\n cities = db.Column(db.PickleType)\n latitudes = db.Column(db.PickleType)\n longitudes = db.Column(db.PickleType)\n distances = db.Column(db.PickleType)\n scores = db.Column(db.PickleType)\n csr = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n station,\n cities,\n latitudes,\n longitudes,\n distances,\n scores,\n csr,\n project_id):\n self.station = station\n self.cities = cities\n self.latitudes = latitudes\n self.longitudes = longitudes\n self.distances = distances\n self.scores = scores\n self.csr = csr\n self.project_id = project_id\n\n\nclass SMN(db.Model):\n __tablename__ = 'smn'\n id = db.Column(db.Integer, primary_key=True)\n station = db.Column(db.String)\n cities = db.Column(db.PickleType)\n latitudes = db.Column(db.PickleType)\n longitudes = db.Column(db.PickleType)\n distances = db.Column(db.PickleType)\n codes = db.Column(db.PickleType)\n rains = db.Column(db.PickleType)\n temperatures = db.Column(db.PickleType)\n significant_rains = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n station,\n cities,\n latitudes,\n longitudes,\n distances,\n codes,\n rains,\n temperatures,\n significant_rains,\n project_id):\n self.station = station\n self.cities = cities\n self.latitudes = latitudes\n self.longitudes = longitudes\n self.distances = distances\n self.codes = codes\n self.rains = rains\n self.temperatures = temperatures\n self.significant_rains = significant_rains\n self.project_id = project_id\n\n\nclass TMY(db.Model):\n __tablename__ = 'tmy'\n id = db.Column(db.Integer, primary_key=True)\n cities = db.Column(db.PickleType)\n latitudes = db.Column(db.PickleType)\n longitudes = db.Column(db.PickleType)\n types = db.Column(db.PickleType)\n temperatures = db.Column(db.PickleType)\n elevations = db.Column(db.PickleType)\n ghis = db.Column(db.PickleType)\n classes = db.Column(db.PickleType)\n uncertainties = db.Column(db.PickleType)\n dhis = db.Column(db.PickleType)\n distances = db.Column(db.PickleType)\n codes = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n cities,\n latitudes,\n longitudes,\n types,\n temperatures,\n elevations,\n ghis,\n classes,\n uncertanties,\n dhis,\n distances,\n codes,\n project_id):\n self.cities = cities\n self.latitudes = latitudes\n self.longitudes = longitudes\n self.types = types\n self.temperatures = temperatures\n self.elevations = elevations\n self.ghis = ghis\n self.classes = classes\n self.uncertanties = uncertanties\n self.dhis = dhis\n self.distances = distances\n self.codes = codes\n self.project_id = project_id\n\n\n# Irradiance Classes\nclass PSMv3(db.Model):\n __tablename__ = 'psmv3'\n id = db.Column(db.Integer, primary_key=True)\n variability = db.Column(db.Float)\n ghi = db.Column(db.Float)\n tmyghi = db.Column(db.Float)\n dhi = db.Column(db.Float)\n tmydhi = db.Column(db.Float)\n temp = db.Column(db.Float)\n tmytemp = db.Column(db.Float)\n ghi_year = db.Column(db.PickleType)\n dhi_year = db.Column(db.PickleType)\n temp_year = db.Column(db.PickleType)\n n_years = db.Column(db.Integer)\n file = db.Column(db.PickleType)\n tmyfile = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n variability,\n ghi,\n tmyghi,\n dhi,\n tmydhi,\n temp,\n tmytemp,\n ghi_year,\n dhi_year,\n temp_year,\n n_years,\n file,\n tmyfile,\n project_id):\n self.variability = variability\n self.ghi = ghi\n self.tmyghi = tmyghi\n self.dhi = dhi\n self.tmydhi = tmydhi\n self.temp = temp\n self.tmytemp = tmytemp\n self.ghi_year = ghi_year\n self.dhi_year = dhi_year\n self.temp_year = temp_year\n self.n_years = n_years\n self.file = file\n self.tmyfile = tmyfile\n self.project_id = project_id\n\n\n# Sizing Scenarios\nclass Scenario(db.Model):\n __tablename__ = 'scenario'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n scenario_name = db.Column(db.String, unique=True)\n trackers_per_section = db.Column(db.Integer)\n number_of_trackers = db.Column(db.Float)\n number_of_blocks = db.Column(db.Integer)\n modules_per_block = db.Column(db.Integer)\n modules_per_plant = db.Column(db.Integer)\n pvsyst_strings = db.Column(db.Integer)\n MWdc = db.Column(db.Integer)\n MWac = db.Column(db.Integer)\n SR = db.Column(db.Integer)\n interconnection_limit = db.Column(db.Integer)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n name,\n scenario_name,\n trackers_per_section,\n number_of_trackers,\n number_of_blocks,\n modules_per_block,\n modules_per_plant,\n pvsyst_strings,\n MWdc,\n MWac,\n SR,\n interconnection_limit,\n project_id):\n self.name = name\n self.scenario_name = scenario_name\n self.trackers_per_section = trackers_per_section\n self.number_of_trackers = number_of_trackers\n self.number_of_blocks = number_of_blocks\n self.modules_per_block = modules_per_block\n self.modules_per_plant = modules_per_plant\n self.pvsyst_strings = pvsyst_strings\n self.MWdc = MWdc\n self.MWac = MWac\n self.SR = SR\n self.interconnection_limit = interconnection_limit\n self.project_id = project_id\n\n\nclass SolarGIS_TMY(db.Model):\n __tablename__ = 'solargis_tmy'\n id = db.Column(db.Integer, primary_key=True)\n ghi = db.Column(db.Float)\n dhi = db.Column(db.Float)\n temp = db.Column(db.Float)\n hourly = db.Column(db.PickleType)\n daily = db.Column(db.PickleType)\n monthly = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n ghi, dhi, temp,\n hourly, daily, monthly,\n project_id):\n self.ghi = ghi\n self.dhi = dhi\n self.temp = temp\n self.hourly = hourly\n self.daily = daily\n self.monthly = monthly\n self.project_id = project_id\n\n \nclass SolarGIS_Timeseries(db.Model):\n __tablename__ = 'solargis_timeseries'\n id = db.Column(db.Integer, primary_key=True)\n ghi = db.Column(db.Float)\n dhi = db.Column(db.Float)\n temp = db.Column(db.Float)\n hourly = db.Column(db.PickleType)\n daily = db.Column(db.PickleType)\n project_id = db.Column(db.Integer, db.ForeignKey('geocode.id'))\n\n def __init__(self,\n ghi, dhi, temp,\n hourly, daily,\n project_id):\n self.ghi = ghi\n self.dhi = dhi\n self.temp = temp\n self.hourly = hourly\n self.daily = daily\n self.project_id = project_id\n\n\ndb.create_all()\ndb.session.commit()\n","sub_path":"TableConstructor.py","file_name":"TableConstructor.py","file_ext":"py","file_size_in_byte":12045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"517087245","text":"from .resource import BaseResource\n\nclass AlertResource(BaseResource):\n id_params = [\"id\", \"alias\", \"tinyId\"]\n\n #Opsgenie uses inconsisten naming /sigh\n alert_id_params = [\"alertId\", \"alias\"]\n\n def __init__(self, opsgenie_api):\n self.api = opsgenie_api\n self.path = \"/alert\"\n\n def create(self, message, **optional_create_params):\n alert_dict = optional_create_params\n alert_dict[\"message\"] = message\n response_body = self._post(alert_dict)\n return response_body\n\n def update(self, **update_params):\n \"\"\"Update an alert\"\"\"\n if not self.contains_id_param(update_params):\n raise ValueError(\"You must specify one of the identifier parameters: {0}\"\n \" Did you mean to call {1}.create() instead?\".format(\n self.id_params, self.__class__.__name__))\n return self._post(update_params)\n\n def get(self, **get_params):\n \"\"\"Get a singe alert.\"\"\"\n if not self.contains_id_param(get_params):\n raise ValueError(\"You must specify one of the identifier parameters: {0}\"\n \" Did you mean to call {1}.list() instead?\".format(\n self.id_params, self.__class__.__name__))\n return self._get(params=get_params)\n\n def list(self, **optional_params):\n \"\"\"Get a list of alerts.\n\n Unpacks the result for you, returning a list of alerts.\n \"\"\"\n id_param = self.contains_id_param(optional_params)\n if id_param is not None:\n raise ValueError(\"You specified the ID parameter '{0}'. This will cause\"\n \"the API to return a single alert and not a list. Did you mean to\"\n \"call {1}.get() instead?\".format(id_param, self.__class__.__name__))\n alerts_response = self._get(params=optional_params)\n return alerts_response[\"alerts\"]\n\n def assign(self, owner, **params):\n self.raise_no_alert_id(params)\n params[\"owner\"] = owner\n return self._post(params, append_path = \"assign\")\n\n def renotify(self, **params):\n self.raise_no_alert_id(params)\n return self._post(params, append_path = \"renotify\")\n\n def add_recipient(self, recipient, **params):\n self.raise_no_alert_id(params)\n params[\"recipient\"] = recipient\n return self._post(params, append_path = \"recipient\")\n\n def contains_alert_id_param(self, params):\n return self.contains_id_param(params, available=self.alert_id_params)\n\n def contains_id_param(self, params, available=None):\n if available is None:\n available = self.id_params\n for need_param in available:\n if need_param in params:\n return need_param\n return None\n\n def raise_no_alert_id(self, params):\n if not self.contains_alert_id_param(params):\n raise ValueError(\"You must specify one of the available ID params: {0}\".format(\n self.alert_id_params))\n\n","sub_path":"src/opsgenie/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329493992","text":"import requests\nimport re\nimport json\nimport datetime\n\nURLS = [r'https://www.info.uaic.ro/regulamente/', r'https://www.info.uaic.ro/documente-formulare/',\n r'https://www.info.uaic.ro/contact/']\n# BASE_URL = r'https://www.info.uaic.ro/regulamente/'\nfor url in URLS:\n response = requests.get(url, verify=False)\n data = response.text\n\n final_dict = {}\n\n final_dict['date'] = str(datetime.datetime.now())\n final_dict['title'] = re.search(r'class=\"post-title\">([^<]+)<', data).group(1)\n final_dict['content'] = re.search(r'([^$]+?)', data).group(1)\n final_dict['type'] = 'internal'\n\n with open(\"./jsons/{}\".format(final_dict[\"title\"]), \"w\", encoding='utf-8') as f:\n json.dump(final_dict, f, indent=4, ensure_ascii=False)\n f.close()\n\nprint(final_dict)\n\n\n","sub_path":"FII-Student-A4/Back/fii_student/resources/db/anunturi_studenti.py","file_name":"anunturi_studenti.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639397702","text":"import cv2 as cv\n\ndef rescaleFrame(frame, scale=0.75):\n width = int(frame.shape[1] * scale)\n height = int(frame.shape[0] * scale)\n dimensions = (width, height)\n\n return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA)\n\n\nimg = cv.imread('images/wallpaper1.jpg')\ncv.imshow('wallpaper1', img)\ncv.imshow('resizedwallpaper', rescaleFrame(img, scale=0.5))\n\ncv.waitKey(0)","sub_path":"rescaleimg.py","file_name":"rescaleimg.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79401214","text":"import importlib\nimport re\nimport os\n\nfrom mop.azure.utils.create_configuration import change_dir, OPERATIONSPATH\nfrom mop.framework.mopbase import MopBase\n\nclass Execution(MopBase):\n\n def __init__(self):\n super().__init__()\n self.plugins = {}\n\n def load_plugins(self):\n plugins = self.config['PLUGINS']\n for plugin in plugins:\n if re.match('plugin_', plugin, re.IGNORECASE):\n self.plugins[plugin] = self.config['PLUGINS'][plugin]\n\n def run(self, plugin_name):\n plugins = self.config['PLUGINS']\n root_path = self.config[\"DEFAULT\"][\"plugin_root_path\"]\n\n with change_dir(OPERATIONSPATH):\n path = '{}/{}'.format(os.getcwd(), root_path)\n\n for plugin in plugins:\n if re.match('plugin_', plugin, re.IGNORECASE):\n self.plugins[plugin] = self.config['PLUGINS'][plugin]\n\n return path\n","sub_path":"src/mop/azure/plugins/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321691782","text":"# Author: Borja Guanche Sicilia\n# Mail: bg.sicilia@gmail.com\n# Date: 26/04/2021\n# File exponenciacionRapida.py: Implementación del algoritmo de exponenciación rápida.\n\n\ndef exponenciacionRapida(a, b, m, f):\n\n x = 1\n y = a % m\n\n f.write(\"\\n\\n %s ^\"% str(a)+\" %s\" %str(b)+\" (mod %s) \\n\" %str(m));\n f.write(\"\\ny: b: x:\\n\"); f.write(str(y)+\" \"+str(b)+\" \"+str(x)+\"\\n\")\n\n while (b > 0) and (y > 1):\n \n if (b % 2 != 0):\n\n x = (x * y) % m\n b = b - 1\n f.write(\" \"+str(round(b))+\" \"+str(x)+\"\\n\")\n else:\n\n y = (y * y) % m\n b = b / 2\n f.write(str(y)+\" \"+str(round(b))+\"\\n\")\n\n return (x)","sub_path":"Intercambio-de-claves-de-Diffie-Hellman-y-cifrado-de-ElGamal/exponenciacionRapida.py","file_name":"exponenciacionRapida.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"291723501","text":"from bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words, \\\n html_to_markdown\n\n\nclass ImpDali(Store):\n @classmethod\n def categories(cls):\n return [\n 'LightTube',\n 'LightProjector',\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n session = session_with_proxy(extra_args)\n product_urls = []\n page = 1\n\n while True:\n category_url = 'http://www.impdali.cl/iluminacion-led/page/{}/' \\\n ''.format(page)\n\n if page >= 10:\n raise Exception('Page overflow:' + category_url)\n\n soup = BeautifulSoup(session.get(category_url).text, 'html.parser')\n\n containers = soup.findAll('div', 'default_product_display')\n\n if not containers:\n break\n\n for container in containers:\n product_link = container.find('a', 'wpsc_product_title')\n\n product_name = product_link.text.lower()\n\n ptype = None\n\n if 'tubo' in product_name:\n ptype = 'LightTube'\n elif 'proyector' in product_name:\n ptype = 'LightProjector'\n\n if ptype == category:\n product_url = product_link['href']\n product_urls.append(product_url)\n\n page += 1\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n session = session_with_proxy(extra_args)\n soup = BeautifulSoup(session.get(url).text, 'html.parser')\n\n name = soup.find('h1', 'entry-title').text.strip()\n sku = soup.find('input', {'name': 'product_id'})['value'].strip()\n description = html_to_markdown(\n str(soup.find('div', 'product_description')))\n picture_urls = [tag['href'] for tag in soup.findAll('a', 'thickbox')]\n price = Decimal(remove_words(soup.find('span', 'currentprice').text))\n\n price *= Decimal('1.19')\n price = price.quantize(0)\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n -1,\n price,\n price,\n 'CLP',\n sku=sku,\n description=description,\n picture_urls=picture_urls\n )\n\n return [p]\n","sub_path":"storescraper/stores/imp_dali.py","file_name":"imp_dali.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"120630965","text":"#!/usr/bin/env python3\nimport argparse\nimport logging\nimport gc\nimport objgraph\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.client import device_lib\n\n\nimport numpy as np\n\nfrom trainer.ellington_library import EllingtonLibrary, Track\nfrom trainer.audio import Audio, BareTrack\nfrom trainer.generator import LibraryIterator, TrackIterator\nfrom trainer.spectrogram import RangeError\nfrom trainer.model import model_gen\n\ndef get_sample(spect, start, length): \n (h, w) = spect.shape\n end = start + length\n if end >= w: \n raise RangeError(\"Requested sample end %d is beyond the audio length %d\" % (end, w))\n return spect[:, int(start):int(end)]\n\n\n\ndef main(model, audio):\n logging.basicConfig(\n format='%(asctime)s %(levelname)s %(module)s %(lineno)d : %(message)s', level=logging.DEBUG)\n\n # Create the model, print info\n model = keras.models.load_model(model)\n print(model.summary())\n\n # Create the bare track to load spectrogram data from\n track = BareTrack(audio)\n # And create an Audio object from it\n audio = Audio(track)\n audio.load() # Load the data, and compute a spectrogram. \n # audio.plot_spectrogram()\n\n # Get the spectrogram data, and cut off frequencies\n spect = audio.spect[64:320,:]\n (h, w) = spect.shape\n # We want data of shape\n input_w = 1720\n input_h = 256\n\n sixty = 60 * 86\n\n \n samples = [] \n times = [] \n for i in range(sixty, w - input_w, 43): \n try:\n sample = get_sample(spect, i, input_w)\n\n maxv = np.max(np.abs(sample))\n data = np.reshape(sample, (input_h, input_w, 1)) / maxv\n times.append(i / 86)\n samples.append(data)\n except RangeError:\n print(\"Random range was invalid - continuing to try again\")\n \n print(\"Predicting batch\")\n results = model.predict_on_batch(np.array(samples)).flatten().tolist()\n\n pairs = zip(times, results)\n\n print(\"Results: [{}]\".format( \"\\n \".join('(%.2f, %.2f)' % (t, (400 * r)) for (t, r) in pairs) ))\n print(\"Mean: %.2f\" % (np.mean(results) * 400))\n print(\"Stddev: %.2f\" % (np.std(results) * 400))\n\n print(\"Geomean: %.2f\" % ((np.array(results).prod()**(1.0/len(results))) * 400))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', required=True, help='The model to use for inference')\n parser.add_argument('--audio', required=True, help='The audio file to analyse')\n args = parser.parse_args()\n arguments = args.__dict__\n main(**arguments)\n","sub_path":"trainer/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132368034","text":"import pytest\n\n\n@pytest.fixture(scope=\"module\")\ndef input_data():\n input_data = {1: {'Python let you know': 2.5, 'snakes on a plane': 3.5, 'just my luck': 3.0, 'superman returns': 3.5,\n 'you,me and dupree': 2.5, 'the night listener': 3.0},\n 2: {'Python let you know': 3.0, 'snakes on a plane': 3.5, 'just my luck': 1.5, 'superman returns': 5.0,\n 'you,me and dupree': 3.5, 'the night listener': 3.0},\n 3: {'Python let you know': 2.5, 'snakes on a plane': 3.0, 'superman returns': 3.5,\n 'the night listener': 4.0},\n 4: {'snakes on a plane': 3.5, 'just my luck': 3.0, 'superman returns': 4.0,\n 'the night listener': 4.5},\n 5: {'Python let you know': 3.0, 'snakes on a plane': 4.0, 'just my luck': 2.0, 'superman returns': 3.0,\n 'you,me and dupree': 2.0, 'the night listener': 3.0},\n 6: {'Python let you know': 3.0, 'snakes on a plane': 4.0, 'superman returns': 5.0, 'you,me and dupree': 3.5,\n 'the night listener': 3.0},\n 7: {'snakes on a plane': 4.5, 'superman returns': 4.0, 'you,me and dupree': 1.0},\n 8: {'abc': 1.2}}\n\n return input_data\n","sub_path":"user_based_collaborative_filtering/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438188838","text":"#!/usr/bin/python3\nimport requests\nimport json\nimport os\n\nimport appdirs\n\nclass ShortcutExporter:\n def __init__(self):\n self.BASE_URL = 'https://api.app.shortcut.com/api/v2'\n self.TOKEN = os.environ.get('SHORTCUT_API_TOKEN')\n self.DATA_DIR = appdirs.user_data_dir('shortcut')\n os.makedirs(self.DATA_DIR, exist_ok=True)\n self.DEBUG = False\n\n def get(self, endpoint, params=None):\n if params is None:\n params = {}\n params['token'] = self.TOKEN\n headers = {'Content-Type': 'application/json'}\n if self.DEBUG:\n print('curl -X GET -H \"Content-Type: application/json\" \\'{}/{}?{}\\''.format(self.BASE_URL, endpoint.lstrip('/'), '&'.join('{}={}'.format(k, v) for k, v in params.items())))\n r = requests.get('{}/{}'.format(self.BASE_URL, endpoint.lstrip('/')), params=params, headers=headers)\n r.raise_for_status()\n return r\n\n def get_story(self, story_id, params=None):\n \"\"\"Get Story returns information about a chosen Story.\"\"\"\n if params is None:\n params = {}\n return self.get('stories/{}'.format(str(story_id).lstrip('/')), params).json()\n\n def search_stories(self, params):\n \"\"\"Search Stories lets you search Stories based on desired parameters.\"\"\"\n return self.get('search/stories', params).json()['data']\n\n def export(self):\n story_ids = [x['id'] for x in self.search_stories({\"query\": \"is:story\"})]\n fields = ['categories', 'epic-workflow', 'epics', 'files', 'labels', 'linked-files', 'members',\n 'milestones', 'projects', 'repositories', 'stories', 'teams', 'workflows']\n\n for field in fields:\n filename = os.path.join(self.DATA_DIR, field + '.json')\n\n if field == 'stories':\n resp = [self.get_story(x) for x in story_ids]\n else:\n resp = self.get(field).json()\n with open(filename, 'w') as f:\n print(filename)\n f.write(json.dumps(resp))\n\n\nif __name__ == '__main__':\n exporter = ShortcutExporter()\n exporter.export()\n","sub_path":"exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"144299622","text":"import argparse\nimport pickle\n\nimport numpy as np\n\nfrom nasbench_analysis.search_spaces.search_space_1 import SearchSpace1\nfrom nasbench_analysis.search_spaces.search_space_2 import SearchSpace2\nfrom nasbench_analysis.search_spaces.search_space_3 import SearchSpace3\n\nimport json\nimport logging\nimport os\nimport random\nimport time\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torchvision.datasets as dset\nfrom torch.autograd import Variable\n\nfrom optimizers.darts import utils\nfrom optimizers.darts.genotypes import PRIMITIVES\nfrom nasbench_analysis.utils import NasbenchWrapper\n# from optimizers.pc_darts.model_search import PCDARTSNetwork as Network\nfrom optimizers.darts.model_search import Network\n\n\nclass AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n\nclass DartsWrapper:\n def __init__(self, save_path, seed, batch_size, grad_clip, epochs, num_intermediate_nodes, search_space, cutout,\n resume_iter=None, init_channels=16):\n args = {}\n args['data'] = '../data'\n args['epochs'] = epochs\n args['learning_rate'] = 0.025\n args['batch_size'] = batch_size\n args['learning_rate_min'] = 0.001\n args['momentum'] = 0.9\n args['weight_decay'] = 3e-4\n args['init_channels'] = init_channels\n # Adapted to nasbench\n args['layers'] = 9\n args['drop_path_prob'] = 0.3\n args['grad_clip'] = grad_clip\n args['train_portion'] = 0.5\n args['seed'] = seed\n args['log_interval'] = 50\n args['save'] = save_path\n args['gpu'] = 0\n args['cuda'] = False\n args['cutout'] = cutout\n args['cutout_length'] = 16\n args['report_freq'] = 50\n args['output_weights'] = True\n args['steps'] = num_intermediate_nodes\n args['search_space'] = search_space.search_space_number\n self.search_space = search_space\n args = AttrDict(args)\n self.args = args\n\n # Dump the config of the run, but if only if it doesn't yet exist\n config_path = os.path.join(args.save, 'config.json')\n if not os.path.exists(config_path):\n with open(config_path, 'w') as fp:\n json.dump(args.__dict__, fp)\n self.seed = seed\n\n np.random.seed(args.seed)\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n # torch.cuda.set_device(args.gpu)\n cudnn.benchmark = False\n cudnn.enabled = True\n cudnn.deterministic = True\n # torch.cuda.manual_seed_all(args.seed)\n\n train_transform, valid_transform = utils._data_transforms_cifar10(args)\n train_data = dset.CIFAR10(root=args.data, train=True, download=True, transform=train_transform)\n\n num_train = len(train_data)\n indices = list(range(num_train))\n split = int(np.floor(args.train_portion * num_train))\n\n self.train_queue = torch.utils.data.DataLoader(\n train_data, batch_size=args.batch_size,\n sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]),\n pin_memory=True, num_workers=0, worker_init_fn=np.random.seed(args.seed))\n\n self.valid_queue = torch.utils.data.DataLoader(\n train_data, batch_size=args.batch_size,\n sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:num_train]),\n pin_memory=True, num_workers=0, worker_init_fn=np.random.seed(args.seed))\n\n _, test_transform = utils._data_transforms_cifar10(args)\n test_data = dset.CIFAR10(root=args.data, train=False, download=True, transform=test_transform)\n self.test_queue = torch.utils.data.DataLoader(\n test_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=2)\n\n self.train_iter = iter(self.train_queue)\n self.valid_iter = iter(self.valid_queue)\n\n self.steps = 0\n self.epochs = 0\n self.total_loss = 0\n self.start_time = time.time()\n criterion = nn.CrossEntropyLoss()\n # criterion = criterion.cuda()\n self.criterion = criterion\n\n\n\n model = Network(args.init_channels, 10, args.layers, self.criterion, output_weights=args.output_weights,\n search_space=search_space, steps=args.steps)\n\n # model = model.cuda()\n self.model = model\n\n logging.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n\n optimizer = torch.optim.SGD(\n self.model.parameters(),\n args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n self.optimizer = optimizer\n\n self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, float(args.epochs), eta_min=args.learning_rate_min)\n\n if resume_iter is not None:\n self.steps = resume_iter\n self.epochs = int(resume_iter / len(self.train_queue))\n logging.info(\"Resuming from epoch %d\" % self.epochs)\n self.objs = utils.AvgrageMeter()\n self.top1 = utils.AvgrageMeter()\n self.top5 = utils.AvgrageMeter()\n for i in range(self.epochs):\n self.scheduler.step()\n\n size = 0\n for p in model.parameters():\n size += p.nelement()\n logging.info('param size: {}'.format(size))\n\n total_params = sum(x.data.nelement() for x in model.parameters())\n logging.info('Args: {}'.format(args))\n logging.info('Model total parameters: {}'.format(total_params))\n\n def train_batch(self, arch):\n args = self.args\n if self.steps % len(self.train_queue) == 0:\n self.scheduler.step()\n self.objs = utils.AvgrageMeter()\n self.top1 = utils.AvgrageMeter()\n self.top5 = utils.AvgrageMeter()\n lr = self.scheduler.get_lr()[0]\n\n weights = self.get_weights_from_arch(arch)\n self.set_arch_model_weights(weights)\n\n step = self.steps % len(self.train_queue)\n input, target = next(self.train_iter)\n\n self.model.train()\n n = input.size(0)\n\n # input = input.cuda()\n # target = target.cuda(non_blocking=True)\n\n # get a random_ws minibatch from the search queue with replacement\n self.optimizer.zero_grad()\n logits = self.model(input, discrete=True)\n loss = self.criterion(logits, target)\n\n loss.backward()\n nn.utils.clip_grad_norm(self.model.parameters(), args.grad_clip)\n self.optimizer.step()\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n self.objs.update(loss.data.item(), n)\n self.top1.update(prec1.data.item(), n)\n self.top5.update(prec5.data.item(), n)\n\n if step % args.report_freq == 0:\n logging.info('train %03d %e %f %f', step, self.objs.avg, self.top1.avg, self.top5.avg)\n\n self.steps += 1\n if self.steps % len(self.train_queue) == 0:\n # Save the model weights\n self.epochs += 1\n self.train_iter = iter(self.train_queue)\n valid_err = self.evaluate(arch)\n logging.info('epoch %d | train_acc %f | valid_acc %f' % (self.epochs, self.top1.avg, 1 - valid_err))\n self.save(epoch=self.epochs)\n\n def evaluate(self, arch, split=None):\n # Return error since we want to minimize obj val\n logging.info(arch)\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n\n weights = self.get_weights_from_arch(arch)\n self.set_arch_model_weights(weights)\n\n self.model.eval()\n\n if split is None:\n n_batches = 10\n else:\n n_batches = len(self.valid_queue)\n\n for step in range(n_batches):\n try:\n input, target = next(self.valid_iter)\n except Exception as e:\n logging.info('looping back over valid set')\n self.valid_iter = iter(self.valid_queue)\n input, target = next(self.valid_iter)\n # input = input.cuda()\n # target = target.cuda(non_blocking=True)\n\n logits = self.model(input, discrete=True)\n loss = self.criterion(logits, target)\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n objs.update(loss.data.item(), n)\n top1.update(prec1.data.item(), n)\n top5.update(prec5.data.item(), n)\n\n if step % self.args.report_freq == 0:\n logging.info('valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n\n return 1 - 0.01 * top1.avg\n\n def evaluate_test(self, arch, split=None, discrete=False, normalize=True):\n # Return error since we want to minimize obj val\n logging.info(arch)\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n\n weights = self.get_weights_from_arch(arch)\n self.set_arch_model_weights(weights)\n\n self.model.eval()\n\n if split is None:\n n_batches = 10\n else:\n n_batches = len(self.test_queue)\n\n for step in range(n_batches):\n try:\n input, target = next(self.test_iter)\n except Exception as e:\n logging.info('looping back over valid set')\n self.test_iter = iter(self.test_queue)\n input, target = next(self.test_iter)\n # input = input.cuda()\n # target = target.cuda(non_blocking=True)\n\n logits = self.model(input, discrete=discrete, normalize=normalize)\n loss = self.criterion(logits, target)\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n objs.update(loss.data.item(), n)\n top1.update(prec1.data.item(), n)\n top5.update(prec5.data.item(), n)\n\n if step % self.args.report_freq == 0:\n logging.info('test %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n\n return 1 - 0.01 * top1.avg\n\n def save(self, epoch):\n utils.save(self.model, os.path.join(self.args.save, 'one_shot_model_{}.pt'.format(epoch)))\n\n def load(self, epoch=None):\n if epoch is not None:\n model_obj_path = os.path.join(self.args.save, 'one_shot_model_{}.obj'.format(epoch))\n if os.path.exists(model_obj_path):\n utils.load(self.model, model_obj_path)\n else:\n model_pt_path = os.path.join(self.args.save, 'one_shot_model_{}.pt'.format(epoch))\n utils.load(self.model, model_pt_path)\n else:\n utils.load(self.model, os.path.join(self.args.save, 'weights.obj'))\n\n def get_weights_from_arch(self, arch):\n adjacency_matrix, node_list = arch\n num_ops = len(PRIMITIVES)\n\n # Assign the sampled ops to the mixed op weights.\n # These are not optimized\n alphas_mixed_op = Variable(torch.zeros(self.model._steps, num_ops), requires_grad=False)\n for idx, op in enumerate(node_list):\n alphas_mixed_op[idx][PRIMITIVES.index(op)] = 1\n\n # Set the output weights\n alphas_output = Variable(torch.zeros(1, self.model._steps + 1), requires_grad=False)\n for idx, label in enumerate(list(adjacency_matrix[:, -1][:-1])):\n alphas_output[0][idx] = label\n\n # Initialize the weights for the inputs to each choice block.\n if type(self.model.search_space) == SearchSpace1:\n begin = 3\n else:\n begin = 2\n alphas_inputs = [Variable(torch.zeros(1, n_inputs), requires_grad=False) for n_inputs in\n range(begin, self.model._steps + 1)]\n for alpha_input in alphas_inputs:\n connectivity_pattern = list(adjacency_matrix[:alpha_input.shape[1], alpha_input.shape[1]])\n for idx, label in enumerate(connectivity_pattern):\n alpha_input[0][idx] = label\n\n # Total architecture parameters\n arch_parameters = [\n alphas_mixed_op,\n alphas_output,\n *alphas_inputs\n ]\n return arch_parameters\n\n def set_arch_model_weights(self, weights):\n self.model._arch_parameters = weights\n\n def sample_arch(self):\n adjacency_matrix, op_list = self.search_space.sample(with_loose_ends=True, upscale=False)\n return adjacency_matrix, op_list\n\n\n\ndef correlation_with_weights(model_path, config, epoch):\n if config['search_space'] == '1':\n search_space = SearchSpace1()\n elif config['search_space'] == '2':\n search_space = SearchSpace2()\n elif config['search_space'] == '3':\n search_space = SearchSpace3()\n else:\n raise ValueError('Unknown search space')\n model = DartsWrapper(save_path=model_path, seed=0, batch_size=128, grad_clip=5, epochs=200,\n num_intermediate_nodes=search_space.num_intermediate_nodes, search_space=search_space,\n cutout=False)\n if 'random_ws' in model_path:\n discrete = True\n normalize = False\n else:\n discrete = False\n normalize = True\n\n model.load(epoch=epoch)\n nb_test_errors = []\n nb_valid_errors = []\n one_shot_test_errors = []\n for adjacency_matrix, ops, model_spec in search_space.generate_search_space_without_loose_ends():\n if str(config['search_space']) == '1' or str(config['search_space']) == '2':\n adjacency_matrix_ss = np.delete(np.delete(adjacency_matrix, -2, 0), -2, 0)\n # Remove input, output and 5th node\n ops_ss = ops[1:-2]\n elif str(config['search_space']) == '3':\n adjacency_matrix_ss = adjacency_matrix\n # Remove input and output node\n ops_ss = ops[1:-1]\n else:\n raise ValueError('Unknown search space')\n\n one_shot_test_error = model.evaluate_test((adjacency_matrix_ss, ops_ss), split='test', discrete=discrete,\n normalize=normalize)\n one_shot_test_errors.extend(np.repeat(one_shot_test_error, 3))\n # Query NASBench\n data = nasbench.query(model_spec)\n nb_test_errors.extend([1 - item['test_accuracy'] for item in data])\n nb_valid_errors.extend([1 - item['validation_accuracy'] for item in data])\n print('NB', nb_test_errors[-1], 'OS', one_shot_test_errors[-1], 'weights', model.model.arch_parameters())\n\n correlation = np.corrcoef(one_shot_test_errors, nb_test_errors)[0, -1]\n return correlation, nb_test_errors, nb_valid_errors, one_shot_test_errors\n\n\ndef eval_directory_on_epoch(path, epoch):\n \"\"\"Evaluates all one-shot architecture methods in the directory.\"\"\"\n # Read in config\n with open(os.path.join(path, 'config.json')) as fp:\n config = json.load(fp)\n correlations = []\n nb_test_errors, nb_valid_errors, one_shot_test_errors = [], [], []\n correlation, nb_test_error, nb_valid_error, one_shot_test_error = \\\n correlation_with_weights(model_path=path,\n config=config,\n epoch=epoch)\n correlations.append(correlation)\n nb_test_errors.append(nb_test_error)\n nb_valid_error.append(nb_valid_error)\n one_shot_test_errors.append(one_shot_test_error)\n\n with open(os.path.join(path, 'correlation_{}.obj'.format(epoch)), 'wb') as fp:\n pickle.dump(correlations, fp)\n\n with open(os.path.join(path, 'nb_test_errors_{}.obj'.format(epoch)), 'wb') as fp:\n pickle.dump(nb_test_errors, fp)\n\n with open(os.path.join(path, 'nb_valid_errors_{}.obj'.format(epoch)), 'wb') as fp:\n pickle.dump(nb_valid_errors, fp)\n\n with open(os.path.join(path, 'one_shot_test_errors_{}.obj'.format(epoch)), 'wb') as fp:\n pickle.dump(one_shot_test_errors, fp)\n\n\ndef understanding(model_path):\n with open(os.path.join(model_path, 'config.json')) as fp:\n config = json.load(fp)\n\n config['search_space'] = '3'\n\n if config['search_space'] == '1':\n search_space = SearchSpace1()\n elif config['search_space'] == '2':\n search_space = SearchSpace2()\n elif config['search_space'] == '3':\n search_space = SearchSpace3()\n else:\n raise ValueError('Unknown search space')\n model = DartsWrapper(save_path=model_path, seed=0, batch_size=128, grad_clip=5, epochs=200,\n num_intermediate_nodes=search_space.num_intermediate_nodes, search_space=search_space,\n cutout=False)\n\n for adjacency_matrix, ops, model_spec in search_space.generate_search_space_without_loose_ends():\n if str(config['search_space']) == '1' or str(config['search_space']) == '2':\n adjacency_matrix_ss = np.delete(np.delete(adjacency_matrix, -2, 0), -2, 0)\n # Remove input, output and 5th node\n ops_ss = ops[1:-2]\n elif str(config['search_space']) == '3':\n adjacency_matrix_ss = adjacency_matrix\n # Remove input and output node\n ops_ss = ops[1:-1]\n else:\n raise ValueError('Unknown search space')\n\n arch_parameters = model.get_weights_from_arch((adjacency_matrix_ss, ops_ss))\n\n\n acces = []\n means = []\n variances = []\n maximum = []\n minimum = []\n ranges = []\n L1 = []\n L2 = []\n\n data = nasbench.query(model_spec)\n\n print(data)\n\n a = model.model.extract_sub(arch_parameters[0]).state_dict()\n keys = [key for key in a if\n 'bn' not in key and 'se' not in key and 'classifier' not in key and 'weight' in key and len(\n a[key].shape) == 4]\n\n acces.append()\n\n weights_list = [a[key].cpu().numpy() for key in keys]\n means.append(np.mean([np.mean(weights) for weights in weights_list]))\n variances.append(np.mean([np.var(weights) for weights in weights_list]))\n maximum.append(np.mean([np.max(weights) for weights in weights_list]))\n minimum.append(np.mean([np.min(weights) for weights in weights_list]))\n ranges.append(np.mean([np.max(weights) - np.min(weights) for weights in weights_list]))\n L2.append(np.mean([np.linalg.norm(weights) for weights in weights_list]))\n L1.append(np.mean([np.abs(weights).mean() for weights in weights_list]))\n\n\n print(\"arch parameters:\")\n print(arch_parameters)\n print(\"model spec\")\n print(model_spec.matrix)\n print(model_spec.ops)\n # print('adjacency_matrix_ss:')\n # print(adjacency_matrix_ss)\n # print('ops_ss:')\n # print(ops_ss)\n print()\n print(model.model)\n\ndef main():\n understanding(args.model_path)\n # Load NASBench\n # eval_directory_on_epoch(args.model_path, args.epoch)\n\n\nparser = argparse.ArgumentParser(\"correlation_analysis\")\nparser.add_argument('--data', type=str, default='../data', help='location of the darts corpus')\nparser.add_argument('--model_path', default=\"/Users/liqi17thu/Desktop/darts/search_space_1/search-baseline-20200623-134823-0-1\",\n help='Path to where the models are stored.')\nparser.add_argument('--epoch', type=int, help='Epoch', default=108)\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n nasbench = NasbenchWrapper('/Users/liqi17thu/Documents/GitHub/nasbench/nasbench_full.tfrecord')\n main()\n","sub_path":"nasbench_analysis/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":19559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"551367159","text":"from typing import List\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nINPUT_OPTION = 'USER_ENTERED'\nSCOPES = ['https://spreadsheets.google.com/feeds']\n\n\nclass Sheet:\n\n def __init__(self, service_account_file: str, spreadsheet_id: str):\n\n creds = \\\n ServiceAccountCredentials\\\n .from_json_keyfile_name(service_account_file, SCOPES)\n\n client = gspread.authorize(creds)\n\n self.spreadsheet = client.open_by_key(spreadsheet_id)\n\n def get_worksheets(self):\n\n return self.spreadsheet.worksheets()\n\n def get_values(self, range_: str):\n\n # The API sometimes return None, when that happens set value\n # to an empty list.\n values = self.spreadsheet.values_get(range_).get('values') or []\n\n for [value] in values:\n yield value\n\n def append(self, range_: str, request_body: List[list]):\n\n self.spreadsheet.values_append(\n range_,\n params={'valueInputOption': INPUT_OPTION},\n body={'values': request_body})\n\n def update(self, range_: str, request_body: List[list]):\n\n self.spreadsheet.values_update(\n range_,\n params={'valueInputOption': INPUT_OPTION},\n body={'values': request_body})\n\n def sort(self, sheet_name: str, column: int = 0, order: str = 'ASCENDING'):\n \"\"\"Sort the values of the given sheet name.\n\n Args:\n sheet_name: The name of the sheet to be sorted.\n column: The column of the sheet where the sort should\n be applied to.\n order: The order of the data on sort. Supported values\n are the following:\n - ASCENDING\n - DESCENDING\n - SORT_ORDER_UNSPECIFIED\n \"\"\"\n\n sheet_id = self.spreadsheet.worksheet(sheet_name).id\n\n request_body = [{\n 'sortRange': {\n 'range': {\n 'sheetId': sheet_id,\n 'startRowIndex': 1 # exclude headers\n },\n 'sortSpecs': [\n {\n 'dimensionIndex': column,\n 'sortOrder': order\n }\n ]\n }\n }]\n\n self.spreadsheet.batch_update(\n body={'requests': request_body})\n","sub_path":"libs/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236016908","text":"from Bio import Phylo as phy\nfrom io import StringIO as stio\nimport multiprocessing\nimport time\nst = time.time()\nwith open(\"D:/Download/rosalind_sptd.txt\",mode='r') as f:\n taxas = f.readline().strip('\\n').split()\n tree_texta = f.readline().strip('\\n')[:-1]\n tree_textb = f.readline().strip('\\n')[:-1]\n\ndef splitree(tree):\n #print(tree)\n terminal = tree.get_terminals()\n internal = tree.get_nonterminals()\n n = len(internal) ; all_pos = int(n*(n-1)/2) ; count = 1\n ret = []\n res = set()\n for i in range(len(internal)):\n for j in range(i+1,len(internal)):\n print(\"dealing with {}/{}\".format(count,all_pos)) ; count+=1\n clade0 = internal[i]\n clade1 = internal[j]\n route = len(clade0.get_path(clade1)) if clade0.get_path(clade1) else 99\n if route != 1: continue \n for ter in terminal:\n if clade0 not in tree.trace(clade1,ter):\n ret.append(taxas.index(ter.name))\n if len(ret) <= (len(taxas)//2):\n res.add(''.join(map(str,sorted(ret))))\n else:\n rett = [i for i in range(len(taxas)) if i not in ret]\n res.add(''.join(map(str,sorted(rett))))\n return res\n\nif __name__ == \"__main__\":\n with multiprocessing.Pool(2) as p:\n treea = phy.read(stio(tree_texta),format='newick')\n treeb = phy.read(stio(tree_textb),format='newick')\n A,B = p.map(splitree,[treea,treeb])\n x = len(A&B)\n print(\"Used %s\" %(time.time()-st))\n print(2*(len(taxas)-3)-2*x)","sub_path":"Phylogeny/Phylogeny Comparison with Split Distance-try01.py","file_name":"Phylogeny Comparison with Split Distance-try01.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423954955","text":"from core.helpers import pad_title, get_pref\nfrom core.plugin import ART, NAME, ICON, PLUGIN_VERSION\nfrom interface.sync_menu import SyncMenu\n\n\n@handler('/applications/trakttv', NAME, thumb=ICON, art=ART)\ndef MainMenu():\n oc = ObjectContainer(no_cache=True)\n\n if not get_pref('valid'):\n oc.add(DirectoryObject(\n key='/applications/trakttv',\n title=L(\"Error: Authentication failed\"),\n ))\n\n oc.add(DirectoryObject(\n key=Callback(SyncMenu),\n title=L(\"Sync\"),\n summary=L(\"Sync the Plex library with Trakt.tv\")\n ))\n\n oc.add(DirectoryObject(\n key=Callback(AboutMenu),\n title=L(\"About\")\n ))\n\n oc.add(PrefsObject(\n title=\"Preferences\",\n summary=\"Configure how to connect to Trakt.tv\",\n thumb=R(\"icon-preferences.png\")\n ))\n\n return oc\n\n\n@route('/applications/trakttv/about')\ndef AboutMenu():\n oc = ObjectContainer(title2=\"About\")\n\n oc.add(DirectoryObject(\n key=Callback(AboutMenu),\n title=pad_title(\"Version: %s\" % PLUGIN_VERSION)\n ))\n\n return oc\n","sub_path":"Trakttv.bundle/Contents/Code/interface/main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310199112","text":"#taken from https://victorzhou.com/blog/keras-neural-network-tutorial/\n\n# The full neural network code!\n###############################\nimport numpy as np\nimport mnist\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import to_categorical\n\ntrain_images = mnist.train_images()\ntrain_labels = mnist.train_labels()\ntest_images = mnist.test_images()\ntest_labels = mnist.test_labels()\n\n# Normalize the images.\ntrain_images = (train_images / 255) - 0.5\ntest_images = (test_images / 255) - 0.5\n\n\n# Flatten the images.\ntrain_images = train_images.reshape((-1, 784))\ntest_images = test_images.reshape((-1, 784))\n\n# Build the model.\nmodel = Sequential([\n Dense(256, activation='relu', input_shape=(784,)),\n Dense(128, activation='relu', input_shape=(784,)),\n Dense(10, activation='softmax'),\n #Line below helps with overfitting AKA regualrization Rate\n keras.layers.Dropout(rate =0.2)\n])\n\n# Compile the model.\nmodel.compile(\n optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n)\n\n# Train the model.\nmodel.fit(\n train_images,\n to_categorical(train_labels),\n epochs=5,\n batch_size=10,\n)\n\n# Evaluate the model.\nmodel.evaluate(\n test_images,\n to_categorical(test_labels)\n)\n\n# Save the model to disk.\n#model.save_weights('model.h5')\n\n# Load the model from disk later using:\nmodel.load_weights('model.h5')\n\n# Predict on the first 5 test images.\npredictions = model.predict(test_images[:5])\n\n# Print our model's predictions.\nprint(np.argmax(predictions, axis=1)) # [7, 2, 1, 0, 4]\n\n# Check our predictions against the ground truths.\nprint(test_labels[:5]) # [7, 2, 1, 0, 4]","sub_path":"Python/Projects_found_Online/Neural Network with Keras.py","file_name":"Neural Network with Keras.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"392247956","text":"import torch\nimport torch.nn as nn\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # Backbone:\n # in_channel, out_channel, kernel_size, stride, padding\n # block 1\n self.conv1_1 = nn.Conv2d(1, 8, 5, 2, 0)\n self.prelu1_1 = nn.PReLU()\n # block 2\n self.conv2_1 = nn.Conv2d(8, 16, 3, 1, 0)\n self.prelu2_1 = nn.PReLU()\n self.conv2_2 = nn.Conv2d(16, 16, 3, 1, 0)\n self.prelu2_2 = nn.PReLU()\n # block 3\n self.conv3_1 = nn.Conv2d(16, 24, 3, 1, 0)\n self.prelu3_1 = nn.PReLU()\n self.conv3_2 = nn.Conv2d(24, 24, 3, 1, 0)\n self.prelu3_2 = nn.PReLU()\n # block 4\n self.conv4_1 = nn.Conv2d(24, 40, 3, 1, 1)\n self.prelu4_1 = nn.PReLU()\n # points branch\n self.conv4_2 = nn.Conv2d(40, 80, 3, 1, 1)\n self.prelu4_2 = nn.PReLU()\n self.ip1 = nn.Linear(4 * 4 * 80, 128)\n self.preluip1 = nn.PReLU()\n self.ip2 = nn.Linear(128, 128)\n self.preluip2 = nn.PReLU()\n self.ip3 = nn.Linear(128, 42)\n # classification branch\n self.conv4_2_cls = nn.Conv2d(40, 80, 3, 1, 1)\n self.prelu4_2_cls = nn.PReLU()\n self.ip1_cls = nn.Linear(4 * 4 * 80, 128)\n self.preluip1_cls = nn.PReLU()\n self.ip2_cls = nn.Linear(128, 128)\n self.preluip2_cls = nn.PReLU()\n self.ip3_cls = nn.Linear(128, 2)\n # self.face_score = nn.Sigmoid()\n # common used\n self.ave_pool = nn.AvgPool2d(2, 2, ceil_mode=True)\n\n def forward(self, x):\n # block 1\n # print('x input shape: ', x.shape)\n x = self.prelu1_1(self.conv1_1(x))\n x = self.ave_pool(x)\n # print('x after block1 and pool shape should be 32x8x27x27: ', x.shape) # good\n # block 2\n x = self.prelu2_1(self.conv2_1(x))\n # print('b2: after conv2_1 and prelu shape should be 32x16x25x25: ', x.shape) # good\n x = self.prelu2_2(self.conv2_2(x))\n # print('b2: after conv2_2 and prelu shape should be 32x16x23x23: ', x.shape) # good\n x = self.ave_pool(x)\n # print('x after block2 and pool shape should be 32x16x12x12: ', x.shape)\n # block 3\n x = self.prelu3_1(self.conv3_1(x))\n # print('b3: after conv3_1 and pool shape should be 32x24x10x10: ', x.shape)\n x = self.prelu3_2(self.conv3_2(x))\n # print('b3: after conv3_2 and pool shape should be 32x24x8x8: ', x.shape)\n x = self.ave_pool(x)\n # print('x after block3 and pool shape should be 32x24x4x4: ', x.shape)\n # block 4\n x = self.prelu4_1(self.conv4_1(x))\n # print('x after conv4_1 and pool shape should be 32x40x4x4: ', x.shape)\n\n # points branch\n ip = self.prelu4_2(self.conv4_2(x))\n # print('pts: ip3 after conv4_2 and pool shape should be 32x80x4x4: ', ip.shape)\n # print(type(ip))\n # ip3 = ip3.view(-1, 4 * 4 * 80)\n ip = torch.flatten(ip)\n # print('ip3 flatten shape should be 32x1280: ', ip.shape)\n ip = self.preluip1(self.ip1(ip))\n # print('ip3 after ip1 shape should be 32x128: ', ip.shape)\n ip = self.preluip2(self.ip2(ip))\n # print('ip3 after ip2 shape should be 32x128: ', ip.shape)\n ip = self.ip3(ip)\n # print('ip3 after ip3 shape should be 32x42: ', ip.shape)\n ip = ip.view(-1, 21, 2)\n\n # classification branch\n # print(x.size())\n ip_cls = self.prelu4_2(self.conv4_2_cls(x))\n # print('pts: ip3 after conv4_2 and pool shape should be 32x80x4x4: ', ip.shape)\n ip_cls = torch.flatten(ip_cls)\n # print('ip3 flatten shape should be 32x1280: ', ip_cls.shape)\n ip_cls = self.preluip1_cls(self.ip1_cls(ip_cls))\n # print('ip3 after ip1 shape should be 32x128: ', ip_cls.shape)\n ip_cls = self.preluip2_cls(self.ip2_cls(ip_cls))\n # print('ip3 after ip2 shape should be 32x128: ', ip_cls.shape)\n ip_cls = self.ip3_cls(ip_cls)\n # print('ip3 after ip3 shape should be 32x2: ', ip_cls.shape)\n # ip_cls = self.face_score(ip_cls)\n # print('face_score after ip3 shape should be 32x42: ', ip_cls.shape)\n # output = torch.cat((ip,ip_cls),1)\n # print(output.shape)\n\n return ip, ip_cls\n\n\n# ResNet18 oriented to this project\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n # Figure5(×ó) Block\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.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = 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 identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, layers=[2, 2, 2, 2], num_classes=[2, 42], zero_init_residual=False): # num_classes:[42,2]\n super(ResNet, self).__init__()\n\n # self.inplanes = 64\n self.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False) # Change input channel to 1\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n\n self.layer1 = self._make_layer(BasicBlock, 64, 64, layers[0], stride=1)\n self.layer2 = self._make_layer(BasicBlock, 64, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(BasicBlock, 128, 256, layers[2], stride=2)\n\n # layers for landmarks branch\n self.layer4 = self._make_layer(BasicBlock, 256, 512, layers[3], stride=2)\n self.fc = nn.Linear(512, num_classes[1])\n\n # layers for classification branch\n self.layer4_cls = self._make_layer(BasicBlock, 256, 512, layers[3], stride=2)\n self.fc_cls = nn.Linear(512, num_classes[0])\n\n # common use\n # self.flatten = Flatten()\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, inplanes, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or inplanes != planes:\n downsample = nn.Sequential(\n conv1x1(inplanes, planes, stride),\n nn.BatchNorm2d(planes),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample))\n # self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(planes, 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 # print('shape of x in layer3', x.size())\n # branch for landmarks\n pts = self.layer4(x)\n # print('shape of pts in layer4', pts.size())\n pts = self.avgpool(pts)\n ##print('shape of pts in avgpool', pts.size())\n pts = torch.flatten(pts, 1)\n # print('shape of pts in flatten', pts.size())\n pts = self.fc(pts)\n # print('shape of pts in fc', pts.size())\n pts = pts.view(-1, 21, 2)\n # print('shape of pts in view', pts.size())\n\n # branch for classification\n # self.inplanes = 256\n # print('shape of x in layer3', x.size())\n cls = self.layer4_cls(x)\n # print('shape of pts in layer4', pts.size())\n cls = self.avgpool(cls)\n # print('shape of pts in avgpool', pts.size())\n cls = torch.flatten(cls, 1)\n # print('shape of pts in flatten', pts.size())\n cls = self.fc_cls(cls)\n # print('shape of pts in fc', pts.size())\n return pts, cls\n","sub_path":"project II/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":9189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"119684714","text":"\"\"\"\nCopyright (c) 2018 Ewan Barr \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport logging\nimport socket\nimport errno\nimport ctypes as C\nimport numpy as np\nimport coloredlogs\nimport signal\nimport os\nfrom tornado.gen import coroutine, sleep, Return, TimeoutError\nfrom tornado.locks import Event, Condition\nfrom tornado.ioloop import IOLoop\nfrom argparse import ArgumentParser\n\nlog = logging.getLogger(\"mpikat.mock_fw_client\")\n\nTYPE_MAP = {\n \"F\": (C.c_float, \"float32\"),\n \"I\": (C.c_uint32, \"uint32\")\n }\n\n\nclass StopEvent(Exception):\n pass\n\n\nclass MockFitsWriterClientError(Exception):\n pass\n\n\nclass FWSectionHeader(C.LittleEndianStructure):\n _fields_ = [\n ('section_id', C.c_uint32),\n ('nchannels', C.c_uint32)\n ]\n\n def __repr__(self):\n return \"<{} {}>\".format(self.__class__.__name__, \", \".join(\n [\"{} = {}\".format(\n key, getattr(self, key)) for key, _ in self._fields_]))\n\n\nclass FWHeader(C.LittleEndianStructure):\n _fields_ = [\n (\"data_type\", C.c_char * 4),\n (\"channel_data_type\", C.c_char * 4),\n (\"packet_size\", C.c_uint32),\n (\"backend_name\", C.c_char * 8),\n (\"timestamp\", C.c_char * 28),\n (\"integration_time\", C.c_uint32),\n (\"blank_phases\", C.c_uint32),\n (\"nsections\", C.c_uint32),\n (\"blocking_factor\", C.c_uint32)\n ]\n\n def __repr__(self):\n return \"<{} {}>\".format(self.__class__.__name__, \", \".join(\n [\"{} = {}\".format(\n key, getattr(self, key)) for key, _ in self._fields_]))\n\n\nclass MockFitsWriterClient(object):\n \"\"\"\n Wrapper class for a KATCP client to a EddFitsWriterServer\n \"\"\"\n def __init__(self, address, record_dest):\n \"\"\"\n @brief Construct new instance\n If record_dest is not empty, create a folder named record_dest and record the received packages there.\n \"\"\"\n self._address = address\n self.__record_dest = record_dest\n if record_dest:\n if not os.path.isdir(record_dest):\n os.makedirs(record_dest)\n self._ioloop = IOLoop.current()\n self._stop_event = Event()\n self._is_stopped = Condition()\n self._socket = None\n self.__last_package = 0\n\n def reset_connection(self):\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.setblocking(False)\n try:\n self._socket.connect(self._address)\n except socket.error as error:\n if error.args[0] == errno.EINPROGRESS:\n pass\n else:\n raise error\n\n @coroutine\n def recv_nbytes(self, nbytes):\n received_bytes = 0\n data = b''\n while received_bytes < nbytes:\n if self._stop_event.is_set():\n raise StopEvent\n try:\n log.debug(\"Requesting {} bytes\".format(nbytes - received_bytes))\n current_data = self._socket.recv(nbytes - received_bytes)\n received_bytes += len(current_data)\n data += current_data\n log.debug(\"Received {} bytes ({} of {} bytes)\".format(\n len(current_data), received_bytes, nbytes))\n except socket.error as error:\n error_id = error.args[0]\n if error_id == errno.EAGAIN or error_id == errno.EWOULDBLOCK:\n yield sleep(0.1)\n else:\n log.exception(\n \"Unexpected error on socket recv: {}\".format(\n str(error)))\n raise error\n raise Return(data)\n\n @coroutine\n def recv_loop(self):\n try:\n header, sections = yield self.recv_packet()\n except StopEvent:\n log.debug(\"Notifying that recv calls have stopped\")\n self._is_stopped.notify()\n except Exception as E:\n log.exception(\"Failure while receiving packet: {}\".format(E))\n else:\n self._ioloop.add_callback(self.recv_loop)\n\n def start(self):\n self._stop_event.clear()\n self.reset_connection()\n self._ioloop.add_callback(self.recv_loop)\n\n @coroutine\n def stop(self, timeout=2):\n self._stop_event.set()\n try:\n success = yield self._is_stopped.wait(\n timeout=self._ioloop.time() + timeout)\n if not success:\n raise TimeoutError\n except TimeoutError:\n log.error((\"Could not stop the client within \"\n \"the {} second limit\").format(timeout))\n except Exception:\n log.exception(\"Fucup\")\n\n @coroutine\n def recv_packet(self):\n log.debug(\"Receiving packet header\")\n raw_header = yield self.recv_nbytes(C.sizeof(FWHeader))\n log.debug(\"Converting packet header\")\n header = FWHeader.from_buffer_copy(raw_header)\n log.info(\"Received header: {}\".format(header))\n if header.timestamp < self.__last_package:\n log.error(\"Timestamps out of order!\")\n else:\n self.__last_package = header.timestamp\n\n if self.__record_dest:\n filename = os.path.join(self.__record_dest, \"FWP_{}.dat\".format(header.timestamp))\n while os.path.isfile(filename):\n log.warning('Filename {} already exists. Add suffix _'.format(filename))\n filename += '_'\n log.info('Recording to file {}'.format(filename))\n ofile = open(filename, 'wb')\n ofile.write(raw_header)\n\n fw_data_type = header.channel_data_type.strip().upper()\n c_data_type, np_data_type = TYPE_MAP[fw_data_type]\n sections = []\n for section in range(header.nsections):\n log.debug(\"Receiving section {} of {}\".format(\n section+1, header.nsections))\n raw_section_header = yield self.recv_nbytes(C.sizeof(FWSectionHeader))\n if self.__record_dest:\n ofile.write(raw_section_header)\n\n section_header = FWSectionHeader.from_buffer_copy(raw_section_header)\n log.info(\"Section {} header: {}\".format(section, section_header))\n log.debug(\"Receiving section data\")\n raw_bytes = yield self.recv_nbytes(C.sizeof(c_data_type)\n * section_header.nchannels)\n if self.__record_dest:\n ofile.write(raw_bytes)\n data = np.frombuffer(raw_bytes, dtype=np_data_type)\n log.info(\"Section {} data: {}\".format(section, data[:10]))\n sections.append((section_header, data))\n\n if self.__record_dest:\n ofile.close()\n raise Return((header, sections))\n\n\n@coroutine\ndef on_shutdown(ioloop, client):\n log.info(\"Shutting down client\")\n yield client.stop()\n ioloop.stop()\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"Receive (and optionally record) tcp packages send by EDD Fits writer interface.\")\n parser.add_argument('-H', '--host', dest='host', type=str,\n help='Host interface to connect to')\n parser.add_argument ('-p', '--port', dest='port', type=int,\n help='Port number to connect to')\n parser.add_argument('--log-level', dest='log_level', type=str, help='Log level', default=\"INFO\")\n\n parser.add_argument('--record-to', dest='record_to', type=str,\n help='Destination to record data to. No recording if empty', default=\"\")\n args = parser.parse_args()\n logging.getLogger().addHandler(logging.NullHandler())\n logger = logging.getLogger('mpikat')\n logging.getLogger('katcp').setLevel(logging.DEBUG)\n coloredlogs.install(\n fmt=(\"[ %(levelname)s - %(asctime)s - %(name)s \"\n \"- %(filename)s:%(lineno)s] %(message)s\"),\n level=args.log_level.upper(),\n logger=logger)\n ioloop = IOLoop.current()\n log.info(\"Starting MockFitsWriterClient instance\")\n client = MockFitsWriterClient((args.host, args.port), args.record_to)\n signal.signal(\n signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(\n on_shutdown, ioloop, client))\n client.start()\n ioloop.start()\n","sub_path":"mpikat/effelsberg/edd/mock_fw_client.py","file_name":"mock_fw_client.py","file_ext":"py","file_size_in_byte":9285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"160992278","text":"from unittest.mock import MagicMock\n\nimport pytest\nfrom requests import exceptions as requests_exceptions\n\nfrom briefcase.exceptions import MissingToolError, NetworkFailure\nfrom briefcase.integrations.linuxdeploy import LinuxDeploy\n\n\n@pytest.fixture\ndef mock_command(tmp_path):\n command = MagicMock()\n command.host_arch = 'wonky'\n command.tools_path = tmp_path / 'tools'\n command.tools_path.mkdir()\n\n return command\n\n\ndef test_upgrade_exists(mock_command, tmp_path):\n \"If linuxdeploy already exists, upgrading deletes first\"\n appimage_path = tmp_path / 'tools' / 'linuxdeploy-wonky.AppImage'\n\n # Mock the existence of an install\n appimage_path.touch()\n\n # Mock a successful download\n mock_command.download_url.return_value = 'new-downloaded-file'\n\n # Create a linuxdeploy wrapper, then upgrade it\n linuxdeploy = LinuxDeploy(mock_command)\n linuxdeploy.upgrade()\n\n # The mock file will be deleted\n assert not appimage_path.exists()\n\n # A download is invoked\n mock_command.download_url.assert_called_with(\n url='https://github.com/linuxdeploy/linuxdeploy/'\n 'releases/download/continuous/linuxdeploy-wonky.AppImage',\n download_path=tmp_path / 'tools'\n )\n # The downloaded file will be made executable\n mock_command.os.chmod.assert_called_with('new-downloaded-file', 0o755)\n\n\ndef test_upgrade_does_not_exist(mock_command, tmp_path):\n \"If linuxdeploy doesn't already exist, upgrading is an error\"\n # Create a linuxdeploy wrapper, then upgrade it\n linuxdeploy = LinuxDeploy(mock_command)\n with pytest.raises(MissingToolError):\n linuxdeploy.upgrade()\n\n # The tool wasn't already installed, so an error is raised.\n assert mock_command.download_url.call_count == 0\n\n\ndef test_upgrade_linuxdeploy_download_failure(mock_command, tmp_path):\n \"If linuxdeploy doesn't exist, but a download failure occurs, an error is raised\"\n # Mock the existence of an install\n appimage_path = tmp_path / 'tools' / 'linuxdeploy-wonky.AppImage'\n appimage_path.touch()\n\n mock_command.download_url.side_effect = requests_exceptions.ConnectionError\n\n # Create a linuxdeploy wrapper, then upgrade it.\n # The upgrade will fail\n linuxdeploy = LinuxDeploy(mock_command)\n with pytest.raises(NetworkFailure):\n linuxdeploy.upgrade()\n\n # The mock file will be deleted\n assert not appimage_path.exists()\n\n # A download was invoked\n mock_command.download_url.assert_called_with(\n url='https://github.com/linuxdeploy/linuxdeploy/'\n 'releases/download/continuous/linuxdeploy-wonky.AppImage',\n download_path=tmp_path / 'tools'\n )\n","sub_path":"tests/integrations/linuxdeploy/test_LinuxDeploy__upgrade.py","file_name":"test_LinuxDeploy__upgrade.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47716895","text":"from dataclasses import dataclass\nimport math\nfrom typing import Optional, Tuple, Dict\nimport re\n\nfrom furl import furl\nfrom funcy import project, walk_values, first\n\n\n@dataclass\nclass Request:\n youtube_id: str\n start: int\n end: int\n\n\n@dataclass\nclass Timestamp:\n h: int\n m: int\n s: int\n\n\ndef first_some(seq):\n return first(x for x in seq if x is not None)\n\n\ndef is_youtube_url(possible_yt_video_url: str) -> bool:\n return bool(re.match(r'(https?://)?((www\\.)?youtube\\.com|youtu\\.be)\\b', possible_yt_video_url))\n\n\ndef youtube_url_as_dict(yt_url: str) -> Dict[str, str]:\n yt_url_with_schema = yt_url if yt_url.startswith('http') else 'https://' + yt_url\n f = furl(yt_url_with_schema)\n\n if f.host.endswith('youtube.com'):\n if str(f.path) == '/watch' and 'v' in f.args:\n return project(f.args, ['v', 't'])\n else:\n return {}\n\n else: # youtu.be\n if f.path.segments:\n return {\n 'v': f.path.segments[0],\n **project(f.args, ['t']),\n }\n else:\n return {}\n\n\nHMS_PATTERN = (\n r'(?=\\d+[hms])' # require at least one group\n r'(?:(?P\\d+)h)?'\n r'(?:(?P\\d+)m)?'\n r'(?:(?P\\d+)s)?'\n)\n\n\nCOLONS_PATTERN = (\n r'(?:'\n r'(?P\\d+)'\n r':'\n r')?'\n r'(?P\\d+)'\n r':'\n r'(?P\\d+)'\n)\n\n\ndef hms_to_seconds(h: int, m: int, s: int) -> int:\n return (\n h * 60 * 60\n + m * 60\n + s\n )\n\n\ndef match_to_seconds(m):\n return hms_to_seconds(**walk_values(int, m.groupdict(default='0')))\n\n\ndef match_int(s: str) -> Optional[int]:\n try:\n return int(s)\n except ValueError:\n return None\n\n\ndef match_time_pattern(time_pattern: str, s: str) -> Optional[int]:\n found = re.search(r'^' + time_pattern + r'$', s)\n if found:\n return match_to_seconds(found)\n else:\n return None\n\n\ndef match_start(s: str) -> Optional[int]:\n return first_some([match_int(s),\n match_time_pattern(HMS_PATTERN, s),\n match_time_pattern(COLONS_PATTERN, s)])\n\n\ndef match_t_start(s: str) -> Optional[int]:\n return first_some([match_int(s),\n match_time_pattern(HMS_PATTERN, s)])\n\n\n\ndef match_end(s: str) -> Optional[Tuple[str, int]]:\n try:\n return ('relative', int(s))\n except ValueError:\n pass\n\n found = first_some([re.search(r'^\\+' + HMS_PATTERN + r'$', s),\n re.search(r'^\\+' + COLONS_PATTERN + r'$', s)])\n if found:\n return ('relative', match_to_seconds(found))\n\n found = first_some([re.search(r'^\\.\\.' + HMS_PATTERN + r'$', s),\n re.search(r'^\\.\\.' + COLONS_PATTERN + r'$', s)])\n if found:\n return ('ellipsis', match_to_seconds(found))\n\n found = first_some([re.search(r'^' + HMS_PATTERN + r'$', s),\n re.search(r'^' + COLONS_PATTERN + r'$', s)])\n if found:\n return ('absolute', match_to_seconds(found))\n\n return None\n\n\ndef seconds_to_ts(val: int) -> Timestamp:\n left, s = divmod(val, 60)\n h, m = divmod(left, 60)\n return Timestamp(h, m, s)\n\n\ndef ts_to_hms(ts: Timestamp) -> str:\n return (\n (str(int(ts.h)) + 'h' if ts.h > 0 else '')\n + (str(int(ts.m)) + 'm' if ts.m > 0 else '')\n + (str(int(ts.s)) + 's' if ts.s > 0 else '')\n )\n\n\ndef ts_to_columns(ts: Timestamp) -> str:\n s_frac, s_int = math.modf(ts.s)\n s_frac = round(s_frac * 10)\n return (\n (f'{ts.h:02.0f}' + ':' if ts.h > 0 else '')\n + f'{ts.m:02.0f}' + ':'\n + f'{s_int:02.0f}' + (f'.{s_frac}' if s_frac >= 1 else '')\n )\n\n\ndef request_to_start_timestamp_url(r: Request) -> str:\n start_hms = ts_to_hms(seconds_to_ts(r.start))\n return ('https://youtu.be/' + r.youtube_id\n + ('?t=' + start_hms if start_hms else ''))\n\n\ndef request_to_query(r: Request) -> str:\n start = ts_to_columns(seconds_to_ts(r.start))\n end = ts_to_columns(seconds_to_ts(r.end))\n return f'https://youtu.be/{r.youtube_id} {start} {end}'\n\n\ndef merge_ellipsis(s: int, e: int) -> Optional[int]:\n start = seconds_to_ts(s)\n end = seconds_to_ts(e)\n if end.m > 0:\n return hms_to_seconds(start.h, end.m, end.s)\n elif end.s > 0:\n return hms_to_seconds(start.h, start.m, end.s)\n else:\n return None\n\n\ndef raw_end_to_absolute(start: int, raw_end: Tuple[str, int]) -> Optional[int]:\n end_type, end = raw_end\n if end_type == 'absolute':\n return end\n elif end_type == 'relative':\n return start + end\n elif end_type == 'ellipsis':\n return merge_ellipsis(start, end)\n else:\n raise ValueError(raw_end)\n\n\ndef match_request(s: str) -> Optional[Request]:\n tokens = s.split()\n if len(tokens) == 2:\n maybe_yt_url_with_hms, maybe_end = tokens\n\n if not is_youtube_url(maybe_yt_url_with_hms):\n return None\n\n yt_dict = youtube_url_as_dict(maybe_yt_url_with_hms)\n\n if 'v' not in set(yt_dict):\n return None\n youtube_id = yt_dict['v']\n\n if 't' not in set(yt_dict):\n if maybe_end == 'full':\n maybe_end = '10:00'\n start = 0\n else:\n return None\n else:\n start = match_t_start(yt_dict['t'])\n if start is None:\n return None\n\n elif len(tokens) == 3:\n maybe_yt_url, maybe_start, maybe_end = tokens\n\n if not is_youtube_url(maybe_yt_url):\n return None\n\n yt_dict = youtube_url_as_dict(maybe_yt_url)\n if {'v'} != set(yt_dict):\n return None\n\n youtube_id = yt_dict['v']\n\n start = match_start(maybe_start)\n if start is None:\n return None\n\n else:\n return None\n\n raw_end = match_end(maybe_end)\n if raw_end is None:\n return None\n\n end = raw_end_to_absolute(start, raw_end)\n if end is None:\n return None\n\n if start >= end:\n raise ValueError('End position should be greater than start position.')\n\n if end - start > 10 * 60:\n raise ValueError('Maximum clip length is 10 minutes')\n\n return Request(youtube_id, start, end)\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"339521361","text":"class Node(object):\n\n def __init__(self, label, parent=None, examples=None):\n self.label = label\n self.parent = parent\n self.children = []\n self.connection = None\n self.examples = examples\n\n def add_child(self, child, connection):\n child.parent = self\n child.connection = connection\n self.children.append(child)\n\n def __str__(self):\n s = ''\n if self.children:\n for child in self.children:\n if child.connection is not None:\n s += '\\n{} = {}'.format(self.label, child.connection)\n sub = str(child)\n sub = sub.replace('\\n', '\\n ')\n s += sub\n else:\n s += ': {}'.format(self.label)\n\n return s\n\n __repr__ = __str__\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210012672","text":"from pipeline.objgen.baseclass import ObjetOutline2D\nimport numpy as np\nfrom skimage.transform import resize, rotate\nfrom scipy.ndimage import shift\n\nclass CCell(ObjetOutline2D):\n def __init__(self, ):\n super(CCell, self).__init__()\n\n def setup_basic_ball(self, color_setting, shape_setting):\n if color_setting is None:\n self.color_setting = {\n 'border': np.array([0.8,0.8,0.8]),\n 'inner': np.array([0.2,0.2,0.8])\n }\n else:\n self.color_setting = color_setting\n\n if shape_setting is None:\n self.shape_setting = {\n 'radius': 100,\n 'vertical_stretch':1.0, # to roughly make ellipse\n 'thickness': 20, # border thickness\n 'd_noise':0.1,\n 'noise_roughness': 20 # 1 is very fine, pixel level noise\n } \n else:\n self.shape_setting = shape_setting\n\n def make_basic_ball(self, centerpos=(0,0), rotate_angle=None):\n r = self.shape_setting['radius']\n d_noise = self.shape_setting['d_noise']\n thickness = self.shape_setting['thickness']\n noise_roughness = self.shape_setting['noise_roughness']\n vertical_stretch = self.shape_setting['vertical_stretch']\n border_color = self.color_setting['border']\n inner_color = self.color_setting['inner'] \n\n return self.build_basic_ball_body(r, thickness, border_color, inner_color, vertical_stretch=vertical_stretch,\n d_noise=d_noise, noise_roughness=noise_roughness, rotate_angle=rotate_angle, centerpos=centerpos) \n\n def build_basic_ball_body(self, r, thickness, border_color, inner_color, vertical_stretch=1.0,\n d_noise=None, noise_roughness=None, centerpos=(0,0), rotate_angle=None, \n do_make_explanation=True):\n \"\"\"\n r (radius of ball), thickness (of border) are floats in the scale of array pixels (1 means 1 pixel of array)\n d is the array containing distance from origin (defined as the center of the array)\n\n also in the same order of magnitude as r:\n + centerpos is (x0,y0) : float \n + d_noise : float. Set None to disable. \n + noise_roughness : float. Set equals to 1. to generate random normal number per pixel. If set to, for example 2,\n noise is generated every 2x2 pixels\n \"\"\"\n\n x, y = self.get_lattice_coord()\n x0,y0 = centerpos\n\n # d = ((x-x0) **2 + ((y-y0)/vertical_stretch)**2)**0.5\n d = ((x) **2 + ((y)/vertical_stretch)**2)**0.5\n\n if d_noise is not None:\n n = resize(np.random.normal(0,d_noise, size=[int(dn/noise_roughness) for dn in d.shape]), d.shape)\n d = d + n\n else:\n n = None\n\n border = (d<=r) * (d>=r-thickness) \n border = self.stack_color(border, border_color, channel_CHW=True)\n inner_ball = (d --predictFile= --tol=')\n\texit(1)\n\nlabelFile = ''\npredictFile = ''\ntol = 10\nfor (opt, arg) in opts:\n\tif opt == '--tol':\n\t\ttol = int(arg)\n\telif opt == '--labelFile':\n\t\tlabelFile = arg\n\telif opt == '--predictFile':\n\t\tpredictFile = arg\n\telse:\n\t\tprint('usage: python3 detect_FN.py --labelFile= --predictFile= --tol=')\n\t\texit(1)\n\n#Labeled file\ndata1 = pd.read_csv(labelFile)\nno1 = data1['Frame'].values\nv1 = data1['Visibility'].values\nx1 = data1['X'].values\ny1 = data1['Y'].values\n#Predicted file\ndata2 = pd.read_csv(predictFile)\nno2 = data2['Frame'].values\nv2 = data2['Visibility'].values\nx2 = data2['X'].values\ny2 = data2['Y'].values\n\noffset = no2[0] - no1[0]\n#0 for TP, 1 for TN, 2 for FP1, 3 for FP2, 4 for FN\noutcome = []\n#no1[i + offset] is equal to no2[i]\nn = min(len(no1) - offset, len(no2))\nfor i in range(n):\n\t#Negative\n\tif v2[i] == 0:\n\t\t#TN\n\t\tif v1[i + offset] == 0:\n\t\t\toutcome.append(1)\n\t\t#FN\n\t\telif v1[i + offset] == 1:\n\t\t\toutcome.append(4)\n\t#Positive\n\telif v2[i] == 1:\n\t\tif v1[i + offset] == 0:\n\t\t\toutcome.append(3)\n\t\telif v1[i + offset] == 1:\n\t\t\tdist = math.sqrt(pow(x2[i] - x1[i + offset], 2) + pow(y2[i] - y1[i + offset], 2))\n\t\t\tif dist > tol:\n\t\t\t\toutcome.append(2)\n\t\t\telse:\n\t\t\t\toutcome.append(0)\n\n#If the size of the predicted data may be larger than labeled data\nif len(no1) < len(no2) + offset:\n\tfor i in range(len(no1) - offset, len(no2)):\n\t\tif v2[i] == 0:\n\t\t\toutcome.append(1)\n\t\telif v2[i] == 1:\n\t\t\toutcome.append(3)\n\n\n\ncontinuous_FN = []\naccumulate = 0\nfor i in range(len(outcome)):\n\tif outcome[i] == 4:\n\t\taccumulate += 1\n\telse:\n\t\tif accumulate > 0:\n\t\t\tcontinuous_FN.append(accumulate)\n\t\taccumulate = 0\n\nif accumulate > 0:\n\tcontinuous_FN.append(accumulate)\n\ncontinuous_FN.sort()\n\ns = e = 0\nwhile e < len(continuous_FN):\n\ts = e\n\twhile continuous_FN[e] == continuous_FN[s]:\n\t\te += 1\n\t\tif e >= len(continuous_FN):\n\t\t\tbreak\n\tprint('Number of '+ str(continuous_FN[s]) + ' successive FNs: ' + str(e - s))\n\nprint('Outcome of every frame of the predicted labeling csv file (0 for TP, 1 for TN, 2 for FP1, 3 for FP2, 4 for FN):')\nprint(outcome)\nTP = TN = FP1 = FP2 = FN = 0\nfor i in range(len(outcome)):\n\tif outcome[i] == 0:\n\t\tTP += 1\n\telif outcome[i] == 1:\n\t\tTN += 1\n\telif outcome[i] == 2:\n\t\tFP1 += 1\n\telif outcome[i] == 3:\n\t\tFP2 += 1\n\telif outcome[i] == 4:\n\t\tFN += 1\n\nprint('(TP, TN, FP1, FP2, FN):', (TP, TN, FP1, FP2, FN))\n","sub_path":"detect_FN.py","file_name":"detect_FN.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571159572","text":"#!/usr/bin/env python\n\n# virt assembler\n# version 2017-04-11\n# developed in Python 3.4.1\n\nimport sys\n\n### LOGGER #####################################################################\n\n# 0 no logging\n# 1 fatal\n# 2 error\n# 3 warn\n# 4 info\n# 5 debug\n\ndef debug(msg):\n\tif logLevel < 5:\n\t\treturn\n\tprintMessage(\"DEBUG\", msg)\n\ndef error(msg):\n\tif logLevel < 2:\n\t\treturn\n\tprintMessage(\"ERROR\", \"(\" + str(asmLine) + \") \" + msg)\n\ndef fatal(msg):\n\tif logLevel < 1:\n\t\treturn\n\tprintMessage(\"FATAL\", \"(\" + str(asmLine) + \") \" + msg)\n\ndef info(msg):\n\tif logLevel < 4:\n\t\treturn\n\tprintMessage(\"INFO\", msg)\n\t\t\ndef warn(msg):\n\tif logLevel < 3:\n\t\treturn\n\tprintMessage(\"WARN\", msg)\n\ndef printMessage(lbl, msg):\n\tglobal addressPtr, asmLine\n\tprint(lbl + \" | \" + msg)\n\n### OPERATION CODES ############################################################\n\nOP_NOP = 0x0\nOP_DI = 0xFD\nOP_EI = 0xFE\nOP_HALT = 0xFF\nOP_MOV_R8_N8 = 0x10\nOP_MOV_R8_R8 = 0x11\nOP_MOV_R8_mN16 = 0x12\nOP_MOV_mN16_R8 = 0x13\nOP_MOV_R8_mR16 = 0x14\nOP_MOV_mR16_R8 = 0x15\nOP_MOV_mR16_N8 = 0x16\nOP_MOV_R16_N16 = 0x17\nOP_MOV_R16_R16 = 0x18\nOP_SWP_R8_R8 = 0x1F\nOP_PUSH_R16 = 0x20\nOP_PUSH_N16 = 0x21\nOP_POP_R16 = 0x22\nOP_JMP_N16 = 0x30\nOP_JC_N16 = 0x31\nOP_JNC_N16 = 0x32\nOP_JZ_N16 = 0x33\nOP_JNZ_N16 = 0x34\nOP_CALL_N16 = 0x40\nOP_RET = 0x41\nOP_AND_R8_N8 = 0x50\nOP_AND_R8_R8 = 0x51\nOP_OR_R8_N8 = 0x52\nOP_OR_R8_R8 = 0x53\nOP_XOR_R8_N8 = 0x54\nOP_XOR_R8_R8 = 0x55\nOP_NOT_R8 = 0x56\nOP_ADD_R8_N8 = 0x60\nOP_ADD_R8_R8 = 0x61\nOP_SUB_R8_N8 = 0x62\nOP_SUB_R8_R8 = 0x63\nOP_INC_R8 = 0x64\nOP_DEC_R8 = 0x65\nOP_SHL_R8 = 0x66\nOP_SHR_R8 = 0x67\nOP_CMP_R8_N8 = 0x70\nOP_CMP_R8_R8 = 0x71\n\nFLAG_ZERO = 0x80\nFLAG_CARRY = 0x40\n\ndef handleNOP(opcode, args):\n\tdata = bytearray()\n\tdata.append(opcode)\n\treturn data\n\t\ndef handleN16(opcode, args):\n\tif args.isdecimal():\n\t\tn = int(args)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\t\n\tif not isInt16(n):\n\t\terror(\"Argument is not 16bit\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\tdata.append(opcode)\t\n\tdata.append((n >> 8) & 0xFF)\n\tdata.append(n & 0xFF)\n\t\n\treturn data\n\ndef handleMN16_R8(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\n\tdata = bytearray()\n\n\tif isMemoryAddress(sargs[0]) and isRegister(sargs[1]):\n\t\tif sargs[0][1:-1].isdecimal():\n\t\t\tmn16 = int(sargs[0][1:-1])\n\n\t\tr8 = getRegister(sargs[1])\n\t\t\n\t\tif not isInt16(mn16):\n\t\t\terror(\"Memory location not 16bit\")\n\t\t\texit(1)\n\t\t\n\t\tif not isReg8(sargs[1]):\n\t\t\terror(\"Second argument is not 8bit\")\n\t\t\texit(1)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append((mn16 >> 8) & 0xFF)\n\t\tdata.append(mn16 & 0xFF)\t\n\t\tdata.append(r8)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\ndef handleMR16_N8(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isMemoryRegister(sargs[0]) and sargs[1].isdecimal():\t\t\n\t\tmr16 = getRegister(sargs[0][1:-1])\n\t\tn8 = int(sargs[1])\n\t\t\n\t\tif not isReg16(sargs[0][1:-1]):\n\t\t\terror(\"First argument is not 16bit\")\n\t\t\texit(1)\n\t\t\n\t\tif not isInt8(n8):\n\t\t\terror(\"Second argument is not 8bit\")\n\t\t\texit(1)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(mr16)\n\t\tdata.append(n8)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\n\treturn data\n\ndef handleMR16_R8(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isMemoryRegister(sargs[0]) and isRegister(sargs[1]):\n\t\tif not isReg16(sargs[0][1:-1]):\n\t\t\terror(\"Memory location register not 16bit\")\n\t\t\texit(1)\n\n\t\tif not isReg8(sargs[1]):\n\t\t\terror(\"Second argument is not 8bit\")\n\t\t\texit(1)\n\t\t\n\t\tmr16 = getRegister(sargs[0][1:-1])\n\t\tr8 = getRegister(sargs[1])\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(mr16)\n\t\tdata.append(r8)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\n\treturn data\n\t\ndef handleReadR8(opcode, args):\n\tdata = bytearray()\n\n\tif isRegister(args):\n\t\tif not isReg8(args):\n\t\t\terror(\"Register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tr = getRegister(args)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\ndef handleWriteR8(opcode, args):\n\tdata = bytearray()\n\n\tif isRegister(args):\n\t\tif not isReg8(args):\n\t\t\terror(\"Register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(args):\n\t\t\terror(\"Register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tr = getRegister(args)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\ndef handleR8_mN16(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\n\tdata = bytearray()\n\t\t\n\tif isRegister(sargs[0]) and isMemoryAddress(sargs[1]):\n\t\tr8 = getRegister(sargs[0])\n\n\t\tif sargs[1][1:-1].isdecimal():\n\t\t\tn16 = int(sargs[1][1:-1])\n\t\t\n\t\tif not isReg8(sargs[0]):\n\t\t\terror(\"Register is not 8bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"Register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isInt16(n16):\n\t\t\terror(\"Memory location is not 16bit\")\n\t\t\texit(1)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r8)\n\t\tdata.append((n16 >> 8) & 0xFF)\n\t\tdata.append(n16 & 0xFF)\n\telse:\n\t\terror(\"Unknown operation:\" + opcode + \" \" + args)\n\t\texit(1)\n\t\t\n\treturn data\n\ndef handleR8_mR16(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isRegister(sargs[0]) and isMemoryRegister(sargs[1]):\t\t\t\t\n\t\tif not isReg8(sargs[0]):\n\t\t\terror(\"First register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"First register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isReg16(sargs[1][1:-1]):\n\t\t\terror(\"Memory location register not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tr8 = getRegister(sargs[0])\n\t\tmr16 = getRegister(sargs[1][1:-1])\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r8)\n\t\tdata.append(mr16)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\n\treturn data\n\ndef handleR8_N8(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isRegister(sargs[0]) and sargs[1].isdecimal():\n\t\tr = getRegister(sargs[0])\n\t\tn = int(sargs[1])\n\t\t\n\t\tif not isReg8(sargs[0]):\n\t\t\terror(\"First register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"First register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isInt8(n):\n\t\t\terror(\"Second argument is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\t\tdata.append(n)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\ndef handleR8_R8(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isRegister(sargs[0]) and isRegister(sargs[1]):\t\t\n\t\tif not isReg8(sargs[0]):\n\t\t\terror(\"First register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"First register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isReg8(sargs[1]):\n\t\t\terror(\"Second register is not 8 bit\")\n\t\t\texit(1)\n\t\t\n\t\tr1 = getRegister(sargs[0])\n\t\tr2 = getRegister(sargs[1])\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r1)\n\t\tdata.append(r2)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\ndef handleReadR16(opcode, args):\n\tdata = bytearray()\n\n\tif isRegister(args):\n\t\tif not isReg16(args):\n\t\t\terror(\"Register is not 16 bit\")\n\t\t\texit(1)\n\t\t\t\t\n\t\tr = getRegister(args)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\n\treturn data\n\t\ndef handleWriteR16(opcode, args):\n\tdata = bytearray()\n\n\tif isRegister(args):\n\t\tif not isReg16(args):\n\t\t\terror(\"Register is not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(args):\n\t\t\terror(\"Register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tr = getRegister(args)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\n\treturn data\n\ndef handleR16_N16(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isRegister(sargs[0]) and sargs[1].isdecimal():\n\t\tr = getRegister(sargs[0])\n\t\tn = int(sargs[1])\n\t\t\n\t\tif not isReg16(sargs[0]):\n\t\t\terror(\"Register is not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"Register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isInt16(n):\n\t\t\terror(\"Second argument is not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r)\n\t\tdata.append((n >> 8) & 0xFF)\n\t\tdata.append(n & 0xFF)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\t\ndef handleR16_R16(opcode, args):\n\tsargs = args.split(\",\")\n\t\n\tif len(sargs) != 2:\n\t\terror(\"Bad syntax, requires 2 arguments\")\n\t\texit(1)\n\t\n\tdata = bytearray()\n\t\n\tif isRegister(sargs[0]) and isRegister(sargs[1]):\t\t\n\t\tif not isReg16(sargs[0]):\n\t\t\terror(\"First register is not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tif isReadOnly(sargs[0]):\n\t\t\terror(\"First register is read-only\")\n\t\t\texit(1)\n\t\t\n\t\tif not isReg16(sargs[1]):\n\t\t\terror(\"Second register is not 16 bit\")\n\t\t\texit(1)\n\t\t\n\t\tr1 = getRegister(sargs[0])\n\t\tr2 = getRegister(sargs[1])\n\t\t\n\t\tdata.append(opcode)\n\t\tdata.append(r1)\n\t\tdata.append(r2)\n\telse:\n\t\terror(\"Unknown operation: \" + opcode + \" \" + args)\n\t\texit(1)\n\t\n\treturn data\n\t\n### ASSEMBLER INSTRUCTIONS #####################################################\n\ndef handleByte(args):\n\tsargs = args.split(\",\")\n\t\n\tdata = bytearray()\n\t\n\tfor exp in sargs:\n\t\tif isNumber(exp):\n\t\t\tn = getNumber(exp)\n\t\t\t\n\t\t\tif isInt8(n):\n\t\t\t\tdata.append(n)\n\t\n\treturn data\t\n\ndef handleDefine(args):\n\tsargs = args.partition(\" \")\n\t\n\tif isSymbol(sargs[0]) and isNumber(sargs[2]):\n\t\tif sargs[0] in addressMap:\n\t\t\terror(\"Symbol already exists \" + sargs[0])\n\t\t\texit(1)\n\t\n\t\tn = getNumber(sargs[2])\n\t\t\t\n\t\tif isInt16(n):\n\t\t\taddressMap[sargs[0]] = getNumber(sargs[2])\n\t\telse:\n\t\t\terror(\"Must be 16bit: \" + sargs[2])\n\t\t\texit(1)\n\telif isRegister(sargs[0]):\n\t\terror(\"Cannot use register name as symbol (case of letters is ignored)\\n\")\n\t\texit(1)\n\telse:\n\t\terror(\"Bad format \" + sargs[0])\n\t\texit(1)\t\n\t\n\treturn bytearray()\n\ndef handleIncbin(args):\n\tif not isString(args):\n\t\terror(\"Not a string: \" + args)\n\t\treturn bytearray()\n\t\t\n\tf = open(args[1:-1], \"rb\")\n\tdata = bytearray(f.read())\n\tf.close()\n\t\n\treturn data\n\ndef handleOrg(args):\n\tglobal addressPtr, binaryPtr\n\n\tdata = bytearray()\n\n\tdecimal = getNumber(args)\n\n\tdiff = decimal - addressPtr\n\t\n\tif diff < 0:\n\t\terror(\"ORG position < instruction pointer: \" + hex(decimal)\\\n\t\t\t+ \" IP:\" + hex(addressPtr))\n\t\texit(1)\n\telif diff > 0:\n\t\tfor i in range(diff):\n\t\t\tdata.append(0x0)\n\t\t\n\treturn data\n\ndef handleSection(args):\n\tglobal addressPtr\n\t\n\tdecimal = getNumber(args)\n\t\n\tif isInt16(decimal):\n\t\taddressPtr = decimal\n\telse:\n\t\terror(\"Section address must be 16bit\")\n\t\texit(1)\n\t\n\treturn bytearray()\n\n################################################################################\n\ndef handleInstruction(line):\n\tglobal addressPtr, binaryPtr\n\t\n\tif asmPass == 2 and line.startswith(\".define\"):\n\t\treturn bytearray()\n\t\n\tline = line[1:]\n\tpart = line.partition(\" \")\n\top = part[0]\n\targs = part[2]\n\n\tff = instructions[op]\n\tdata = ff(args)\n\t\n\taddressPtr += len(data)\n\tbinaryPtr += len(data)\n\t\n\treturn data\n\ndef handleOperation(line):\n\tglobal addressPtr, binaryPtr\n\t\n\tpart = line.partition(\" \")\n\top = part[0]\n\targs = part[2]\n\t\t\n\topcode = getOpCode(line)\n\t\t\n\tff = ophandlers[opcode]\n\tdata = ff(opcode, args)\n\t\n\taddressPtr += len(data)\n\tbinaryPtr += len(data)\n\t\n\treturn data\n\n### UTILS ######################################################################\n\ndef getNumber(exp):\n\tn = -1\n\t\t\n\tif isBinary(exp):\n\t\tn = int(exp[1:],2)\n\telif isDecimal(exp):\n\t\tn = int(exp)\n\telif isHex(exp):\n\t\tn = int(exp[1:], 16)\n\telse:\n\t\terror(\"Unknown type: \" + exp)\n\t\n\treturn n\n\ndef getOpCode(line):\n\tif not isOperation(line):\n\t\terror(\"Not an operation\")\n\t\texit(1)\n\n\tpart = line.partition(\" \")\n\top = part[0]\n\targs = part[2]\n\tsargs = args.split(\",\")\n\t\n\topcode = -1\n\t\n\tif op == \"add\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_ADD_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_ADD_R8_R8\n\telif op == \"and\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_AND_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_AND_R8_R8\n\telif op == \"call\":\n\t\tif isExpression(sargs[0]):\n\t\t\topcode = OP_CALL_N16\n\telif op == \"cmp\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_CMP_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_CMP_R8_R8\n\telif op == \"dec\":\n\t\tif isReg8(sargs[0]):\n\t\t\topcode = OP_DEC_R8\n\telif op == \"di\":\n\t\topcode = OP_DI\n\telif op == \"ei\":\n\t\topcode = OP_EI\n\telif op == \"halt\":\n\t\topcode = OP_HALT\n\telif op == \"inc\":\n\t\tif isReg8(sargs[0]):\n\t\t\topcode = OP_INC_R8\n\telif op == \"jmp\":\n\t\tif isExpression(sargs[0]):\n\t\t\topcode = OP_JMP_N16\n\telif op == \"jnc\":\n\t\tif isExpression(sargs[0]):\n\t\t\topcode = OP_JNC_N16\n\telif op == \"jnz\":\n\t\tif isExpression(sargs[0]):\n\t\t\topcode = OP_JNZ_N16\n\telif op == \"jz\":\n\t\tif isExpression(sargs[0]):\n\t\t\topcode = OP_JZ_N16\n\telif op == \"mov\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_MOV_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_MOV_R8_R8\n\t\telif isReg8(sargs[0]) and isMemoryAddress(sargs[1]):\n\t\t\topcode = OP_MOV_R8_mN16\n\t\telif isMemoryAddress(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_MOV_mN16_R8\n\t\telif isReg8(sargs[0]) and isMemoryRegister(sargs[1]):\n\t\t\topcode = OP_MOV_R8_mR16\n\t\telif isMemoryRegister(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_MOV_mR16_R8\n\t\telif isMemoryRegister(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_MOV_mR16_N8\n\t\telif isReg16(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_MOV_R16_N16\n\t\telif isReg16(sargs[0]) and isReg16(sargs[1]):\n\t\t\topcode = OP_MOV_R16_R16\n\telif op == \"not\":\n\t\tif isReg8(sargs[0]):\n\t\t\topcode = OP_NOT_R8\n\telif op == \"nop\":\n\t\topcode = OP_NOP\n\telif op == \"or\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_OR_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_OR_R8_R8\n\telif op == \"pop\":\n\t\tif isReg16(sargs[0]):\n\t\t\topcode = OP_POP_R16\n\telif op == \"push\":\n\t\tif isReg16(sargs[0]):\n\t\t\topcode = OP_PUSH_R16\n\t\telif isExpression(sargs[0]):\n\t\t\topcode = OP_PUSH_N16\n\telif op == \"ret\":\n\t\topcode = OP_RET\n\telif op == \"shl\":\n\t\tif isReg8(sargs[0]):\n\t\t\topcode = OP_SHL_R8\n\telif op == \"shr\":\n\t\tif isReg8(sargs[0]):\n\t\t\topcode = OP_SHR_R8\n\telif op == \"sub\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_SUB_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_SUB_R8_R8\n\telif op == \"swp\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_SWP_R8_R8\n\telif op == \"xor\" and len(sargs) == 2:\n\t\tif isReg8(sargs[0]) and isExpression(sargs[1]):\n\t\t\topcode = OP_XOR_R8_N8\n\t\telif isReg8(sargs[0]) and isReg8(sargs[1]):\n\t\t\topcode = OP_XOR_R8_R8\n\t\n\tif opcode == -1:\n\t\terror(\"getOpCode(): Unknown operation: \" + line + \" \" + str(opcode))\n\t\texit(1)\n\t\n\treturn opcode\n\t\ndef getRegister(exp):\n\treturn regnames.index(exp)\n\ndef isBinary(exp):\n\tchars = \"01\"\n\treturn exp.startswith(\"%\") and all(c in chars for c in exp[1:])\n\ndef isDecimal(exp):\n\treturn exp.isdecimal()\n\ndef isExpression(exp):\n\treturn isNumber(exp) or isSymbol(exp)\n\t\ndef isHex(exp):\n\thexdigits = \"0123456789abcdefABCDEF\"\n\treturn exp.startswith(\"$\") and all(c in hexdigits for c in exp[1:])\n\t\ndef isInstruction(line):\n\tline = line.lower()\n\n\tfor i in instructions:\n\t\tif line[1:].find(i + \" \") == 0:\n\t\t\treturn True\n\t\n\treturn False\n\ndef isInt8(i):\n\treturn 0x0 <= i and i <= 0xFF\n\ndef isReg8(r):\n\tif r not in regnames:\n\t\treturn False\n\n\tr = r.lower()\n\ti = regnames.index(r);\n\treturn regsizes[i] == 8;\n\t\ndef isReg16(r):\n\tif r not in regnames:\n\t\treturn False\n\n\tr = r.lower()\n\ti = regnames.index(r);\n\treturn regsizes[i] == 16;\t\n\ndef isInt16(i):\n\treturn 0x0 <= i and i <= 0xFFFF\n\t\ndef isMemoryAddress(exp):\n\treturn exp.startswith(\"[\") and exp.endswith(\"]\") and isExpression(exp[1:-1])\n\ndef isMemoryRegister(exp):\n\treturn exp.startswith(\"[\") and exp.endswith(\"]\") and isRegister(exp[1:-1])\n\ndef isNumber(exp):\n\treturn isBinary(exp) or isDecimal(exp) or isHex(exp)\n\ndef isLabel(line):\n\treturn line.endswith(\":\") and isSymbol(line[:line.find(\":\")])\n\t\ndef isOperation(line):\n\tline = line.lower()\n\n\tfor o in operations:\n\t\t# i.e. check for \"push \" or \"nop\"\n\t\tif line.find(o + \" \") == 0 or (line.find(o) == 0 and len(line) == len(o)):\n\t\t\treturn True\n\t\n\treturn False\n\ndef isReadOnly(r):\n\tr = r.lower();\n\ti = regnames.index(r)\n\treturn regreadonly[i]\n\t\ndef isRegister(exp):\n\texp = exp.lower()\n\treturn exp in regnames\n\ndef isString(exp):\n\treturn exp[0] == '\"' and exp[-1] == '\"'\n\ndef isSymbol(exp):\n\tif isNumber(exp) or isRegister(exp):\n\t\treturn False\n\n\tchars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"\n\treturn exp not in regnames and all(c in chars for c in exp)\n\ndef resolveSymbol(symbol):\n\tif not isSymbol(symbol):\n\t\treturn -1\n\t\n\tif symbol not in addressMap:\n\t\terror(\"Cannot resolve symbol: \" + symbol)\n\t\texit(1)\n\n\treturn int(addressMap.get(symbol))\n\t\n################################################################################\n\t\ndef normalize(line):\n\t# remove comments\n\tif line.startswith(\";\"):\n\t\treturn \"\"\n\t\n\tif line.find(\";\") != -1:\n\t\tline = line[:line.find(\";\")]\n\t\n\t# normalize\n\tline = line.strip()\n\t\n\tif len(line) == 0:\n\t\treturn line\n\t\n\tline = line.replace(\"\\t\", \" \")\n\n\t# replace all access spaces\n\twhile line.find(\" \") != -1:\n\t\tline = line.replace(\" \", \" \")\n\t\n\tif isOperation(line) or isInstruction(line):\n\t\twhile line.find(\", \") != -1:\n\t\t\tline = line.replace(\", \", \",\")\n\t\t\n\t\twhile line.find(\" ,\") != -1:\n\t\t\tline = line.replace(\" ,\", \",\")\n\t\n\t# lower register letters and turn any number to decimal\n\tif isOperation(line):\n\t\tif \" \" in line:\n\t\t\tpart = line.partition(\" \")\n\t\t\top = part[0].lower()\n\t\t\targs = part[2]\n\t\t\t\n\t\t\tsargs = args.split(\",\")\n\t\t\t\n\t\t\tline = op + \" \"\n\t\t\t\n\t\t\tfor i in range(len(sargs)):\n\t\t\t\tif i > 0:\n\t\t\t\t\tline += \",\"\n\n\t\t\t\tif isNumber(sargs[i]):\n\t\t\t\t\tline += str(getNumber(sargs[i]))\n\t\t\t\telif isRegister(sargs[i]):\n\t\t\t\t\tline += str(sargs[i].lower())\n\t\t\t\telif isMemoryAddress(sargs[i]) and isNumber(sargs[i][1:-1]):\n\t\t\t\t\tline += \"[\" + str(getNumber(sargs[i][1:-1])) + \"]\"\n\t\t\t\telse:\n\t\t\t\t\tline += sargs[i]\n\t\telse:\n\t\t\tline = line.lower()\n\t\n\tif isInstruction(line):\n\t\tif \" \" in line:\n\t\t\tpart = line.partition(\" \")\n\t\t\t\n\t\t\tline = part[0].lower() + \" \" + part[2]\n\t\telse:\n\t\t\tline = line.lower()\n\t\t\n\treturn line\n\t\ndef resolveSymbols(line):\n\tif isOperation(line):\n\t\tif \" \" in line:\n\t\t\tpart = line.partition(\" \")\n\t\t\top = part[0].lower()\n\t\t\targs = part[2]\n\t\t\t\n\t\t\tsargs = args.split(\",\")\n\t\t\t\n\t\t\tline = op + \" \"\n\t\t\t\n\t\t\tfor i in range(len(sargs)):\n\t\t\t\tif i > 0:\n\t\t\t\t\tline += \",\"\n\n\t\t\t\tif isSymbol(sargs[i]):\n\t\t\t\t\taddr = resolveSymbol(sargs[i])\n\t\t\t\t\t\n\t\t\t\t\tif addr != -1:\n\t\t\t\t\t\tline += str(addr)\n\t\t\t\t\telse:\n\t\t\t\t\t\terror(\"Symbol cannot be resolved: \" + sargs[i])\n\t\t\t\t\t\texit(1)\n\t\t\t\telif isMemoryAddress(sargs[i]) and isSymbol(sargs[i][1:-1]):\n\t\t\t\t\taddr = resolveSymbol(sargs[i][1:-1])\n\t\t\t\t\n\t\t\t\t\tif addr != -1:\n\t\t\t\t\t\tline += \"[\" + str(addr) + \"]\"\n\t\t\t\t\telse:\n\t\t\t\t\t\terror(\"Symbol cannot be resolved: \" + sargs[i])\n\t\t\t\t\t\texit(1)\n\t\t\t\telse:\n\t\t\t\t\tline += sargs[i]\n\treturn line\n\ndef assemble(src, dst):\n\tglobal addressPtr, asmLine, fbin, origLine\n\t\n\tdebug(\"--- Assemble ---\")\n\t\n\tfbin = open(dst, \"wb\")\n\t\n\twith open(src, \"r\") as file:\n\t\tfor line in file:\n\t\t\torigLine = line.strip()\n\n\t\t\tasmLine = asmLine + 1\n\t\t\n\t\t\tline = resolveSymbols(normalize(line))\n\t\t\t\n\t\t\tif len(line) == 0 or isLabel(line):\n\t\t\t\tcontinue\n\t\t\n\t\t\tdebug(str(asmLine) + \" \" + str(addressPtr) + \": \" + line)\n\t\t\n\t\t\tif isOperation(line):\n\t\t\t\tfbin.write(handleOperation(line))\n\t\t\telif isInstruction(line):\n\t\t\t\tfbin.write(handleInstruction(line))\n\t\t\n\tfbin.close()\n\t\ndef resolve(src):\n\tglobal addressPtr, asmLine\n\t\n\tdebug(\"--- Resolve ---\");\n\t\n\twith open(src, \"r\") as file:\n\t\tfor line in file:\n\t\t\tasmLine = asmLine + 1\n\n\t\t\tline = normalize(line)\n\n\t\t\tif len(line) == 0:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif isOperation(line):\n\t\t\t\topcode = getOpCode(line)\n\t\t\t\t\n\t\t\t\tif opcode != -1:\n\t\t\t\t\tdebug(str(asmLine) + \": \" + hex(addressPtr) + \" \" + str(opsizes[opcode]) + \" \" + hex(opcode) + \" \" + line)\n\t\t\t\t\taddressPtr += opsizes[opcode]\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\terror(\"Cannot find opcode for operation: \" + line)\n\t\t\t\t\texit(1)\n\t\t\telif isInstruction(line):\n\t\t\t\thandleInstruction(line)\n\t\t\t\tdebug(line)\n\t\t\telif isLabel(line):\n\t\t\t\tlabel = line[:-1]\n\t\t\t\t\t\t\t\t\n\t\t\t\tif label not in addressMap:\n\t\t\t\t\taddressMap[label] = addressPtr\n\t\t\t\telse:\n\t\t\t\t\terror(\"label already exists \" + label)\n\t\t\t\t\texit(1)\n\t\t\telse:\n\t\t\t\terror(\"Unknown operation: \" + line)\n\t\t\t\texit(1)\n\ndef asm(src, dst):\n\tglobal addressPtr, asmLine, asmPass, binaryPtr, logLevel\n\n\taddressPtr = 0\n\tasmLine = 0\n\tasmPass = 1\n\tbinaryPtr = 0\n\tlogLevel = 3 # debug\n\tresolve(src)\n\t\n\taddressPtr = 0\n\tasmLine = 0\n\tasmPass = 2\n\tbinaryPtr = 0\n\tlogLevel = 5 # errors\n\tassemble(src, dst)\n\n### GLOBALS ####################################################################\n\naddressPtr = 0\nasmLine = 0\nasmPass = 0\nbinaryPtr = 0\nfbin = 0\nlogLevel = 0\norigLine = 0\n\naddressMap = {}\n\nregnames = [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"ab\", \"cd\", \"ef\", \"sp\" ]\nregsizes = [ 8, 8, 8, 8, 8, 8, 16, 16, 16, 16 ]\nregreadonly = [ False, False, False, False, False, False, False, False, False, True ]\n\ninstructions = {\n\t\"byte\": handleByte,\n\t\"define\": handleDefine,\n\t\"incbin\": handleIncbin,\n\t\"org\": handleOrg,\n\t\"section\": handleSection\n}\n\noperations = [ \"add\", \"and\", \"call\", \"cmp\",\t\"dec\", \"di\", \"ei\", \"halt\", \"inc\", \"jmp\", \"jnc\",\n\t\t\"jnz\", \"jz\", \"mov\", \"not\", \"nop\", \"or\", \"pop\", \"push\", \"ret\", \"shl\",\n\t\t\"shr\", \"sub\", \"swp\", \"xor\" ]\n\nopsizes = {\n\tOP_NOP: 1,\n\tOP_DI: 1,\n\tOP_EI: 1,\n\tOP_HALT: 1,\n\tOP_MOV_R8_N8: 3,\n\tOP_MOV_R8_R8: 3,\n\tOP_MOV_R8_mN16: 4,\n\tOP_MOV_mN16_R8: 4,\n\tOP_MOV_R8_mR16: 3,\n\tOP_MOV_mR16_R8: 3,\n\tOP_MOV_mR16_N8: 3,\n\tOP_MOV_R16_N16: 4,\n\tOP_MOV_R16_R16: 3,\n\tOP_SWP_R8_R8: 3,\n\tOP_PUSH_R16: 2,\n\tOP_PUSH_N16: 3,\n\tOP_POP_R16: 2,\n\tOP_JMP_N16: 3,\n\tOP_JC_N16: 3,\n\tOP_JNC_N16: 3,\n\tOP_JZ_N16: 3,\n\tOP_JNZ_N16: 3,\n\tOP_CALL_N16: 3,\n\tOP_RET: 1,\n\tOP_AND_R8_N8: 3,\n\tOP_AND_R8_R8: 3,\n\tOP_OR_R8_N8: 3,\n\tOP_OR_R8_R8: 3,\n\tOP_XOR_R8_N8: 3,\n\tOP_XOR_R8_R8: 3,\n\tOP_NOT_R8: 2,\n\tOP_ADD_R8_N8: 3,\n\tOP_ADD_R8_R8: 3,\n\tOP_SUB_R8_N8: 3,\n\tOP_SUB_R8_R8: 3,\n\tOP_INC_R8: 2,\n\tOP_DEC_R8: 2,\n\tOP_SHL_R8: 2,\n\tOP_SHR_R8: 2,\n\tOP_CMP_R8_N8: 3,\n\tOP_CMP_R8_R8: 3\n}\n\nophandlers = {\n\tOP_NOP: handleNOP,\n\tOP_DI: handleNOP,\n\tOP_EI: handleNOP,\n\tOP_HALT: handleNOP,\n\tOP_MOV_R8_N8: handleR8_N8,\n\tOP_MOV_R8_R8: handleR8_R8,\n\tOP_MOV_R8_mN16: handleR8_mN16,\n\tOP_MOV_mN16_R8: handleMN16_R8,\n\tOP_MOV_R8_mR16: handleR8_mR16,\n\tOP_MOV_mR16_R8: handleMR16_R8,\n\tOP_MOV_mR16_N8: handleMR16_N8,\n\tOP_MOV_R16_N16: handleR16_N16,\n\tOP_MOV_R16_R16: handleR16_R16,\n\tOP_SWP_R8_R8: handleR8_R8,\n\tOP_PUSH_R16: handleReadR16,\n\tOP_PUSH_N16: handleN16,\n\tOP_POP_R16: handleWriteR16,\n\tOP_JMP_N16: handleN16,\n\tOP_JC_N16: handleN16,\n\tOP_JNC_N16: handleN16,\n\tOP_JZ_N16: handleN16,\n\tOP_JNZ_N16: handleN16,\n\tOP_CALL_N16: handleN16,\n\tOP_RET: handleNOP,\n\tOP_AND_R8_N8: handleR8_N8,\n\tOP_AND_R8_R8: handleR8_R8,\n\tOP_OR_R8_N8: handleR8_N8,\n\tOP_OR_R8_R8: handleR8_R8,\n\tOP_XOR_R8_N8: handleR8_N8,\n\tOP_XOR_R8_R8: handleR8_R8,\n\tOP_NOT_R8: handleWriteR8,\n\tOP_ADD_R8_N8: handleR8_N8,\n\tOP_ADD_R8_R8: handleR8_R8,\n\tOP_SUB_R8_N8: handleR8_N8,\n\tOP_SUB_R8_R8: handleR8_R8,\n\tOP_INC_R8: handleWriteR8,\n\tOP_DEC_R8: handleWriteR8,\n\tOP_SHL_R8: handleWriteR8,\n\tOP_SHR_R8: handleWriteR8,\n\tOP_CMP_R8_N8: handleR8_N8,\n\tOP_CMP_R8_R8: handleR8_R8\n}\n\ndef main():\n\tglobal fbin\n\t\n\tsrc = sys.argv[1]\n\tdst = sys.argv[2]\n\t\n\t#src = \"program.asm\"\n\t#dst = \"program.bin\"\n\n\tasm(src, dst)\n\n\tprint(\"\\n--- Address Map ---\")\n\n\tfor s in addressMap:\n\t\tprint(s + \" \" + str(hex(addressMap.get(s))) + \" (\" + str(addressMap.get(s)) + \")\")\n\t\t\t\nif __name__ == \"__main__\":\n main()\n\t\n### TESTS ######################################################################\t\n\nassert isBinary(\"%010001001\") == True\nassert isBinary(\"$01001\") == False\nassert isBinary(\"%0012001\") == False\n\nassert isHex(\"$30F\") == True\nassert isHex(\"v10\") == False\n\nassert isMemoryAddress(\"[123]\") == True\nassert isMemoryAddress(\"[$1FF]\") == True\nassert isMemoryAddress(\"123]\") == False\nassert isMemoryAddress(\"[ 234 ]\") == False\n\nassert isMemoryRegister(\"[ab]\") == True\nassert isMemoryRegister(\"[$1FFF]\") == False\n\nassert isNumber(\"$30F\") == True\nassert isNumber(\"12134\") == True\nassert isNumber(\"123 234\") == False\n\nassert isSymbol(\"Test_Loop\") == True\nassert isSymbol(\"asdf test\") == False\nassert isSymbol(\"@Testing\") == False\n\n","sub_path":"asm/asm.py","file_name":"asm.py","file_ext":"py","file_size_in_byte":24484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26388099","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render_to_response, redirect\nfrom django.core import serializers\nimport random\n# Create your views here.\n\nimport pylast\n\n# You have to have your own unique two values for API_KEY and API_SECRET\n# Obtain yours from http://www.last.fm/api/account for Last.fm\nAPI_KEY = \"5805551071db81a56b74eecbced7318c\" # this is a sample key\nAPI_SECRET = \"41a57d40919906f14b91b6209f302f24\"\n\nGS_API_KEY = \"aIv4qlAYsmvq91qAlslGZohfvnLQLrR6P6ydZ7U44DbPf5a%2BF77m3JVUMquSHarm236AYxlffPQhJ7a6%2BReHvw%3D%3D\"\n\n# In order to perform a write operation you need to authenticate yourself\nusername = \"your_user_name\"\npassword_hash = pylast.md5(\"your_password\")\n\nnetwork = pylast.LastFMNetwork(API_KEY, API_SECRET)\n\n\ndef index(request):\n return render_to_response('groovefm/index.html')\n\ndef auth_lastfm(request):\n sg = pylast.SessionKeyGenerator(network)\n url = \"http://www.last.fm/api/auth?api_key=\"+API_KEY\n #url += '&cb=http://apps/groovefm/auth/lastfm/callback'\n return redirect(url)\n\ndef lastfm_callback(request):\n network = pylast.LastFMNetwork(API_KEY, API_SECRET)\n sg = pylast.SessionKeyGenerator(network)\n session_key = sg.get_web_auth_session_key(token=request.GET['token'])\n network = pylast.LastFMNetwork(API_KEY, API_SECRET, session_key)\n user = network.get_authenticated_user()\n artists = user.get_recommended_artists(limit=500)\n random.shuffle(artists)\n\n recommended_artists = []\n for artist in artists[:10]:\n recommended_artists.append({'name': artist.name, 'image': artist.get_cover_image(), 'tracks': artist.get_top_tracks()})\n\n return render_to_response('groovefm/index.html', {'name': \"Name: \" + user.get_name(), 'artists':recommended_artists[:10]})\n","sub_path":"apps/groovefm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18133936","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2009 EduSense BV ().\n# All Rights Reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n'''\nThis module presents a browser like class to browse the web, fill and submit\nforms and to parse the results back in. It is heavily based on BeautifulSoup.\n'''\n\nimport urllib\nfrom BeautifulSoup import BeautifulSoup\n\n__all__ = ['urlsplit', 'urljoin', 'pathbase', 'urlbase', 'SoupForm',\n 'URLAgent'\n ]\n\ndef urlsplit(url):\n '''\n Split an URL into scheme, host and path parts. Helper function.\n '''\n if ':' in url:\n parts = url.split(':')\n scheme = parts[0]\n url = ':'.join(parts[1:])\n else:\n scheme = ''\n host, path = urllib.splithost(url)\n return (scheme, host, path)\n\ndef urljoin(scheme, host, path, args = None):\n '''\n Join scheme, host and path to a full URL.\n Optional: add urlencoded args.\n Helper function.\n '''\n url = '%s://%s/%s' % (scheme or 'http', host, path)\n if args:\n url += '?%s' % urllib.urlencode(args)\n return url\n\ndef pathbase(path):\n '''\n Return the base for the path in order to satisfy relative paths.\n Helper function.\n '''\n if path and '/' in path:\n return path[:path.rfind('/') +1]\n return path\n\ndef urlbase(url):\n '''\n Return the base URL for url in order to satisfy relative paths.\n Helper function.\n '''\n scheme, host, path = urlsplit(url)\n return urljoin(scheme, host, pathbase(path))\n\nclass SoupForm(object):\n '''\n A SoupForm is a representation of a HTML Form in BeautifulSoup terms.\n It has a helper method __setitem__ to set or replace form fields.\n It gets initiated from a soup object.\n '''\n def __init__(self, soup, parent=False):\n '''\n Parse the form attributes and fields from the soup. Make sure\n to get the action right. When parent is set, then the parent\n element is used as anchor for the search for form elements.\n '''\n self._extra_args = {}\n self.soup = soup\n\n # Make sure to use base strings, not unicode\n for attr, value in soup.attrMap.iteritems():\n setattr(self, str(attr), str(value))\n\n # Set right anchor point for harvest\n if parent:\n self.soup = soup.parent\n\n # Harvest input elements. \n self._args = {}\n for item in self.soup.findAll('input'):\n # Make sure to initialize to '' to avoid None strings to appear\n # during submit\n self._args[str(item.get('name'))] = item.get('value') or ''\n\n # Harvest url\n self.scheme, self.host, self.action = urlsplit(self.action)\n self.action, args = urllib.splitquery(self.action)\n if args:\n args = args.split('&')\n for arg in args:\n attr, value = urllib.splitvalue(arg)\n self._extra_args[str(attr)] = value or ''\n\n def __setitem__(self, name, value, force=False):\n '''\n Set values for the form attributes when present\n '''\n if name in self._args or force:\n self._extra_args[name] = value\n else:\n raise AttributeError('No such attribute: %s' % name)\n\n def __getitem__(self, name):\n '''\n Get a value. Set values overrule got values.\n '''\n if name in self._extra_args:\n return self._extra_args[name]\n if name in self._args:\n return self._args[name]\n raise AttributeError('No attribute with name \"%s\" found.' % name)\n\n def set(self, **kwargs):\n '''\n Forcibly sets an attribute to the supplied value, even if it is not\n part of the parsed form.\n Can be useful in situations where forms are deliberatly chunked in\n order to make it difficult to automate form requests, e.g. the\n SWIFT BIC service, which uses JavaScript to add form attributes to an\n emtpy base form.\n '''\n for name, value in kwargs.iteritems():\n self.__setitem__(name, value, force=True)\n\n def args(self):\n '''\n Return the field values as attributes, updated with the modified\n values.\n '''\n args = dict(self._args)\n args.update(self._extra_args)\n return args\n\nclass URLAgent(object):\n '''\n Assistent object to ease HTTP(S) requests.\n Mimics a normal web browser.\n '''\n\n def __init__(self, *args, **kwargs):\n super(URLAgent, self).__init__(*args, **kwargs)\n self._extra_headers = {}\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; U; Linux x86_64; us; rv:1.9.0.10) Gecko/2009042708 Fedora/3.0.10-1.fc9 Firefox/3.0.10',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-us;q=1.0',\n 'Accept-Charset': 'UTF-8,*',\n 'Cache-Control': 'max-age=0'\n }\n\n def add_headers(self, **kwargs):\n self._extra_headers.update(**kwargs)\n\n def open(self, URL):\n '''\n Open a URL and set some vars based on the used URL.\n Meant to be used on a single server.\n '''\n self.scheme, self.host, self.path = urlsplit(URL)\n\n # Create agent\n self.agent = urllib.URLopener()\n\n # Remove additional and unasked for User-Agent header\n # Some servers choke on multiple User-Agent headers\n self.agent.addheaders = []\n headers = self._extra_headers.copy()\n headers.update(self.headers)\n for key, value in headers.iteritems():\n self.agent.addheader(key, value)\n\n # Open webpage\n request = self.agent.open(URL)\n\n # Get and set cookies for next actions\n attributes = request.info()\n if attributes.has_key('set-cookie'):\n self.agent.addheader('Cookie', attributes['set-cookie'])\n\n # Add referer\n self.agent.addheader('Referer', URL)\n\n # Return request\n return request\n\n def submit(self, form, action=None, method=None, **kwargs):\n '''\n Submit a SoupForm. Override missing attributes in action from our own\n initial URL.\n '''\n if action:\n scheme, host, path = urlsplit(action)\n else:\n scheme = form.scheme or self.scheme\n host = form.host or self.host\n action = form.action\n method = (method or form.method).lower()\n args = urllib.urlencode(kwargs or form.args())\n\n if not action.startswith('/'):\n # Relative path\n action = pathbase(self.path) + action\n\n function = getattr(self.agent, 'open_%s' % scheme)\n if method == 'post':\n return function('//%s%s' % (host, action), args)\n return function('//%s%s?%s' % (host, action, args))\n","sub_path":"extra-addons/account_banking/sepa/urlagent.py","file_name":"urlagent.py","file_ext":"py","file_size_in_byte":7640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48251565","text":"import random\n\nchoices = ['r', 'p', 's']\n\nwins = 0\nlosses = 0\nties = 0\n\ndef check_inputs(cmd, cpu_cmd):\n if cmd == cpu_cmd:\n return 0\n elif cmd == \"r\" and cpu_cmd == \"s\" \\\n or cmd == \"p\" and cpu_cmd == \"r\" \\\n or cmd == \"s\" and cpu_cmd == \"p\":\n return 1\n else:\n return -1\n\n\n# Create a REPL loop to process commands\nwhile True: # Loop\n # Read\n cmd = input(\"-> \")\n\n # CPU will pick a random choice\n cpu_choice = random.choice(choices)\n\n # REPL should accept 'r', 'p', 's' commands\n # 'q' to quit\n # Eval\n if cmd in choices:\n result = check_inputs(cmd, cpu_choice)\n if result == 1:\n wins += 1\n print(f\"CPU chooses {cpu_choice}. You win!\")\n elif result == 0:\n ties += 1\n print(f\"CPU chooses {cpu_choice}. You tie.\")\n elif result == -1:\n losses += 1\n print(f\"CPU chooses {cpu_choice}. You lose...\")\n elif cmd == \"q\":\n # Break out of the loop\n print(\"Goodbye!\")\n break\n else:\n print(\"Invalid command.\")\n\n # Print out the score and loop\n print(f\"\\n\\n{wins} / {losses} / {ties}\")\n\n","sub_path":"src/rock_paper_sci/rock_p_s.py","file_name":"rock_p_s.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"527752577","text":"import sys\n\nwd = {'zero': '0', 'one': '1', 'two': '2','five': '5','seven': '7', 'eight': '8',\n 'four': '4', 'three': '3', 'six': '6', 'nine': '9'}\n\nif __name__ == '__main__':\n filename = \"input.txt\"\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n\n with open(filename, \"r\") as read_file:\n for line in read_file:\n if line.strip():\n line_list = line.strip().split(';')\n print(''.join(wd[i] for i in line_list))","sub_path":"easy/104-word-to-digit/word_to_digit.py","file_name":"word_to_digit.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"358830576","text":"from django.contrib.auth import authenticate, login\nfrom django.shortcuts import render, redirect, get_object_or_404 \nfrom socios.models import Socio, ActividadPorPeriodo\nfrom redes.forms import RedForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic import DetailView\nfrom compras.models import Compra\n\ndef activo(request,socio_uiid,periodo):\n existeActivo= ActividadPorPeriodo.objects.filter(socio_id=socio_uiid,activo=1,periodo=periodo).exists()\n #obtienePeriodoActivo= ActividadPorPeriodo.objects.get(socio_id=socio_uiid,activo=1,periodo=periodo)\n return existeActivo\n\ndef puntos(request,socio_uiid,periodo):\n p= ActividadPorPeriodo.objects.get(socio_id=socio_uiid,periodo=periodo)\n return p\n\ndef indexs(request,socio_uiid):\n i = Socio.objects.filter(patrocinador_id=socio_uiid)\n return i\ndef socio(request,socio_uiid):\n s = Socio.objects.get(socio_uiid=socio_uiid)\n return s\n\ndef nivel_0(request,nivel0,periodo,mes):\n indices0=[]#nivel0!!\n #nivelZ=[]\n for i in range(len(nivel0)):\n indice = nivel0[i].socio_uiid\n #actualizar Actividad por periodo para cada patrocinado :v\n activoPeriodo(indice,periodo,mes)\n print('activeUpdatedn0_0') \n if (activo(request,indice,periodo)):\n indices0.append(indice)\n #p=puntos(request,indice,periodo)\n #nivelZ.append(p.puntosTotales) \n #nivelZ.append(socio(request,indice))\n #nivelZ.append(0.1)\n #nivelZ.append(1)\n \n else: # si no se busca el else 5 veces jaja\n indices2= indexs(request,indice) ##desde aca los demas niveles\n for j in range(len(indices2)):\n indices2_2 = indices2[j].socio_uiid\n #actialuzando ActividadPorPeriodo:\n activoPeriodo(indices2_2,periodo,mes)\n print('activeUpdatedn0_2')\n \n if (activo(request,indices2_2,periodo)):\n indices0.append(indices2_2)\n \"\"\" nivelZ.append(socio(request,indices2_2))\n nivelZ.append(0.1)\n nivelZ.append(1)\n p=puntos(request,indices2_2)\n nivelZ.append(p.puntosTotales) \"\"\"\n else:\n indices3 = indexs(request,indices2_2)\n for k in range(len(indices3)):\n indices3_3 = indices3[k].socio_uiid\n activoPeriodo(indices3_3,periodo,mes)\n print('activeUpdatedn0_3')\n if (activo(request,indices3_3,periodo)):\n indices0.append(indices3_3)\n \"\"\" nivelZ.append(socio(request,indices3_3))\n nivelZ.append(0.1)\n nivelZ.append(1)\n p=puntos(request,indices3_3)\n nivelZ.append(p.puntosTotales) \"\"\"\n else:\n indices4 = indexs(request,indices3_3)\n for l in range(len(indices4)):\n indices4_4 = indices4[l].socio_uiid #jiji\n activoPeriodo(indices4_4,periodo,mes)\n print('activeUpdatedn0_4')\n if (activo(request,indices4_4,periodo)):\n indices0.append(indices4_4)\n \"\"\"nivelZ.append(socio(request,indices4_4))\n nivelZ.append(0.1)\n nivelZ.append(1)\n p=puntos(request,indices4_4)\n nivelZ.append(p.puntosTotales) \"\"\"\n else:\n indices5 = indexs(request,indices4_4)\n for m in range(len(indices5)):\n indices5_5 = indices5[m].socio_uiid\n activoPeriodo(indices5_5,periodo,mes)\n print('activeUpdatedn0_5')\n if (activo(request,indices5_5,periodo)):\n indices0.append(indices5_5)\n \"\"\" nivelZ.append(socio(request,indices5_5))\n nivelZ.append(0.1) \n nivelZ.append(1)\n p=puntos(request,indices5_5)\n nivelZ.append(p.puntosTotales) \"\"\" \n else:\n break\n #nivelZ.append(0.1) \n #return (indices0,nivelZ)\n return indices0\n\n\ndef niveles(request,nivel0,periodo,mes):\n indices = []\n #nivelesz= []\n\n #nivel0=indices0[uiids]\n for j in range(len(nivel0)):\n indices2= indexs(request,nivel0[j])##desde aca los demas niveles\n for k in range(len(indices2)):\n indices2_2 = indices2[k].socio_uiid\n activoPeriodo(indices2_2,periodo,mes)\n print('activeUpdatedn1_0')\n if (activo(request,indices2_2,periodo)):\n indices.append(indices2_2)\n #nivelesz.append(socio(request,indices2_2))\n\n\n else:\n indices3 = indexs(request,indices2_2)\n for l in range(len(indices3)):\n indices3_3 = indices3[l].socio_uiid\n activoPeriodo(indices3_3,periodo,mes)\n print('activeUpdatedn1_2')\n if (activo(request,indices3_3,periodo)):\n indices.append(indices3_3)\n \n else:\n indices4 = indexs(request,indices3_3)\n for m in range(len(indices4)):\n indices4_4 = indices5[m].socio_uiid\n activoPeriodo(indices4_4,periodo,mes)\n print('activeUpdatedn1_3')\n if (activo(request,indices4_4,periodo)):\n indices.append(indices4_4)\n \n else:\n indices5 = indexs(request,indices4_4)\n for l in range(len(indices5)):\n indices5_5 = indices5[l].socio_uiid\n activoPeriodo(indices5_5,periodo,mes)\n print('activeUpdatedn1_4')\n if (activo(request,indices5_5,periodo)):\n indices.append(indices5_5)\n \n else:\n indices6 = indexs(request,indices5_5)\n for m in range(len(indices6)):\n indices6_6 = indices6[m].socio_uiid\n activoPeriodo(indices6_6,periodo,mes)\n print('activeUpdatedn1_5')\n if (activo(request,indices6_6,periodo)):\n indices.append(indices6_6)\n \n else:\n break \n return indices\n\ndef periodoExists(periodo,socio_uiid):\n periodo_exists = ActividadPorPeriodo.objects.filter(periodo=periodo,socio_id=socio_uiid).exists()\n return periodo_exists\n\ndef obtenerActividadperiodo(periodo,socio_uiid):\n obtenerActividad = ActividadPorPeriodo.objects.get(periodo=periodo,socio_id=socio_uiid)\n return obtenerActividad\n\ndef crearPeriodo(periodo,socio_uiid,suma,active):\n crearPeriodo= ActividadPorPeriodo.objects.create(periodo=periodo,puntosTotales=suma,activo=active,socio_id=socio_uiid)\n return crearPeriodo\n\ndef activoPeriodo(socio_uiid,periodo,mes):\n #s=Compra.objects.filter(fecha__range=(fi,ff),socio=socio_uiid).exists()\n s=Compra.objects.filter(fecha__month=mes,socio=socio_uiid).exists()\n\n print(s)\n \n if s:\n #s=Compra.objects.filter(fecha__range=(fi,ff),socio=socio_uiid)\n s=Compra.objects.filter(fecha__month=mes,socio=socio_uiid)\n actividad=[]\n for i in range(len(s)):\n print(s[i].puntos_compra)\n a = s[i].puntos_compra\n actividad.append(a)\n \n print(actividad)\n suma = 0\n for i in actividad:\n suma = suma + i\n print(suma)\n if suma >= 300:\n print('activo')\n\n active = 1\n \n pE = periodoExists(periodo,socio_uiid)\n if pE:\n pa = obtenerActividadperiodo(periodo,socio_uiid)\n pa.puntosTotales=suma\n pa.activo=active\n pa.save()\n print('updatedActivo')\n else:\n pa = crearPeriodo(periodo,socio_uiid,suma,active)\n pa.save()\n print('createdPeriodoActivo')\n else:\n print('no alcanzo jaja')\n active = 0\n\n pE = periodoExists(periodo,socio_uiid)\n if pE:\n pa = obtenerActividadperiodo(periodo,socio_uiid)\n pa.puntosTotales=suma\n pa.activo=active\n pa.save()\n print('updatedNa')\n else:\n pa = crearPeriodo(periodo,socio_uiid,suma,active)\n pa.save()\n print('createdPeriodoNa')\n return suma\n\n\n\n else:\n print('Inactivo')\n suma = 0\n active = 0\n pE = periodoExists(periodo,socio_uiid)\n if pE:\n per = obtenerActividadperiodo(periodo,socio_uiid)\n per.puntosTotales=suma\n per.activo=active\n per.save()\n print('updatedInactivo')\n \n else:\n \n crearPeriodoInactivo = crearPeriodo(periodo,socio_uiid,suma,active)\n crearPeriodoInactivo.save()\n print('createdInactivo')\n \n return suma\n\ndef show (request,red,periodo):\n rt=[]\n gss=[]\n for a in range(len(red)):\n see=[]\n gs=[]\n b = a+1\n for i in red[a]:\n se=[]\n #print (i)\n nom = socio(request,i)\n nombre = nom.first_name\n p = puntos(request,i,periodo)\n pun = p.puntosTotales\n se.append(i)\n se.append(nombre)\n se.append(pun)\n se.append(b)\n if b==1 or b==2:\n porcentaje = 0.1\n if b==3:\n porcentaje = 0.15\n if b==4:\n porcentaje = 0.2\n if b==5:\n porcentaje = 0.25\n se.append(porcentaje)\n g = porcentaje * pun\n gs.append(g)\n se.append(g)\n see.append(se)\n\n gss.append(gs)\n \n rt.append(see)\n\n return(rt,gss)","sub_path":"redes/funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":11427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567611736","text":"# -*- coding: utf-8 -*-\n\nimport PIL\nfrom kotti.util import _\n# from kotti.util import extract_from_settings\nfrom kotti.views.file import AddFileFormView, EditFileFormView\nfrom kotti.resources import Image\nfrom plone.scale.scale import scaleImage\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\nPIL.ImageFile.MAXBLOCK = 33554432\n\n# default image scales\nimage_scales = {\n 'thumb': [160, 120],\n 'carousel': [560, 420]}\n\n\nclass EditImageFormView(EditFileFormView):\n\n pass\n\n\nclass AddImageFormView(AddFileFormView):\n\n item_type = _(u\"Image\")\n\n def add(self, **appstruct):\n\n buf = appstruct['file']['fp'].read()\n\n return Image(\n title=appstruct['title'],\n description=appstruct['description'],\n data=buf,\n filename=appstruct['file']['filename'],\n mimetype=appstruct['file']['mimetype'],\n size=len(buf), )\n\n\nclass ImageView(object):\n\n def __init__(self, context, request):\n\n self.context = context\n self.request = request\n\n @view_config(context=Image,\n name='view',\n permission='view',\n renderer='kotti:templates/view/image.pt')\n def view(self):\n return {}\n\n @view_config(context=Image,\n name=\"image\",\n permission='view')\n def image(self):\n \"\"\"return the image in a specific scale, either inline (default) or as attachment\"\"\"\n\n subpath = list(self.request.subpath)\n\n if (len(subpath) > 0) and (subpath[-1] == \"download\"):\n disposition = \"attachment\"\n subpath.pop()\n else:\n disposition = \"inline\"\n\n if len(subpath) == 1:\n scale = subpath[0]\n if scale in image_scales:\n # /path/to/image/scale/thumb\n width, height = image_scales[scale]\n else:\n # /path/to/image/scale/160x120\n try:\n width, height = [int(v) for v in scale.split(\"x\")]\n except ValueError:\n width, height = (None, None)\n\n elif len(subpath) == 2:\n # /path/to/image/scale/160/120\n try:\n width, height = [int(v) for v in subpath]\n except ValueError:\n width, height = (None, None)\n\n else:\n # don't scale at all\n width, height = (None, None)\n\n if width and height:\n image, format, size = scaleImage(self.context.data,\n width=width,\n height=height,\n direction=\"thumb\")\n else:\n image = self.context.data\n\n res = Response(\n headerlist=[('Content-Disposition', '%s;filename=\"%s\"' % (disposition,\n self.context.filename.encode('ascii', 'ignore'))),\n ('Content-Length', str(len(image))),\n ('Content-Type', str(self.context.mimetype)), ],\n app_iter=image)\n\n return res\n\n\ndef includeme(config):\n # TODO: load predefined scales from .ini\n # image_scales = extract_from_settings('kotti.image_scale.', config)\n\n config.scan(\"kotti.views.image\")\n config.add_view(AddImageFormView,\n name=Image.type_info.add_view,\n permission='add',\n renderer='kotti:templates/edit/node.pt',)\n config.add_view(EditImageFormView,\n context=Image,\n name='edit',\n permission='edit',\n renderer='kotti:templates/edit/node.pt', )\n","sub_path":"kotti/views/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"219401861","text":"import io\nimport os\nimport unittest\nimport threading\n\nimport synapse.link as s_link\nimport synapse.daemon as s_daemon\nimport synapse.eventbus as s_eventbus\nimport synapse.telepath as s_telepath\n\nfrom synapse.tests.common import *\n\n\nclass Woot:\n def foo(self,x,y=20):\n return x + y\n\n def pid(self):\n return os.getpid()\n\nclass Blah:\n def __init__(self, woot):\n self.woot = woot\n\nclass DaemonTest(SynTest):\n\n def test_daemon_timeout(self):\n\n daemon = s_daemon.Daemon()\n link = daemon.listen('tcp://127.0.0.1:0/?timeout=0.1')\n\n relay = s_link.getLinkRelay(link)\n sock = relay.connect()\n\n self.assertEqual( sock.recvobj(),None)\n\n sock.fini()\n daemon.fini()\n\n def test_daemon_on(self):\n\n class Foo:\n def bar(self):\n return 'baz'\n\n dmon = s_daemon.Daemon()\n link = dmon.listen('tcp://127.0.0.1:0/')\n\n bus = s_eventbus.EventBus()\n foo = Foo()\n\n dmon.share('bus', bus)\n dmon.share('foo', foo)\n\n port = link[1].get('port')\n\n bprox = s_telepath.openurl('tcp://127.0.0.1/bus', port=port)\n fprox = s_telepath.openurl('tcp://127.0.0.1/foo', port=port)\n\n evt = threading.Event()\n def woot(mesg):\n evt.set()\n\n bprox.on('woot', woot)\n fprox.on('woot', woot)\n\n bus.fire('woot')\n\n evt.wait(timeout=2)\n\n fprox.off('woot', woot)\n\n self.assertTrue( evt.is_set() )\n\n def test_daemon_conf(self):\n\n class DmonConfTest(s_daemon.DmonConf,s_eventbus.EventBus):\n\n def __init__(self):\n s_eventbus.EventBus.__init__(self)\n s_daemon.DmonConf.__init__(self)\n\n conf = {\n\n 'vars':{\n 'hehe':10,\n },\n 'ctors':(\n ('woot','ctor://synapse.tests.test_daemon.Woot()'),\n ('blah','ctor://synapse.tests.test_daemon.Blah(woot)'),\n ),\n }\n\n dcon = DmonConfTest()\n dcon.loadDmonConf(conf)\n\n self.assertEqual( dcon.locs.get('hehe'), 10 )\n self.assertEqual( dcon.locs.get('woot').foo(10,y=30), 40 )\n self.assertEqual( dcon.locs.get('blah').woot.foo(10,y=30), 40 )\n\n def test_daemon_conf_onfini(self):\n\n conf = {\n 'ctors': (\n ('fini', 'ctor://synapse.eventbus.EventBus()'),\n ),\n 'share': (\n ('fini', {'onfini': True}),\n ),\n }\n\n dmon = s_daemon.Daemon()\n dmon.loadDmonConf(conf)\n dmon.fini()\n self.assertTrue(dmon.shared.get('fini').isfini)\n\n def test_daemon_conf_fork(self):\n self.thisHostMustNot(platform='windows')\n\n iden = guid()\n\n conf = {\n 'forks':(\n ('fork0',{\n 'ctors':(\n ('haha','ctor://synapse.tests.test_daemon.Woot()'),\n ),\n 'share': (\n ('haha',{}),\n ),\n 'listen':(\n 'local://%s' % (iden,),\n ),\n }),\n ),\n }\n\n dmon = s_daemon.Daemon()\n dmon.loadDmonConf(conf)\n\n prox = s_telepath.openurl('local://%s/haha?retry=6' % (iden,))\n\n pid0 = prox.pid()\n self.assertNotEqual( pid0, os.getpid() )\n\n prox.fini()\n\n #dmon.killDmonFork('fork0')\n\n #prox = s_telepath.openurl('local://%s/haha?retry=6' % (iden,))\n\n #pid1 = prox.pid()\n #self.assertNotEqual( pid0, pid1 )\n #self.assertNotEqual( pid1, os.getpid() )\n\n #prox.fini()\n dmon.fini()\n\n def test_daemon_sessconf(self):\n\n with self.getTestDir() as dirname:\n\n dmon = s_daemon.Daemon()\n\n conf = {\n 'sessions':{\n 'maxtime':99999,\n 'savefile':os.path.join(dirname,'sessions.sql3'),\n },\n }\n\n dmon.loadDmonConf(conf)\n\n sess0 = dmon.getNewSess()\n iden = sess0.iden\n\n sess0.put('woot',10)\n\n dmon.fini()\n\n dmon = s_daemon.Daemon()\n dmon.loadDmonConf(conf)\n\n sess1 = dmon.getSessByIden(iden)\n self.eq( sess1.get('woot'), 10 )\n\n dmon.fini()\n\n def test_daemon_ctor_config(self):\n\n conf = {\n\n 'ctors':(\n ('foo','ctor://synapse.cortex.openurl(\"ram://\")', {'config':'woot'}),\n ('bar','ctor://synapse.cortex.openurl(\"ram://\")', {'configs':('woot','blah')}),\n ),\n\n 'configs':{\n 'woot':{},\n }\n\n }\n\n with s_daemon.Daemon() as dmon:\n self.assertRaises(NoSuchConf, dmon.loadDmonConf, conf )\n\n conf['configs']['blah'] = {'newp':1}\n\n with s_daemon.Daemon() as dmon:\n self.assertRaises(NoSuchOpt, dmon.loadDmonConf, conf )\n\n conf['configs']['blah'].pop('newp',None)\n conf['configs']['blah']['caching'] = 'TRUE'\n\n with s_daemon.Daemon() as dmon:\n dmon.loadDmonConf(conf)\n core = dmon.locs.get('bar')\n self.eq( core.caching, 1 )\n\n","sub_path":"synapse/tests/test_daemon.py","file_name":"test_daemon.py","file_ext":"py","file_size_in_byte":5238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182671110","text":"import numpy as np\nimport cv2\nimport pickle\n\ndef obj_img_pts(objp,fnames,ptsn,tosave = './'):\n \n # Arrays to store object points and image points from all the images.\n #3d points in real world space\n objpoints = []\n #2d points in image plane.\n imgpoints = []\n \n #for saving the objpoints and imgpoints\n points_pickle = {}\n log = []\n \n imgs={} \n for fname in fnames:\n img = cv2.imread(fname)\n\n if '/' in fname:\n fname = fname.split('/')[-1]\n \n imgs[fname]=img\n \n isize=(img.shape[1],img.shape[0])\n \n # Step through the list and search for chessboard corners \n for fname in imgs.keys(): \n img=imgs[fname]\n \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, ptsn, None)\n\n # If found, add object points, image points\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n else:\n print('NO CORNERS FOUND ON: '+fname)\n \n points_pickle['objpoints'] = objpoints\n points_pickle['imgpoints'] = imgpoints\n pickle.dump(points_pickle,open('./obj_img_points.pickle','wb'))\n\n print('calibrating Camera is DONE!')\n \n return objpoints,imgpoints,isize\n\ndef Matrix_Coeffs(objpoints,imgpoints,isize):\n \n retval,comeraMatrix,distCoeffs,rvecs,tvexs = cv2.calibrateCamera(objpoints,imgpoints,isize,None,None)\n \n calibrateCamera_pickle={}\n \n calibrateCamera_pickle['retval']=retval\n calibrateCamera_pickle['comeraMatrix']=comeraMatrix\n calibrateCamera_pickle['distCoeffs']=distCoeffs\n calibrateCamera_pickle['rvecs']=rvecs\n calibrateCamera_pickle['tvexs']=tvexs\n \n pickle.dump(calibrateCamera_pickle,open('./calibrateCamera.pickle','wb'))\n \n return comeraMatrix,distCoeffs\n\n# Define a function that takes an chessboard, number of x and y points, \n# camera matrix and distortion coefficients\ndef corners_unwarp(img, nx, ny, mtx, dist,offset=100):\n # Use the OpenCV undistort() function to remove distortion\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n # Convert undistorted image to grayscale\n gray = cv2.cvtColor(undist, cv2.COLOR_BGR2GRAY)\n # Search for corners in the grayscaled image\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n \n warped=None\n M=None\n if ret == True:\n # If we found corners, draw them! (just for fun)\n cv2.drawChessboardCorners(undist, (nx, ny), corners, ret)\n # Choose offset from image corners to plot detected corners\n # This should be chosen to present the result at the proper aspect ratio\n # My choice of 100 pixels is not exact, but close enough for our purpose here\n \n # Grab the image shape\n img_size = (gray.shape[1], gray.shape[0])\n\n # For source points I'm grabbing the outer four detected corners\n src = np.float32([corners[0], corners[nx-1], corners[-1], corners[-nx]])\n # For destination points, I'm arbitrarily choosing some points to be\n # a nice fit for displaying our warped result \n # again, not exact, but close enough for our purposes\n dst = np.float32([[offset, offset], [img_size[0]-offset, offset], \n [img_size[0]-offset, img_size[1]-offset], \n [offset, img_size[1]-offset]])\n # Given src and dst points, calculate the perspective transform matrix\n M = cv2.getPerspectiveTransform(src, dst)\n # Warp the image using OpenCV warpPerspective()\n warped = cv2.warpPerspective(undist, M, img_size)\n\n # Return the resulting image and matrix\n return undist,warped, M","sub_path":"calibrating_camera.py","file_name":"calibrating_camera.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590873144","text":"import numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\ndata = np.float32(np.vstack(\r\n (np.random.randint(0, 40, (50, 2)), np.random.randint(30, 70, (50, 2)), np.random.randint(60, 100, (50, 2)))))\r\n\r\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)\r\n\r\n\r\n# attempts = 10, which specifies the number of times the algorithm is executed using different initial labellings (the\r\n# algorithm returns the labels that yield the best compactness)\r\nret, label, center = cv2.kmeans(data, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)\r\n\r\nA = data[label.ravel() == 0]\r\nB = data[label.ravel() == 1]\r\n\r\n\r\nfig = plt.figure(figsize=(12, 6))\r\nplt.suptitle(\"K-means clustering algorithm\", fontsize=14, fontweight='bold')\r\nfig.patch.set_facecolor('silver')\r\n\r\n\r\nax = plt.subplot(1, 2, 1)\r\nplt.scatter(data[:, 0], data[:, 1], c='c')\r\nplt.title(\"data\")\r\n\r\nax = plt.subplot(1, 2, 2)\r\nplt.scatter(A[:, 0], A[:, 1], c='b')\r\nplt.scatter(B[:, 0], B[:, 1], c='g')\r\nplt.scatter(center[:, 0], center[:, 1], s=100, c='m', marker='s')\r\nplt.title(\"clustered data and centroids (K = 2)\")\r\n\r\nplt.show()\r\n","sub_path":"10 Machine Learning/01 K-Means Clustering/k_means_clustering.py","file_name":"k_means_clustering.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376344588","text":"# TensorFlow implementation of the Guided Anisotropic Diffusion algorithm\n# Original PyTorch implementation by Rodrigo Caye Daudt (https://rcdaudt.github.io)\n# Reference paper:\n# Rodrigo Caye Daudt, Bertrand Le Saux, Alexandre Boulch, and Yann Gousseau.\n# \"Guided anisotropic diffusion and iterative learning for weakly supervised change detection.\"\n# In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition Workshops, 2019.\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\ndef g(x, K=5):\n return 1.0 / (1.0 + (tf.abs((x * x)) / (K * K)))\n\n\ndef get_image_gradients(image):\n dv = image[:, :, 1:, 1:-1] - image[:, :, :-1, 1:-1]\n dh = image[:, :, 1:-1, 1:] - image[:, :, 1:-1, :-1]\n return dv, dh\n\n\ndef diffusion_coefficient(gradient_v, gradient_h, K):\n cv = g(tf.reduce_mean(gradient_v, 1), K)\n ch = g(tf.reduce_mean(gradient_h, 1), K)\n return cv, ch\n\n\n@tf.function\ndef diffuse(image, lambda_, K, coeffs=None, return_coeffs=False):\n # Compute gradients from the image\n dv, dh = get_image_gradients(image)\n if coeffs is None:\n cv, ch = diffusion_coefficient(dv, dh, K)\n else:\n cv, ch = coeffs\n diffused = image[:, :, 1:-1, 1:-1] + lambda_ * (\n cv[:, 1:, :] * dv[:, :, 1:, :]\n - cv[:, :-1, :] * dv[:, :, :-1, :]\n + ch[:, :, 1:] * dh[:, :, :, 1:]\n - ch[:, :, :-1] * dh[:, :, :, :-1]\n )\n image = tf.pad(diffused, tf.constant([[0, 0], [0, 0], [1, 1], [1, 1]]))\n if return_coeffs:\n return image, cv, ch\n else:\n return image\n\n\n@tf.function\ndef anisotropic_diffusion(\n input_image,\n first_guide,\n second_guide=None,\n iterations=500,\n lambda_=0.24,\n K=5,\n is_log=True,\n verbose=False,\n):\n\n if is_log:\n input_image = tf.math.exp(input_image)\n\n for t in range(iterations):\n if verbose:\n print(\"Iteration {}\".format(t))\n\n # Perform diffusion on the first guide\n first_guide, cv1, ch1 = diffuse(first_guide, lambda_, K, return_coeffs=True)\n\n # Perform diffusion on the second guide (if specified)\n if second_guide is not None:\n second_guide, cv2, ch2 = diffuse(second_guide, lambda_, K, return_coeffs=True)\n cv = tf.math.minimum(cv1, cv2)\n ch = tf.math.minimum(ch1, ch2)\n else:\n cv, ch = cv1, ch1\n\n input_image = diffuse(input_image, lambda_, K, coeffs=(cv, ch))\n\n return input_image\n","sub_path":"GAD.py","file_name":"GAD.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"353785979","text":"#Platform Class\n\nimport pygame\n\nclass platform:\n\tdef __init__(self,x,y,width,height,color):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.color = color\n\n\tdef draw(self, surface):\n\t\tpygame.draw.rect(surface,self.color,[self.x,self.y,self.width,self.height])\n\n\tdef isContact(self,playerPosition,player):\n\t\tif (((self.x - player.width) <= playerPosition[\"x\"] <= (self.x + self.width)) and \n\t\t\t((self.y - player.height) <= playerPosition['y'] <= (self.y + self.height))):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False","sub_path":"Pygame-1/PlatformClass.py","file_name":"PlatformClass.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539977863","text":"import sys\nimport os\nfrom os import path\nimport math\nimport shutil\nimport time\nimport csv\nimport shutil\nimport itertools\nimport pandas as pd\nimport matplotlib\nimport numpy as np\nimport random\nfrom cartesian_product import cartesian_product\nfrom filelock import Timeout, FileLock\nmatplotlib.use('TkAgg') \nfrom multiprocessing import Pool,Lock\nmutex = Lock()\nimport matplotlib.pyplot as plt\n\nstart_time = time.time()\nhome_directory=os.environ['HOME_SRC']\nlta_main_directory = home_directory + \"ta_expander1/\"\nlta_expander_output_directory = lta_main_directory + \"lta_output/\"\npacket_level_simulator_directory = os.environ['PACKET']\npacket_level_simulator_demo_directory = packet_level_simulator_directory + \"temp1/demo/\"\npacket_level_simulator_example_directory = packet_level_simulator_directory +\"example/runs/\"\n\n# Check run folder path given as first argument\nrun_folder_path = packet_level_simulator_demo_directory\nif not os.path.isdir(run_folder_path):\n print(\"The run folder path does not exist: \" + run_folder_path)\n print_usage()\n exit()\n\n# Create analysis folder\nanalysis_folder_path = run_folder_path + '/analysis'\nif not os.path.exists(analysis_folder_path):\n os.makedirs(analysis_folder_path)\n\n\n#intrapod_design_strategy = [\"Xpander\",\"ta_expander\"]\nintrapod_design_strategy = [\"Xpander\",\"ta_expander\",\"Jellyfish\"]\nstats_params = [\"all_99.9th_fct_ms\",\"all_99th_fct_ms\",\"all_flows_completed_fraction\",\"all_mean_fct_ms\"]\nparameters = {\"np\":10,\"nspp\":10,\"sr\":20,\"oc\":2.0,\"lc\":40,\"sd\":783,\"ee\":\"cut\",\"routing\":\"ksp\",\"tm\":\"clustered\",\"nf\":5000,\"fd\":\"lognormal\",\"kpaths\":1}\n#param_name = \"_np{}_nspp{}_ksp{}_{}s_ll{}_bs{}\".format(parameters[\"np\"],parameters[\"nspp\"],ksp_path,run_time,link_latency,buffer_size)\ncolor = {\"Jellyfish\":\"red\",\"ta_expander\":\"black\",\"Xpander\":\"green\",\"Xentropy\":\"grey\"}\n\n#check if topology file already exists\ndef check_file_exist():\n\tos.chdir(lta_expander_output_directory)\n\tfor intrapod in intrapod_design_strategy:\n\t\tif not os.path.exists(lta_expander_output_directory+\"lta_{}_np{}_nspp{}_sr{}_oc{}_lc{}_sd{}_inter{}_intra{}_{}_{}_nf{}_{}_{}.topology\".format(intrapod,parameters[\"np\"],parameters[\"nspp\"], parameters[\"sr\"],parameters[\"oc\"],parameters[\"lc\"],parameters[\"sd\"],1.0,1.0,parameters[\"routing\"],parameters[\"fd\"],parameters[\"nf\"],parameters[\"ee\"],parameters[\"tm\"])):\n\t\t\tos.chdir(lta_main_directory)\n\t\t\tos.system('chmod +x uniform_large_expander_simulator')\n\t\t\tos.system('./uniform_large_expander_simulator -write_topology_to_proto=true -write_traffic_to_proto=true -write_topology_to_netbench=true -write_traffic_to_netbench=true -output_directory=' + lta_expander_output_directory + ' -npods={} -nswitches={} -nradices={} -cheeger={} -nclusters={} -link_cap={} -seed={} -interpod_ratio={} -intrapod_ratio={} -routing={} -k_paths={} -flow_distribution={} -num_flows={} -distr_mean={} -distr_stdev={} -tm={} -edge_exp={}'.format(parameters[\"np\"],parameters[\"nspp\"], parameters[\"sr\"],parameters[\"oc\"], 3, parameters[\"lc\"], parameters[\"sd\"], 1.0, 1.0,parameters[\"routing\"],parameters[\"kpaths\"],parameters[\"fd\"],parameters[\"nf\"],5.0,2.0,parameters[\"tm\"],parameters[\"ee\"]))\n\n\ndef frange(start, stop, step):\n\ti = start\n\twhile i < stop:\n\t\tyield i\n\t\ti += step\n\ndef analyze_flow_completion():\n with open(run_folder_path + '/flow_completion.csv.log') as file:\n reader = csv.reader(file)\n\n # To enable preliminary read to determine size:\n # data = list(reader)\n # row_count = len(data)\n\n # Column lists\n flow_ids = []\n source_ids = []\n target_ids = []\n sent_bytes = []\n total_size_bytes = []\n start_time = []\n end_time = []\n duration = []\n completed = []\n\n print(\"Reading in flow completion log file...\")\n\n # Read in column lists\n for row in reader:\n flow_ids.append(float(row[0]))\n source_ids.append(float(row[1]))\n target_ids.append(float(row[2]))\n sent_bytes.append(float(row[3]))\n total_size_bytes.append(float(row[4]))\n start_time.append(float(row[5]))\n end_time.append(float(row[6]))\n duration.append(float(row[7]))\n completed.append(row[8] == 'TRUE')\n if len(row) != 9:\n print(\"Invalid row: \", row)\n exit()\n\n print(\"Calculating statistics...\")\n\n statistics = {\n 'general_num_flows': len(flow_ids),\n 'general_num_unique_sources': len(set(source_ids)),\n 'general_num_unique_targets': len(set(target_ids)),\n 'general_flow_size_bytes_mean': np.mean(total_size_bytes),\n 'general_flow_size_bytes_std': np.std(total_size_bytes)\n }\n\n range_low = [-1, -1, -1, 100000, 2434900, 1000000, 10000000]\n range_high = [-1, 100000, 2434900, -1, -1, -1, -1]\n range_name = [\"all\", \"less_100KB\", \"less_2.4349MB\", \"geq_100KB\", \"geq_2.4349MB\", \"geq_1MB\", \"geq_10MB\"]\n range_completed_duration = [[], [], [], [], [], [], []]\n range_completed_throughput = [[], [], [], [], [], [], []]\n range_num_finished_flows = [0, 0, 0, 0, 0, 0, 0]\n range_num_unfinished_flows = [0, 0, 0, 0, 0, 0, 0]\n range_low_eq = [0, 0, 0, 1, 1, 1, 1,]\n range_high_eq = [0, 0, 0, 1, 1, 1, 1,]\n\n\n # Go over all flows\n for i in range(0, len(flow_ids)):\n\n # Range-specific\n for j in range(0, len(range_name)):\n if (\n (range_low[j] == -1 or (range_low_eq[j] == 0 and total_size_bytes[i] > range_low[j]) or (range_low_eq[j] == 1 and total_size_bytes[i] >= range_low[j])) and\n (range_high[j] == -1 or (range_high_eq[j] == 0 and total_size_bytes[i] < range_high[j]) or (range_high_eq[j] == 1 and total_size_bytes[i] <= range_high[j]))\n ):\n if completed[i]:\n range_num_finished_flows[j] += 1\n range_completed_duration[j].append(duration[i])\n range_completed_throughput[j].append(total_size_bytes[i] * 8 / duration[i])\n\n else:\n range_num_unfinished_flows[j] += 1\n\n # Ranges statistics\n for j in range(0, len(range_name)):\n\n # Number of finished flows\n statistics[range_name[j] + '_num_flows'] = range_num_finished_flows[j] + range_num_unfinished_flows[j]\n statistics[range_name[j] + '_num_finished_flows'] = range_num_finished_flows[j]\n statistics[range_name[j] + '_num_unfinished_flows'] = range_num_unfinished_flows[j]\n total = (range_num_finished_flows[j] + range_num_unfinished_flows[j])\n if range_num_finished_flows[j] != 0:\n statistics[range_name[j] + '_flows_completed_fraction'] = float(range_num_finished_flows[j]) / float(total)\n statistics[range_name[j] + '_mean_fct_ns'] = np.mean(range_completed_duration[j])\n statistics[range_name[j] + '_median_fct_ns'] = np.median(range_completed_duration[j])\n statistics[range_name[j] + '_99th_fct_ns'] = np.percentile(range_completed_duration[j], 99)\n statistics[range_name[j] + '_99.9th_fct_ns'] = np.percentile(range_completed_duration[j], 99.9)\n statistics[range_name[j] + '_mean_fct_ms'] = statistics[range_name[j] + '_mean_fct_ns'] / 1000000\n statistics[range_name[j] + '_median_fct_ms'] = statistics[range_name[j] + '_median_fct_ns'] / 1000000\n statistics[range_name[j] + '_99th_fct_ms'] = statistics[range_name[j] + '_99th_fct_ns'] / 1000000\n statistics[range_name[j] + '_99.9th_fct_ms'] = statistics[range_name[j] + '_99.9th_fct_ns'] / 1000000\n statistics[range_name[j] + '_throughput_mean_Gbps'] = np.mean(range_completed_throughput[j])\n statistics[range_name[j] + '_throughput_median_Gbps'] = np.median(range_completed_throughput[j])\n statistics[range_name[j] + '_throughput_99th_Gbps'] = np.percentile(range_completed_throughput[j], 99)\n statistics[range_name[j] + '_throughput_99.9th_Gbps'] = np.percentile(range_completed_throughput[j], 99.9)\n statistics[range_name[j] + '_throughput_1th_Gbps'] = np.percentile(range_completed_throughput[j], 1)\n statistics[range_name[j] + '_throughput_0.1th_Gbps'] = np.percentile(range_completed_throughput[j], 0.1)\n else:\n statistics[range_name[j] + '_flows_completed_fraction'] = 0\n\n # Print raw results\n print('Writing to result file flow_completion.statistics...')\n with open(analysis_folder_path + '/flow_completion.statistics', 'w+') as outfile:\n for key, value in sorted(statistics.items()):\n outfile.write(str(key) + \"=\" + str(value) + \"\\n\")\n\t\t\t\t\n with open(analysis_folder_path + '/range_completed_duration.statistics', 'w+') as write_file:\n for element in sorted(range_completed_duration[0]):\n write_file.write(str(element) + \"\\n\")\n \n\n#without seed averaging \ndef for_loop(intrapod,param_name,file_name):\n#for intrapod in intrapod_design_strategy: (tried this for parallel processing)\n\tfile = \"lta_{}_np{}_nspp{}_sr{}_oc{}_lc{}_sd{}_inter{}_intra{}_{}_{}_nf{}_{}_{}.topology\".format(intrapod,parameters[\"np\"],parameters[\"nspp\"], parameters[\"sr\"],parameters[\"oc\"],parameters[\"lc\"],parameters[\"sd\"],1.0,1.0,parameters[\"routing\"],parameters[\"fd\"],parameters[\"nf\"],parameters[\"ee\"],parameters[\"tm\"])\n\t\n\tfor Lambda in frange(0.1,1.0,0.1):\n\t\tos.chdir(packet_level_simulator_example_directory)\n\t\t#Lambdapr = math.floor(Lambda * 514.403)\n\t\tLambdapr = math.floor(Lambda * 32921.8)\n\t\ttemp_name = intrapod + \"_lambda_\" + str(Lambdapr) + file_name\n\t\tproperties_filename = \"temp_\" + file_name\n\t\tf = open(properties_filename, \"w+\")\n\t\tf.write(\"scenario_topology_file={}{}\".format(lta_expander_output_directory,file)) \n\t\tf.write('\\n')\n\t\tf.write(\"traffic_lambda_flow_starts_per_s={}\".format(Lambdapr))\n\t\tf.write('\\n')\n\t\t#f.write(\"run_folder_name=demo\")\n\t\t#f.write('\\n')\n\t\twith open(file_name,\"r\", encoding = \"ISO-8859-1\") as f1:\n\t\t\tf.write('\\n')\n\t\t\tcount = 0\n\t\t\tfor line in f1:\n\t\t\t\tif not (line.startswith(\"scenario_topology_file\") or line.startswith(\"traffic_lambda_flow_starts_per_s\") or line.startswith(\"analysis_command\")):\n\t\t\t\t\tf.write(line)\n\t\t\t\tif line.startswith(\"traffic_probabilities_file\"):\n\t\t\t\t\tcount += 1\n\t\t\tf.write('\\n')\n\t\t\tif count == 0:\n\t\t\t\tf.write(\"traffic_probabilities_file={}lta_np{}_nspp{}_sr{}_oc{}_lc{}_sd{}_inter{}_intra{}_{}_{}_nf{}_{}_{}_full_tm.txt\".format(lta_expander_output_directory,parameters[\"np\"],parameters[\"nspp\"], parameters[\"sr\"],parameters[\"oc\"],parameters[\"lc\"],parameters[\"sd\"],1.0,1.0,parameters[\"routing\"],parameters[\"fd\"],parameters[\"nf\"],parameters[\"ee\"],parameters[\"tm\"]))\n\t\tf.close()\n\t\t#run the packet level simulator and move the result .statistics file to the ta_expander result folder\n\t\tos.chdir(packet_level_simulator_directory)\n\t\tos.system('java -jar -ea NetBench.jar ./example/runs/{}'.format(properties_filename))\n\t\tanalyze_flow_completion()\n\t\tos.chdir(packet_level_simulator_demo_directory+ \"analysis/\")\n\t\tlock = FileLock(\"flow_completion.statistics.lock\")\n\t\twith lock:\n\t\t\twith open(\"flow_completion.statistics\") as f2:\n\t\t\t\twith open(\"{}.txt\".format(temp_name),\"w+\") as f3:\n\t\t\t\t\tfor line in f2:\n\t\t\t\t\t\t#parse underscores\n\t\t\t\t\t\tif line.startswith(\"all\"):\n\t\t\t\t\t\t\tf3.write(line)\n\t\tsrc_ = packet_level_simulator_demo_directory + \"analysis/{}.txt\".format(temp_name)\n\t\tdst_ = packet_level_simulator_example_directory + \"plots/{}.txt\".format(temp_name)\n\t\tshutil.move(src_, dst_)\n\t\tos.chdir(packet_level_simulator_example_directory)\n\t\tos.remove(properties_filename)\n\t\t\n\t\tos.chdir(packet_level_simulator_example_directory +\"plots\")\n\t\twith open(temp_name +\".txt\", \"r\") as f1: #.txt file from exported from netbench analysis\t\n\t\t\theader = []\n\t\t\tvalues = []\n\t\t\tfor line in f1:\n\t\t\t\tsplit_line = line.split(\"=\")\n\t\t\t\theader.append(split_line[0])\n\t\t\t\tvalues.append(split_line[1])\n\t\t\ttemp_lines = []\n\t\t\twith open(intrapod+file_name +\".csv\", \"a+\") as csv_write, open(intrapod+file_name+\".csv\", \"r\") as csv_read:\n\t\t\t\tresult_reader = csv.reader(csv_read, delimiter=\",\")\n\t\t\t\tresult_writer = csv.writer(csv_write, delimiter=\",\")\n\t\t\t\tif os.stat(intrapod+file_name +\".csv\").st_size == 0:\n\t\t\t\t\tresult_writer.writerow([\"lambda\"]+header)\n\t\t\t\t\t#result_writer.writerow([Lambdapr]+[float(j) for j in values])\n\t\t\t\t#check for repetition and average over the seeds\n\t\t\t\tcount = 0\n\t\t\t\tcsv_read.seek(0)\n\t\t\t\tfor row in result_reader:\n\t\t\t\t\tif row[0] == str(Lambdapr) or row[0] == Lambdapr:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\tbreak\n\t\t\t\tif count == 0 and values:\n\t\t\t\t\tresult_writer.writerow([Lambdapr]+values)\n\t\t\t\t\t\t\t\ndef plot(file_name):\n\t#still need to come up with a way that accomadates multiprocessing for this function\n\tfig, axs = plt.subplots(2, 2)\n\taxes = [axs[0,0], axs[0,1], axs[1,0], axs[1,1]]\n\tos.chdir(packet_level_simulator_example_directory+\"plots\")\n\tfor intrapod in intrapod_design_strategy:\t\n\t\tcount = 0\n\t\tfor param in stats_params:\n\t\t\tprint(\"saving plot as \" + \"{}\".format(intrapod+file_name))\n\t\t\tdf = pd.read_csv(intrapod+file_name+\".csv\",engine='python',error_bad_lines=False)\n\t\t\tdf1=df.sort_values(by='lambda')\n\t\t\tdf1.plot(kind='line',x=\"lambda\",y=param,color=color[intrapod],ax=axes[count])\n\t\t\taxes[count].set_xlabel(\"Load\")\n\t\t\taxes[count].set_ylabel(param)\n\t\t\tcount += 1\n\n\tfor axe in axes:\n\t\taxe.legend(intrapod_design_strategy)\n\tplt.savefig(\"{}.png\".format(file_name))\n\t\n\t\t\t\t\t\t\t\ndef main():\n\tparam_name = \"_np{}_nspp{}_ksp{}\".format(parameters[\"np\"],parameters[\"nspp\"],parameters[\"kpaths\"])\n\t\n\tcheck_file_exist()\n\t\n\tfor file in os.listdir(packet_level_simulator_example_directory):\n\t\tif file.endswith(\"test_ecmp_then_ksp.properties\"):\n\t\t\tfor intrapod in intrapod_design_strategy:\n\t\t\t\tfor_loop(intrapod,param_name,file)\n\n\t\t\tplot(file)\n\t\t\tos.system(\"rm *.txt*\")\n\tprint(\"Program duration: \t--- %s seconds ---\" % (time.time() - start_time))\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"netbench_test.py","file_name":"netbench_test.py","file_ext":"py","file_size_in_byte":14703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451785645","text":"#!/usr/bin/env python3.6\nfrom sanic import Sanic\nfrom sanic.response import file\nfrom sanic_cors import CORS\n\napp = Sanic(__name__)\nCORS(app, automatic_options=True)\napp.config.from_pyfile('config.py')\ntry:\n app.config.from_pyfile('instance/config.py')\nexcept IOError as e: # pragma: no cover\n pass\n\n\n@app.route('/')\n@app.route('/index.html')\nasync def root(req): # pragma: no cover\n return await file('./index.html', headers={'Cache-Control': 'no-cache'})\n\n\n@app.route('/service-worker.js')\nasync def service_worker(req): # pragma: no cover\n return await file('./service-worker.js',\n headers={'Cache-Control': 'no-store'})\n\n\n@app.route('/static/css/main..css')\nasync def css(req, unique_hash): # pragma: no cover\n return await file(f'./static/css/main.{unique_hash}.css',\n headers={'Cache-Control': 'max-age=31556926'})\n\n\n@app.route('/static/css/main..css')\nasync def css_map(req, unique_hash, maps): # pragma: no cover\n return await file(f'./static/css/main.{unique_hash}.css{maps}',\n headers={'Cache-Control': 'max-age=31556926'})\n\n\n@app.route('/static/js/main..js')\nasync def js(req, unique_hash): # pragma: no cover\n return await file(f'./static/js/main.{unique_hash}.js',\n headers={'Cache-Control': 'max-age=31556926'})\n\n\n@app.route('/static/js/main..js')\nasync def js_map(req, unique_hash, maps): # pragma: no cover\n return await file(f'./static/js/main.{unique_hash}.js{maps}',\n headers={'Cache-Control': 'max-age=31556926'})\n\nfrom . import views # noqa\n","sub_path":"backend/sudokurace/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"489295218","text":"import math\n\ndef printarr(inputarr):\n for i in range(len(inputarr)):\n print(inputarr[i], end=' ')\n print()\n\ndef quicksort(wholearr, startdex, endex):\n # Determines appropriate midpoint between start and end\n # Receives leftmost of partition; smallest unsorted index\n index = medpartition(wholearr, startdex, endex)\n\n print(\"\\nIndex: \"+str(index))\n print(\"newstartdex: \"+str(startdex))\n\n\n if startdex < index-1:\n quicksort(wholearr, startdex, index-1)\n print(\"Left sorted\\n\")\n\n # Sort right half\n if endex > index:\n quicksort(wholearr, index, endex)\n print(\"Right sorted\\n\")\n\n\ndef medpartition(wholearr, leftdex, rightdex):\n # Pivot picked to be roughly median\n pivotindex = math.floor((leftdex + rightdex) / 2)\n pivot = wholearr[pivotindex]\n print(\"Pivot: \"+str(pivot)+\" Startdex: \"+str(leftdex)+\" Endex: \"+str(rightdex))\n\n\n # while inside partition\n while leftdex <= rightdex:\n # Iterate through arr until find element on left that should be to right of pivot\n # Record index\n while wholearr[leftdex] < pivot:\n leftdex += 1\n\n # Iterate through arr from right until find element that should be to left of pivot\n while wholearr[rightdex] > pivot:\n rightdex -= 1\n\n # Swap the discovered elements, move indices towards center\n if leftdex <= rightdex:\n # Print swap info\n printarr(wholearr)\n print(\"swap\")\n print(\"leftdex: \"+str(leftdex)+\" rightdex: \"+str(rightdex))\n\n temp = wholearr[leftdex]\n wholearr[leftdex] = wholearr[rightdex]\n wholearr[rightdex] = temp\n leftdex += 1\n rightdex -= 1\n # View swapped array\n printarr(wholearr)\n\n # Return leftdex - left bound. Lets right bound remain the end of the array.\n return leftdex\n\n\n\nif __name__ == '__main__':\n samplearr = [6,1,4,3,2,1,0]\n samplearr = [0,5,4,3,2,6,0]\n samplelen = len(samplearr)\n print(\"Sample: \")\n printarr(samplearr)\n print(\"___________\")\n\n quickarr = samplearr\n quicksort(samplearr, 0, samplelen-1)\n print(\"\\nQuicksorted:\")\n printarr(quickarr)\n","sub_path":"CodingProblems/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197287275","text":"import unittest\nimport numpy as np\nfrom env import MarsRover\nfrom pe_td_zero import td_zero_step, evaluate_policy_td_zero\n\nclass TestTD(unittest.TestCase):\n\n def test_td_step(self):\n sample = [2, 0, 0, 1]\n v = np.zeros(5)\n v_new = td_zero_step(v, sample)\n self.assertTrue(np.array_equal(v, v_new))\n\n sample = [1, 0, 1, 0]\n v = np.zeros(5)\n v_new = td_zero_step(v, sample)\n self.assertFalse(np.array_equal(v, v_new))\n self.assertTrue(v_new[1] == 0.1)\n\n sample = [1, 0, 1, 0]\n v = np.zeros(5)\n v_new = td_zero_step(v, sample, alpha=0.9)\n self.assertFalse(np.array_equal(v, v_new))\n self.assertTrue(v_new[1] == 0.9)\n\n def test_td_eval(self):\n pi = np.zeros(5)\n v, i = evaluate_policy_td_zero(pi, rewards=[1, -1, -1, -1, 10])\n self.assertTrue(i > 1)\n self.assertTrue(v[4]==0)\n self.assertTrue(v[3]==0)\n\n v, i = evaluate_policy_td_zero(pi, rewards=np.zeros(5))\n self.assertTrue(i == 1)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_td_zero.py","file_name":"test_td_zero.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361943711","text":"\"\"\"\nwith open('some_file', 'w') as opened_file:\n opened_file.write('Hola!')\n\n等价于\n\nfile = open('some_file', 'w')\ntry:\n file.write('Hola!')\nfinally:\n file.close()\n\"\"\"\n\nclass File(object):\n def __init__(self, file_name, method):\n self.file_obj = open(file_name, method)\n def __enter__(self):\n return self.file_obj\n # 发生异常时,会把异常的type、value、traceback传递过来\n \"\"\"\n 1、passes the type, value and traceback of the error to the __exit__ method.\n 2、allows the __exit__ method to handle the exception.\n 3、If __exit__ returns True then the exception was gracefully handled.\n 4、If anything other than True is returned by the __exit__ method then the exception is raised by the with statement.\n \"\"\"\n def __exit__(self, type, value, traceback):\n self.file_obj.close()\n\nwith File('demo.txt', 'w') as opened_file:\n opened_file.write('Hola!')\n\n\n# Implementing a Context Manager as a Generator\nfrom contextlib import contextmanager\n\n@contextmanager\ndef open_file(name):\n f = open(name, 'w')\n yield f\n f.close()\n\nwith open_file('some_file') as f:\n f.write('hola!')\n\n@contextmanager\ndef file_open(path):\n try:\n f_obj=open(path,'w')\n yield f_obj\n except OSError:\n print(\"We had an error!\")\n finally:\n print(\"Closing file\")\n f_obj.close()\n\nif __name__ == '__main__':\n with file_open(\"test.db\") as fobj:\n fobj.write(\"Testing context managers\")\n\n\nfrom contextlib import suppress\n# The idea behind this context manager utility is that it can suppress any number of exceptions.\nwith suppress(FileNotFoundError):\n with open(\"test.txt\") as fobj:\n for line in fobj:\n print(line)\n\n\n# redirect stdout/stderr to a file(test.txt)\nfrom contextlib import redirect_stdout\nfrom contextlib import redirect_stderr\nwith open(\"test.txt\",\"w\") as fobj:\n with redirect_stdout(fobj):\n help(redirect_stdout)\n\n\"\"\"\n# ExitStack is a context manager that will allow you to easily programmatically combine other context\n# managers and cleanup functions.\nfrom contextlib import ExitStack\nwith ExitStack as stack:\n file_objects=[stack.enter_context(open(file_open()) for filename in filenames)]\n\"\"\"","sub_path":"context_manager.py","file_name":"context_manager.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292624282","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import linear_model\n\nx = np.random.rand(100, 1) # 0~1 100개 난수 생성\nx = x * 4 - 2 # 범위 -2 ~ 2\n\ny = 3 * x**2 - 2 # y=3x^2-2\ny += np.random.randn(100, 1) # 표준 정규분포에서의 100개의 난수 더하기 (noise)\n\nmodel = linear_model.LinearRegression()\nmodel.fit(x**2, y)\nscore = model.score(x**2, y)\n\nprint(\"model coefficient: \", model.coef_) # 기울기\nprint(\"model intercept: \", model.intercept_) # 절편\nprint(\"R-squared: \", score) # 모델의 결정 계수\n\nplt.scatter(x, y, marker='+')\nplt.scatter(x, model.predict(x**2), marker='o')\nplt.show()","sub_path":"machine-learning-bootcamp/quadratic_linear_regression.py","file_name":"quadratic_linear_regression.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169809820","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom .form import orderForm, customerForm, createUserForm\nfrom .filter import orderFilter\n# contrib.auth library for auth\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.decorators import login_required\n\n\n\n\n\ndef loginPage(request):\n if request.user.is_authenticated:\n return redirect('dashboard_page')\n else:\n\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('dashboard_page')\n else:\n messages.info(request, '⚠ Wrong Credentials ! Please Check ')\n\n\n contex = {}\n return render(request, 'accounts/login.html', contex)\n\ndef logOut(request):\n logout(request)\n return redirect('login')\n\n\ndef registerPage(request):\n if request.user.is_authenticated:\n return redirect('dashboard_page') \n else:\n form = createUserForm()\n if request.method == 'POST':\n form = createUserForm(request.POST)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get('username')\n messages.success(request, user + ' 👋 Hi, your account was created. ')\n return redirect('login')\n \n context = {'register_form': form}\n return render(request, 'accounts/register.html', context)\n\n# @staff_member_required(login_url='login')\n@login_required(login_url='login')\ndef home(request):\n\n orders = Order.objects.all()\n total_orders = orders.count()\n customers = Customer.objects.all()\n\n # status_of_orders\n pending_order = orders.filter(dstatus='Pending').count()\n OFD_order = orders.filter(dstatus='Out for delivery').count()\n delivered_orders = orders.filter(dstatus='Delivered').count()\n\n hmcontext = {'orders': orders, 'customers': customers, 'total_orders': total_orders,\n 'pending': pending_order, 'OFD': OFD_order, 'Delivered': delivered_orders}\n\n return render(request, 'accounts/dashboard.html', hmcontext)\n\n@login_required(login_url='login')\ndef products(request):\n products = Product.objects.all()\n pdcontext = {'products': products}\n\n return render(request, 'accounts/products.html', pdcontext)\n\n@login_required(login_url='login')\ndef customer(request, pk):\n customer = Customer.objects.get(id=pk)\n orders = customer.order_set.all()\n total_orders = orders.count()\n orderfilter = orderFilter(request.GET, queryset=orders)\n orders = orderfilter.qs\n custcontex = {'orderFilter': orderFilter, 'customer': customer,\n 'orders': orders, 'total_orders': total_orders}\n return render(request, 'accounts/customer.html', custcontex)\n\n@staff_member_required(login_url='login')\ndef createCustomer(request):\n cid = Customer.objects.all()\n form = customerForm()\n if request.method == 'POST':\n form = customerForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n\n context = {'create_customer': form}\n return render(request, 'accounts/customer_form.html', context)\n\n@staff_member_required(login_url='login')\ndef createOrder(request):\n form = orderForm()\n if request.method == 'POST':\n form = orderForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n\n context = {'createorder_form': form}\n return render(request, 'accounts/order_form.html', context)\n\n@staff_member_required(login_url='login')\ndef updateOrder(request, pk):\n order = Order.objects.get(id=pk)\n form = orderForm(instance=order)\n if request.method == 'POST':\n form = orderForm(request.POST, instance=order)\n if form.is_valid():\n form.save()\n return redirect('/')\n\n context = {'update_order_form': form}\n return render(request, 'accounts/update_order.html', context)\n\n@staff_member_required(login_url='login')\ndef updateCustomer(request, pk):\n customer = Customer.objects.get(id=pk)\n form = customerForm(instance=customer)\n if request.method == 'POST':\n form = customerForm(request.POST, instance=customer)\n if form.is_valid():\n form.save()\n return redirect('/')\n\n context = {'update_customer_form': form, 'customer': customer}\n return render(request, 'accounts/update_customer.html', context)\n\n@staff_member_required(login_url='login')\ndef deleteOrder(request, pk):\n item = Order.objects.get(id=pk)\n if request.method == 'POST':\n item.delete()\n return redirect('/')\n\n context = {'item': item}\n return render(request, 'accounts/delete_order_confirmation.html', context)\n\n@staff_member_required(login_url='login')\ndef deleteCustomer(request, pk):\n customer = Customer.objects.get(id=pk)\n orders = customer.order_set.all()\n total_order = orders.count()\n if request.method == 'POST':\n customer.delete()\n return redirect('/')\n\n context = {'customer': customer, 'total_order': total_order}\n return render(request, 'accounts/delete_customer_confirmation.html', context)\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331653171","text":"import sqlite3\r\n\r\ndef update_data(data):\r\n with sqlite3.connect(\"test_db.db\") as db:\r\n cursor = db.cursor()\r\n sql = \"update File set Name=?, Size=? where FileID=?\"\r\n cursor.execute(sql,data)\r\n db.commit()\r\n\r\nif __name__ == \"__main__\":\r\n file = (\"Filename\", 2, 1)\r\n update_data(file)\r\n","sub_path":"Computing A2/COMP4/DB/functions/update_data.py","file_name":"update_data.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"571686927","text":"import matplotlib\n\nimport scipy.integrate\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport ipywidgets as widgets\n\nmatplotlib.use('TKAgg')\n\n\n\ndef ideal_gas_expansion(t, z, b, c):\n \"\"\"\n Differential equation for expansion of ideal gas with Newton's second law\n\n Parameters\n ----------\n t: time\n z: tuple of [dx/dt, x]\n b: value of (N k_B T)/m (right hand side of equation of state divided by barrier mass)\n c: friction coefficient gamma, divided by mass (gamma/m)\n\n Returns\n -------\n Tuple with value of dz/dt, i.e. (x'', x')\n \"\"\"\n return b/z[1] - c*z[0], z[0]\n\n\n@widgets.interact(m=widgets.FloatSlider(2, min=0.1, max=5),\n nkt=widgets.FloatSlider(1, min=0.1, max=5),\n gamma=widgets.FloatSlider(1, min=0.1, max=5),\n y0=widgets.FloatSlider(0.5, min=0.1, max=5))\ndef int_plot(m=1, nkt=1, gamma=1, y0=0.5):\n time_range = [0, 5]\n args = (nkt/m, gamma/m)\n t = np.linspace(*time_range, 300)\n sol = scipy.integrate.solve_ivp(ideal_gas_expansion, time_range, [0, y0], args=args, dense_output=True)\n z = sol.sol(t)\n plt.plot(t, z.T)\n plt.plot(t, args[0]/z.T[:,1], label=\"Pressure\")\n plt.xlabel(\"t [sec]\")\n plt.legend(['dx/dt', 'x', \"Pressure\"])\n plt.title(\"Expansion of ideal gas against friction\")\n return plt.figure()\n\n\nif __name__ == \"__main__\":\n int_plot()\n","sub_path":"diffeq.py","file_name":"diffeq.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140181763","text":"#! /usr/bin/env python3\n\nimport time\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\nfrom lib_metrics_spaces import hyp_dist, plot\n\n## Wikipedia page for Hyperbolic space\n\n# Euclid's parallel postulate is no longer assumed to hold. Instead, the parallel\n# postulate is replaced by the following alternative (in two dimensions):\n#\n# *Given any line L and point P not on L, there are at least two distinct lines\n# passing through P which do not intersect L.\n#\n# There are several important models of hyperbolic space: the Klein model, the\n# hyperboloid model, the Poincaré ball model and the Poincaré half space model.\n# These all model the same geometry in the sense that any two of them can be\n# related by a transformation that preserves all the geometrical properties of\n# the space, including isometry (though not with respect to the metric of a\n# Euclidean embedding).\n\n## Here I implement the Hyperboloid model, where the n-hyperbolic space is\n# embedded in R^{n+1} --> x_o^2 - x_1^2 - ... - x_n^2 = 1, x_o > 0\n\n# In this model a line (or geodesic) is the curve formed by the intersection\n# of H^n with a plane through the origin in R^{n+1}.\\\n\n################################################################################\nti = time.time()\n################################################################################\nnp.random.seed(0)\npath_plot = './plots/hyperbolic_spaces'\n\nH_scale = 1\nN = 5_00 # number of points to generate in H^n\nnn = np.arange(1,201)\nn_1_hyper = None # data for 2D and 3D plot\nn_2_hyper = None # data for 2D and 3D plot\n# pp = np.array([1/3, 1/2, 2/3, 1, 2, 3, 5, 10])\nD_mm = np.empty(nn.size)\n\n# origin = 'minima'\norigin = 'random'\n\nfor n in nn:\n\n Hn = H_scale*(np.random.random(size=(N, n+1)) - 0.5) # embedded in Euclidean space\n Hn[:, 0] = np.sqrt(1 + np.sum(Hn[:, 1:]**2, axis=1))\n\n ## data for 2D and 3D plot\n if n==1:\n n_1_hyper = Hn\n\n if n==2:\n n_2_hyper = Hn\n\n ## Query point\n y = H_scale*(np.random.random(size=n+1) - 0.5)\n y[0] = np.sqrt(1 + np.sum(y[1:]**2))\n\n d = hyp_dist(Hn, y=y, origin=origin)\n\n D_mm[n-1] = np.max(d) - np.min(d)\n\nplot(x=nn, y=D_mm, fname=f'contrast_hyperbolic_space', path=path_plot,\ntitle='Distance behavior in hyperbolic spaces',\nmetric='d(x,y)=arccosh($(Q(x+y)-2)/2 \\\\to Q(x) = x_0^2 - \\cdots -x_n^2$')\n\n# fig, ax = plt.subplots(figsize=(10,5))\n# ax.scatter(nn[2:], D_mm[2:])\n# plt.tight_layout()\n#\n# fig.savefig(f'{ploth_path}/hyperbic_distance.png')\n# fig.savefig(f'{ploth_path}/hyperbic_distance.pdf')\n#\n# plt.close()\n\n\n################################################################################\n## plot 1-hyperbolic space\nfig, ax = plt.subplots(figsize=(10,10))\nax.set_title('$H^1$', fontsize='xx-large')\nax.scatter(n_1_hyper[:, 1], n_1_hyper[:, 0])\n# plt.show()\nfig.savefig(f'{path_plot}/n_2_hyperbolic_space.png')\nfig.savefig(f'{path_plot}/n_2_hyperbolic_space.pdf')\nplt.close()\n################################################################################\n## 2-hyperbola\nfig, tmp = plt.subplots(figsize=(10,10))\nax = Axes3D(fig)\nax.set_title('$H^2$', fontsize='xx-large')\n\nax.scatter(n_2_hyper[:, 2], n_2_hyper[:, 1], n_2_hyper[:, 0])\n# plt.show()\nfig.savefig(f'{path_plot}/n_3_hyperbolic_space.png')\nfig.savefig(f'{path_plot}/n_3_hyperbolic_space.pdf')\nplt.close()\n\n################################################################################\ntf = time.time()\nprint(f'Running time: {tf-ti:.2f} seconds')\n","sub_path":"hyperboloids.py","file_name":"hyperboloids.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"616382256","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nCopyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c)\nContact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de\n'''\n\nfrom math import pi\n\nfrom VAMPzero.Handler.Parameter import parameter\n\n\nclass mFuelCR(parameter):\n '''\n The fuel used in the cruise segment\n\n :Unit: [kg]\n '''\n\n def __init__(self, value=0., unit='kg', parent='', cpacsPath=''):\n super(mFuelCR, self).__init__(value=value, unit=unit, doc=self.__doc__, status='init', parent=parent,\n cpacsPath=cpacsPath)\n\n def calc(self):\n '''\n If the design range :ref:`aircraft.desRange` is fixed calcFixRange is chosen, if not the calcFixFuel() method is selected.\n '''\n if self.parent.mFM.getStatus() == 'fix':\n return self.calcFixFuel()\n elif self.parent.aircraft.desRange.getStatus() == 'fix':\n return self.calcFixRange()\n else:\n return self.calcFixRange()\n\n def calcFixRange(self):\n '''\n Calculates the fuel mass for the cruise segment if the range is given.\n\n The calculation is based on a simple equilibrium of forces approach. This means that this\n is a constant altitude cruise phase. An iteration cycle with a leg length of 10km is applied to\n find the needed fuel mass.\n\n The initial aircraft mass is determined from the actual takeoff mass minus the fuel mass for climb and takoff\n\n :Source: adapted from DLR-LY-IL Performance Tool, J. Fuchte, 2011\n :Source: Getting to Grips with Aircraft Performance, N.N., Airbus, 2002, pp. 129\n '''\n # get Fuel Data\n mFuelCLIMB = self.parent.aircraft.fuel.mFuelCLIMB.getValue()\n mFuelTO = self.parent.aircraft.fuel.mFuelTO.getValue()\n mFM = self.parent.aircraft.fuel.mFM.getValue()\n\n # get Distance Data\n distCR = self.parent.aircraft.distCR.getValue()\n\n # get Engine Data\n sfcCR = self.parent.aircraft.engine.sfcCR.getValue()\n\n # get Mass Data\n oWE = self.parent.aircraft.oEM.getValue()\n mPayload = self.parent.aircraft.payload.mPayload.getValue()\n\n # get Atmosphere Data\n q = self.parent.aircraft.atmosphere.qCR.getValue()\n TAS = self.parent.aircraft.atmosphere.TASCR.getValue()\n\n # get Aero Data\n cDw = self.parent.aircraft.wing.cDw.getValue()\n cDMINoffset = self.parent.aircraft.wing.cDMINoffset.getValue()\n cD0 = self.parent.aircraft.cD0.getValue()\n oswald = self.parent.aircraft.oswald.getValue()\n\n # get Wing Data\n refArea = self.parent.aircraft.wing.refArea.getValue()\n aspectRatio = self.parent.aircraft.wing.aspectRatio.getValue()\n\n\n # Initialize\n massCurrent = oWE + mPayload + mFM - mFuelCLIMB - mFuelTO\n fuelResult = 0\n remainDist = distCR\n\n # Distance for iteration\n it = 10000\n\n # Fly Segments\n while remainDist >= 0. and q != 0. and oswald != 0. and refArea != 0. and aspectRatio != 0. and massCurrent > 0. and sfcCR > 0.:\n cLCurrent = massCurrent * 9.81 / (q * refArea)\n cDCurrent = cDw + cD0 + cLCurrent * cDMINoffset + cLCurrent ** 2 / (pi * aspectRatio * oswald)\n thrustReq = cDCurrent * q * refArea\n timeSeg = it / TAS\n fuelSeg = timeSeg / 3600. * thrustReq * sfcCR\n massCurrent = massCurrent - fuelSeg\n remainDist = remainDist - it\n fuelResult = fuelResult + fuelSeg\n\n return self.setValueCalc(fuelResult)\n\n def calcFixFuel(self):\n '''\n Calculates the fuel mass for a cruise segment if the\n fuel mission fuel mass is fixed.\n\n Since the mission fuel mass is fixed, the fuel mass for the cruise phase is\n limited by the fuel needed in all other segments of the mission.\n\n :Source: Daniel Boehnke\n '''\n # get Fuel Data\n mFuelCLIMB = self.parent.aircraft.fuel.mFuelCLIMB.getValue()\n mFuelTO = self.parent.aircraft.fuel.mFuelTO.getValue()\n mFuelRES = self.parent.aircraft.fuel.mFuelRES.getValue()\n mFuelDESCENT = self.parent.aircraft.fuel.mFuelDESCENT.getValue()\n mFM = self.parent.aircraft.fuel.mFM.getValue()\n\n fuelAvailable = mFM - mFuelTO - mFuelCLIMB - mFuelDESCENT - mFuelRES\n \n if fuelAvailable < 0.: \n self.log.warning('VAMPzero FUEL: The remaining fuel for the cruise segment is not sufficient for any cruise!')\n \n return self.setValueCalc(fuelAvailable)\n\n","sub_path":"src/VAMPzero/Component/Fuel/Mass/mFuelCR.py","file_name":"mFuelCR.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185758714","text":"import numpy as np\nimport pandas\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom logger.logger import LoggerHelper\n\n\nLOGGER = LoggerHelper.get_logger(name=\"core-distance\", filename=\"core-distance.log\")\n\n\ndef match_user_county(user_features, county_features):\n try:\n df = county_features.copy()\n county_features = county_features.values\n matching = cosine_similarity(user_features.reshape(1, -1), county_features)\n for user in matching:\n top_3_matching_ratio = np.sort(user)[::-1][:3]\n top_3_matching_county = df.index[user.argsort()[::-1][:3]]\n results = dict(zip(top_3_matching_county, top_3_matching_ratio))\n return results\n except Exception as ex:\n LOGGER.error(str(ex))\n return -1\n","sub_path":"back-processing/core/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312756225","text":"import string\n\nprv_words=[]\nend_word=None\n\nwhile True:\n end_word=input(\"please enter a new word , en (ok) to finish: \")\n if end_word!=\"ok\":\n prv_words.append(end_word)\n else:\n break\n\n\nfname=input(\"please entre the file's name : \")\ntry:\n fhand = open(fname)\nexcept:\n print('File cannot be opened:')\n exit()\n\nhan=[]\ncounts = dict()\nfor line in fhand:\n line = line.translate(line.maketrans('', '', string.punctuation))\n words = line.split()\n for word in words[5:]:\n han.append(word)\n\nfor word in han:\n if word in prv_words:\n continue\n else:\n if word not in counts:\n counts[word] = 1\n else:\n counts[word] += 1\n \n\nlst=list()\n\n\nfor key,val in counts.items():\n\tlst.append( (val , key) )\n\t\nlst.sort(reverse=True)\ndel lst[2]\nfor key , val in lst[:10]:\n\tprint( val , key )\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n","sub_path":"count2.py","file_name":"count2.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445068605","text":"import cv2 as cv\nimport numpy as np\n\nimg = cv.imread(\"Object Detection From Pretrained Image\\contents\\people2.jpg\")\n\nimg_width = img.shape[0]\nimg_height = img.shape[1]\n\nimg_blob = cv.dnn.blobFromImage(img, 1/255, (608,608), swapRB=True, crop=False)\n\nlabels = [\"person\",\"bicycle\",\"car\",\"motorcycle\",\"airplane\",\"bus\",\"train\",\"truck\",\"boat\",\n \"trafficlight\",\"firehydrant\",\"stopsign\",\"parkingmeter\",\"bench\",\"bird\",\"cat\",\n \"dog\",\"horse\",\"sheep\",\"cow\",\"elephant\",\"bear\",\"zebra\",\"giraffe\",\"backpack\",\n \"umbrella\",\"handbag\",\"tie\",\"suitcase\",\"frisbee\",\"skis\",\"snowboard\",\"sportsball\",\n \"kite\",\"baseballbat\",\"baseballglove\",\"skateboard\",\"surfboard\",\"tennisracket\",\n \"bottle\",\"wineglass\",\"cup\",\"fork\",\"knife\",\"spoon\",\"bowl\",\"banana\",\"apple\",\n \"sandwich\",\"orange\",\"broccoli\",\"carrot\",\"hotdog\",\"pizza\",\"donut\",\"cake\",\"chair\",\n \"sofa\",\"pottedplant\",\"bed\",\"diningtable\",\"toilet\",\"tvmonitor\",\"laptop\",\"mouse\",\n \"remote\",\"keyboard\",\"cellphone\",\"microwave\",\"oven\",\"toaster\",\"sink\",\"refrigerator\",\n \"book\",\"clock\",\"vase\",\"scissors\",\"teddybear\",\"hairdrier\",\"toothbrush\"]\n\ncolors = [\"0,255,255\", \"0,0,255\", \"0,255,0\", \"255,0,0\", \"0,0,0\", \"255,255,0\"]\ncolors = [np.array(color.split(\",\")).astype(\"int\") for color in colors]\ncolors = np.array(colors)\ncolors = np.tile(colors, (18, 1))\n\nmodel = cv.dnn.readNetFromDarknet(\"Pretrained Model\\yolov3.cfg\", \"Pretrained Model\\yolov3.weights\")\nlayers = model.getLayerNames()\noutput_layer = [layers[layer[0]-1] for layer in model.getUnconnectedOutLayers()]\n\nmodel.setInput(img_blob)\n\ndetection_layer = model.forward(output_layer)\n\nfor detection in detection_layer:\n for object_detection in detection:\n \n scores = object_detection[5:] \n predicted_id = np.argmax(scores)\n confidence = scores[predicted_id]\n\n if confidence > 0.99:\n\n label = labels[predicted_id]\n bounding_box = object_detection[0:4] * np.array([img_width, img_height, img_width, img_height])\n (box_center_x, box_center_y, box_width, box_height) = bounding_box.astype(\"int\")\n\n start_x = int(box_center_x - (box_width/2))\n start_y = int(box_center_y - (box_height/2))\n \n end_x = start_x + box_width\n end_y = start_y + box_height\n\n box_color = colors[predicted_id]\n box_color = [int(each) for each in box_color]\n\n label = \"{} :{:.2f}%\".format(label, confidence*100)\n\n cv.rectangle(img, (start_x, start_y), (end_x, end_y), box_color, 1)\n cv.putText(img, label, (start_x, start_y-10), cv.FONT_HERSHEY_PLAIN, 1, box_color, 1)\n\ncv.imshow(\"Detection Windows\", img)\n\ncv.waitKey(0)\n\n","sub_path":"Object Detection From Pretrained Image/yolo_pretrained_image.py","file_name":"yolo_pretrained_image.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76610265","text":"import cv2 as cv\nimport numpy as np\nimport dronekit as dk\nimport dronekit_sitl\nfrom pymavlink import mavutil\nimport time\nfrom time import gmtime, strftime\nimport os\n\ndef arm_and_takeoff(aTargetAltitude):\n print(\"Basic pre-arm checks\")\n while not vehicle.is_armable:\n print(\" Waiting for vehicle to initialise...\")\n time.sleep(1)\n\n print(\"Arming motors\")\n vehicle.mode = dk.VehicleMode(\"GUIDED\")\n vehicle.armed = True\n while not vehicle.armed:\n print(\" Waiting for arming...\")\n time.sleep(1)\n\n print(\"Taking off!\")\n vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude\n while True:\n print(\" Altitude: \", vehicle.location.global_relative_frame.alt)\n if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:\n print(\"Reached target altitude\")\n break\n time.sleep(1)\n\ndef send_ned_velocity(velocity_x, velocity_y, velocity_z):\n msg = vehicle.message_factory.set_position_target_local_ned_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_BODY_NED, # frame\n 0b0000111111000111, # type_mask (only speeds enabled)\n 0, 0, 0, # x, y, z positions (not used)\n velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)\n vehicle.send_mavlink(msg)\n vehicle.flush()\n\n\ndef goto_position_target_local_ned(north, east, down):\n msg = vehicle.message_factory.set_position_target_local_ned_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_BODY_NED, # frame\n 0b0000111111111000, # type_mask (only positions enabled)\n north, east, down, # x, y, z positions (or North, East, Down in the MAV_FRAME_BODY_NED frame\n 0, 0, 0, # x, y, z velocity in m/s (not used)\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)\n # send command to vehicle\n vehicle.send_mavlink(msg)\n vehicle.flush()\n\ndef draw_flow(img, flow, step=16):\n h, w = img.shape[:2]\n y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)\n\n fx, fy = flow[y, x].T\n\n lines = np.vstack([x, y, x + fx, y + fy]).T.reshape(-1, 2, 2)\n lines = np.int32(lines + 0.5)\n vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\n for (x1, y1), (x2, y2) in lines:\n # if ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 > 15:\n if ((x2 - x1) > 20 or (x2 - x1) < -20) and ((y2 - y1) > 20 or (y2 - y1) < -20):\n cv.circle(vis, (x1, y1), 15, (0, 0, 255), -1)\n cv.circle(vis, (x2, y2), 15, (0, 0, 255), -1)\n\n # cv.polylines(vis, lines, 0, (0, 255, 0))\n\n return vis\n#END of definitions\n\nconnection_string = '/dev/ttyACM0'\t#Establishing Connection With Flight Controller\nvehicle = dk.connect(connection_string, wait_ready=True, baud=115200)\n\n#RECORDING VIDEO SETUP\ndir_original = 'ORIGINAL'\ndir_opt_flow = 'OPT_FLOW'\ntime_stamp = strftime(\"%Y-%m-%d_%H:%M:%S\", time.localtime(time.time()))\nfourcc = cv.VideoWriter_fourcc(*'XVID')\n#set file to write original camera input\nout_original = cv.VideoWriter(os.path.join(dir_original,'original_'+time_stamp+'.avi'),fourcc, 8.0, (640,480)) \n#set file to write processed frames with optical flow\nout_opt_flow = cv.VideoWriter(os.path.join(dir_opt_flow, 'opt_flow'+time_stamp+'.avi'),fourcc, 8.0, (640,480)) \n\n#Downloading Destination Coordinates from Flight Controller\ncmds = vehicle.commands\ncmds.download()\ncmds.wait_ready()\nwaypoint2 = dk.LocationGlobalRelative(cmds[0].x, cmds[0].y, 3) # Destination point 1\n#waypoint2 = dk.LocationGlobalRelative(cmds[1].x, cmds[1].y, 3) # Destination point 2\n\n# START Flying\narm_and_takeoff(3)\nvehicle.airspeed = 0.5 # set drone speed to be used with simple_goto\n#vehicle.simple_goto(waypoint1)#trying to reach 1st waypoint\n#time.sleep(20)\n\ncam = cv.VideoCapture(0) # Get Initial Image from camera\nret, prev = cam.read()\nh, w = prev.shape[:2]\nprevgray = cv.cvtColor(prev, cv.COLOR_BGR2GRAY)\n\nwhile True:\t# Image processing/avoidance loop\n ret, img = cam.read()\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n flow = cv.calcOpticalFlowFarneback(prevgray, gray, None, 0.6, 5, 15, 3, 5, 1.2, 0)\n prevgray = gray\n new_frame = draw_flow(gray, flow)\n frame_HSV = cv.cvtColor(new_frame, cv.COLOR_BGR2HSV) # convert to HSV\n frame_threshold = cv.inRange(frame_HSV, (0, 58, 140), (57, 255, 255))\n ret, thresh = cv.threshold(frame_threshold, 50, 255, cv.THRESH_BINARY)\n contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n #print ( len(contours) )\n areas = []\n centers = []\n for contour in contours:\n areas.append( cv.contourArea(contour) )\n\n x, y, w, h = cv.boundingRect(contour) \n centers.append( x + (w/2))\n cv.rectangle(new_frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n\n if ( len(contours) ) >= 5 and max(areas) > 5000:\n print(\"turn right\")\n send_ned_velocity(0, 0, 0) # stop the vehicle for 2 seconds \n time.sleep(2)\n goto_position_target_local_ned(0, 2, 0) # move right for 2 metersq\n time.sleep(4)\n elif ( len(contours) ) >= 5 and max(areas) > 5000:\n print(\"turn left\")\n send_ned_velocity(0, 0, 0) # stop the vehicle for 2 seconds\n time.sleep(2)\n goto_position_target_local_ned(0, -2, 0) # move left for 2 meters\n time.sleep(4)\n print(\"go to destination 2 sec\") \n vehicle.simple_goto(waypoint2)\n time.sleep(2)\n\n out_original.write(img)\t#write original(unprocessed) image to the file\n out_opt_flow.write(new_frame)\t#write image processed by Optical Flow to the file\n #cv.imshow(\"OpticalFlow\", new_frame) \n #cv.imshow(\"Original\", frame_gray)\n \n key = cv.waitKey(30)\n if key == ord('q'):\n out_opt_flow.release()\n out_original.release()\n break\t#END of Image Processing Loop (keyboard interrupt)\n lat = vehicle.location.global_relative_frame.lat # get the current latitude\n lon = vehicle.location.global_relative_frame.lon # get the current longitude\n if lat == cmds[0].x and lon == cmds[0].y: \n print(\"Arrived\")\n out_opt_flow.release()\n out_original.release()\n break\t#END of Image Procwssing Loop (Arrival at Destination Point)\n\nprint(\"Landing\")\nvehicle.mode = dk.VehicleMode(\"LAND\")\nvehicle.flush()\n","sub_path":"10_19_Area.py","file_name":"10_19_Area.py","file_ext":"py","file_size_in_byte":6661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647847732","text":"import os\nimport json\nimport argparse\n\nfrom src import const\nfrom src import utils\n\n\ndef get_simulation_output_path(path_project, config_filename):\n\n # read simulation configuration\n config = utils.read_json_config(os.path.join(path_project, config_filename))\n\n path_simulation_output = os.path.join(\n path_project, config[const.CONFIG_PATH_RELATIVE_OUTPUT]\n )\n\n return path_simulation_output\n\n\ndef highlight_tree_differences_to_png(path_matlab, path_simulation_newick, path_reconstructed_newick, path_sisters_csv, path_diff_metrics):\n\n matlab_code = \"addpath('{0}', '{1}'); highlight_differences2('{2}', '{3}', '{4}', '{5}'); exit;\".format(\n const.PATH_ESTGT_BIN, const.PATH_RECONSTRUCT_LIB,\n path_simulation_newick, path_reconstructed_newick, path_sisters_csv, path_diff_metrics\n )\n\n utils.run_matlab_code(path_matlab, matlab_code)\n\n\ndef run(path_matlab, path_project, config_json):\n \"run function\"\n\n # get path to simulation output\n path_simulation_output = get_simulation_output_path(\n path_project, config_json\n )\n\n # highlight tree differences and save to png\n highlight_tree_differences_to_png(\n envs[const.ENV_MATLAB_KEY],\n os.path.join(path_simulation_output, const.FILE_SIMULATION_NEWICK),\n os.path.join(path_simulation_output, const.FILE_RECONSTRUCTED_NEWICK),\n os.path.join(path_simulation_output, const.FILE_SISTERS_COUNT),\n os.path.join(path_simulation_output, const.FILE_DIFF_METRICS)\n )\n\n\ndef parse_arguments():\n\n parser = argparse.ArgumentParser(description='redraw trees only')\n\n parser.add_argument(\n \"--env\",\n action=\"store\",\n dest=\"path_env\",\n required=True\n )\n\n parser.add_argument(\n \"--project\",\n action=\"store\",\n dest=\"path_project\",\n required=True\n )\n\n parser.add_argument(\n \"--config\",\n nargs='+',\n dest=\"configs\",\n required=True\n )\n\n # parse arguments\n params = parser.parse_args()\n\n # read environment configuration\n envs = utils.read_json_config(params.path_env)\n\n # get config json files\n config_jsons = utils.handle_config_args(\n params.path_project, params.configs\n )\n\n return params, envs, config_jsons\n\n\nif __name__ == \"__main__\":\n\n params, envs, config_jsons = parse_arguments()\n\n for config_json in config_jsons:\n\n if not config_json:\n continue\n\n if not os.path.exists(os.path.join(params.path_project, config_json)):\n raise Exception(\"Unable to find {}\".format(config_json))\n\n print()\n print(\"{} #############################################\".format(config_json))\n print()\n\n run(envs[const.ENV_MATLAB_KEY], params.path_project, config_json)\n","sub_path":"redraw_trees_only.py","file_name":"redraw_trees_only.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"540699858","text":"from browser import html, document as docu\nimport datetime\nimport locale\n\n#from utils import lamtronso, Tien\n\nlocale.setlocale(locale.LC_ALL, 'vi_VI')\n\n\ndef lamtronso(sothapphan=0, phanle=2):\n from decimal import Decimal\n # try:\n somoi = float(round(Decimal(sothapphan), phanle))\n # except:\n # somoi = None\n return somoi\n\n\nclass Qtgt:\n def __init__(self, maqt):\n self.maqt = maqt\n self.load_qtgt()\n\n def load_qtgt(self):\n self.__tttt()\n self.__hoso()\n self.__dot()\n self.__qtgt()\n self.__qtxd_oc()\n self.__qtvt_oc()\n self.__qtvl_oc()\n self.__qttl_oc()\n self.__khachhang()\n self.__donvithicong()\n self.__cpql()\n\n def __tttt(self):\n dl = {\"maqt\": \"pkh002\", \"madot\": \"2020gmmp242\", \"mahoso\": \"113344\",\n \"makhachhang\": \"2020kh001\", \"madvtc\": \"qlmltd\"}\n self.tttt = dl\n\n def __hoso(self):\n dl = {\n 'sohoso': 'GM01001/20',\n 'diachigandhn': '25/5/4A- Đường 9- Kp.5- P.Linh Xuân- Q.TĐ', }\n self.sohoso = dl['sohoso']\n self.diachigandhn = dl['diachigandhn']\n\n def __dot(self):\n dl = {'sodot': '999/2020MP', }\n self.sodot = dl['sodot']\n\n def __qtgt(self):\n # load tttt\n dl = {'ngaylap': '20200907', 'macpql': '20200721', 'mabaogia': '20200721',\n 'ocZvl': 0, 'ocZnc': 0, 'ocZmtc': 0, 'ocZtl': 0,\n 'onZvl': 0, 'onZnc': 0, 'onZmtc': 0, 'onZtl': 0,\n 'cpCty': 0, 'cpKhach': 0}\n self.ngaylap = dl['ngaylap']\n self.ocZvl = dl['ocZvl']\n self.ocZnc = dl['ocZnc']\n self.ocZmtc = dl['ocZmtc']\n self.ocZtl = dl['ocZtl']\n self.onZvl = dl['onZvl']\n self.onZnc = dl['onZnc']\n self.onZmtc = dl['onZmtc']\n self.onZtl = dl['onZtl']\n self.cpCty = dl['cpCty']\n self.cpKhach = dl['cpKhach']\n self.mabaogia = dl['mabaogia']\n\n def __qtxd_oc(self):\n dl = [\n {'chiphiid': '001', 'mota': '- Cắt mặt nhựa và BTXM', 'dvt': 'mét',\n 'sl': 16, 'giavl': 6510, 'gianc': 13174, 'giamtc': 5815,\n 'tienvl': 104154, 'tiennc': 210776, 'tienmtc': 93040},\n {'chiphiid': '002', 'mota': '- Đào bốc mặt đường nhựa', 'dvt': 'm3',\n 'sl': 0.24, 'giavl': 0, 'gianc': 538918, 'giamtc': 0,\n 'tienvl': 0, 'tiennc': 129340, 'tienmtc': 0}\n ]\n # load gia\n # tinh tien\n for cp in dl:\n cp['tienvl'] = lamtronso(cp['sl'] * cp['giavl'], 0)\n cp['tiennc'] = lamtronso(cp['sl'] * cp['gianc'], 0)\n cp['tienmtc'] = lamtronso(cp['sl'] * cp['giamtc'], 0)\n self.ocCpxd = dl.copy()\n\n def __qtvt_oc(self):\n dl = [\n {'chiphiid': '001', 'mota': 'Đai lấy nước PP 100 x 20F', 'dvt': 'bộ',\n 'sl': 1, 'giavl': 133900, 'gianc': 47904, 'giamtc': 0,\n 'tienvl': 133900, 'tiennc': 47904, 'tienmtc': 0},\n {'chiphiid': '002', 'mota': 'Ống HDPE 25x3mm', 'dvt': 'mét',\n 'sl': 12, 'giavl': 13895, 'gianc': 17174, 'giamtc': 774,\n 'tienvl': 166740, 'tiennc': 206088, 'tienmtc': 9288},\n ]\n # load gia\n # tinh tien\n for cp in dl:\n cp['tienvl'] = lamtronso(cp['sl'] * cp['giavl'], 0)\n cp['tiennc'] = lamtronso(cp['sl'] * cp['gianc'], 0)\n cp['tienmtc'] = lamtronso(cp['sl'] * cp['giamtc'], 0)\n self.ocCpvt = dl.copy()\n\n def __qtvl_oc(self):\n dl = [\n {'chiphiid': '001', 'mota': 'Đai lấy nước PP 100 x 20F', 'dvt': 'bộ',\n 'sl': 1, 'giavl': 133900, 'gianc': 47904, 'giamtc': 0,\n 'tienvl': 133900, 'tiennc': 47904, 'tienmtc': 0},\n {'chiphiid': '002', 'mota': 'Ống HDPE 25x3mm', 'dvt': 'mét',\n 'sl': 12, 'giavl': 13895, 'gianc': 17174, 'giamtc': 774,\n 'tienvl': 166740, 'tiennc': 206088, 'tienmtc': 9288},\n ]\n # load gia\n # tinh tien\n for cp in dl:\n cp['tienvl'] = lamtronso(cp['sl'] * cp['giavl'], 0)\n cp['tiennc'] = lamtronso(cp['sl'] * cp['gianc'], 0)\n cp['tienmtc'] = lamtronso(cp['sl'] * cp['giamtc'], 0)\n self.ocCpvl = dl.copy()\n\n def __qttl_oc(self):\n dl = [{'chiphiid': '001', 'mota': 'Gạch hình sin', 'dvt': 'm2',\n 'sl': 0.35, 'gia': 412000},\n {'chiphiid': '002', 'mota': '- Đào bốc mặt đường nhựa', 'dvt': 'm2',\n 'sl': 2.4, 'gia': 890000}, ]\n # load gia\n # tinh tien\n for cp in dl:\n cp['ocsl'] = cp['sl']\n cp['tien'] = lamtronso(cp['ocsl'] * cp['gia'], 0)\n self.ocCptl = dl.copy()\n\n def __khachhang(self):\n dl = {'khachhang': 'Nguyễn Lan Chi', }\n self.khachhang = dl['khachhang']\n\n def __donvithicong(self):\n dl = {'dvtc': 'QLMLTD', }\n self.dvtc = dl['dvtc']\n\n def __cpql(self):\n dl = {\"hesoid\": 20200721, \"vl\": 1, \"nc\": 1, \"mtc\": 1, \"chung\": 0.055, \"tructiepkhac\": 0, \"giantiepkhac\": 0.02, \"thutinhtruoc\": 0.055,\n \"khaosat\": 0.0207, \"thietke\": 1.2, \"giamsat\": 0.02566}\n self.hsVl = dl['vl']\n self.hsNc = dl['nc']\n self.hsMtc = dl['mtc']\n self.hsChung = dl['chung']\n self.hsTructiepkhac = dl['tructiepkhac']\n self.hsGiantiepkhac = dl['giantiepkhac']\n self.hsThutinhtruoc = dl['thutinhtruoc']\n self.hsKhaosat = dl['khaosat']\n self.hsThietke = dl['thietke']\n self.hsGiamsat = dl['giamsat']\n # ong cai\n self.ocVl = lamtronso(self.ocZvl * self.hsVl, 0)\n self.ocNc = lamtronso(self.ocZnc * self.hsNc, 0)\n self.ocMtc = lamtronso(self.ocZmtc * self.hsMtc, 0)\n self.ocZvlncmtc = self.ocVl + self.ocNc + self.ocMtc\n self.ocTructiepkhac = lamtronso(\n self.ocZvlncmtc * self.hsTructiepkhac, 0)\n self.ocTructiep = self.ocZvlncmtc + self.ocTructiepkhac\n self.ocChung = lamtronso(self.ocTructiep * self.hsChung, 0)\n self.ocGiantiepkhac = lamtronso(\n self.ocTructiep * self.hsGiantiepkhac, 0)\n self.ocGiantiep = self.ocChung + self.ocGiantiepkhac\n self.ocGiaxaydung = self.ocTructiep + self.ocGiantiep\n self.ocThutinhtruoc = lamtronso(\n self.ocGiaxaydung * self.hsThutinhtruoc, 0)\n self.ocXaydungtruocthue = self.ocGiaxaydung + self.ocThutinhtruoc\n self.ocKhaosatthietke = lamtronso(\n self.ocXaydungtruocthue * self.hsKhaosat * self.hsThietke, 0)\n self.ocGiamsat = lamtronso(self.ocXaydungtruocthue * self.hsGiamsat, 0)\n self.ocTuvan = self.ocKhaosatthietke + self.ocGiamsat\n self.ocTongxaydungtruocthue = self.ocXaydungtruocthue + self.ocTuvan\n self.ocThuetongxaydung = lamtronso(\n self.ocTongxaydungtruocthue * 10/100, 0)\n self.ocTongxaydung = self.ocTongxaydungtruocthue + self.ocThuetongxaydung\n self.ocCongtrinh = self.ocTongxaydung + self.ocZtl\n # ong nganh\n self.onVl = lamtronso(self.onZvl * self.hsVl, 0)\n self.onNc = lamtronso(self.onZnc * self.hsNc, 0)\n self.onMtc = lamtronso(self.onZmtc * self.hsMtc, 0)\n self.onZvlncmtc = self.onVl + self.onNc + self.onMtc\n self.onTructiepkhac = lamtronso(\n self.onZvlncmtc * self.hsTructiepkhac, 0)\n self.onTructiep = self.onZvlncmtc + self.onTructiepkhac\n self.onChung = lamtronso(self.onTructiep * self.hsChung, 0)\n self.onGiantiepkhac = lamtronso(\n self.onTructiep * self.hsGiantiepkhac, 0)\n self.onGiantiep = self.onChung + self.onGiantiepkhac\n self.onGiaxaydung = self.onTructiep + self.onGiantiep\n self.onThutinhtruoc = lamtronso(\n self.onGiaxaydung * self.hsThutinhtruoc, 0)\n self.onXaydungtruocthue = self.onGiaxaydung + self.onThutinhtruoc\n self.onKhaosatthietke = lamtronso(\n self.onXaydungtruocthue * self.hsKhaosat * self.hsThietke, 0)\n self.onGiamsat = lamtronso(self.onXaydungtruocthue * self.hsGiamsat, 0)\n self.onTuvan = self.onKhaosatthietke + self.onGiamsat\n self.onTongxaydungtruocthue = self.onXaydungtruocthue + self.onTuvan\n self.onThuetongxaydung = lamtronso(\n self.onTongxaydungtruocthue*10/100, 0)\n self.onTongxaydung = self.onTongxaydungtruocthue + self.onThuetongxaydung\n self.onCongtrinh = self.onTongxaydung + self.onZtl\n # tong\n self.xaydung = self.ocTongxaydung + self.onTongxaydung\n self.tailap = self.ocZtl + self.onZtl\n self.congtrinh = self.xaydung + self.tailap\n self.congtrinhtruocthue = lamtronso(self.congtrinh*100/110, 0)\n self.thuecongtrinh = self.congtrinh - self.congtrinhtruocthue\n if (self.ocTongxaydung*self.onTongxaydung) > 0:\n self.maubaocao = 'o2'\n elif self.ocTongxaydung > 0:\n self.maubaocao = 'oc'\n else:\n self.maubaocao = 'on'\n\n\ndef khungA4():\n zone = html.DIV(\n Class=\"A4doc\",\n )\n return zone\n\n\ndef quochuy(tendvtc='ĐỘI QLML CẤP NƯỚC QUẬN THỦ ĐỨC', ngaylap='20200813'):\n '''\n
    \n
    \n
    CÔNG TY CỔ PHẦN CẤP NƯỚC THỦ ĐỨC
    \n
    {{dvtc}}
    \n
    ---------oOo---------
    \n
    Số tài khoản: 102010000183907
    \n
    Tại: Nh Công Thương Việt Nam - Cn Đông Sài Gòn
    \n
    \n
    \n
    \n
    CỘNG HOÀ XÃ HỘI CHỦ NGHĨA VIỆT NAM
    \n
    Độc lập - Tự do - Hạnh phúc
    \n
    ---------oOo---------
    \n
    {{ngaylap}}
    \n
    \n
    \n '''\n zone = html.DIV(\n Class=\"grid quochuy\"\n )\n lbox = html.DIV()\n lbox <= html.DIV(\n \"CÔNG TY CỔ PHẦN CẤP NƯỚC THỦ ĐỨC\",\n Class=\"c u fb\",\n style={\"wordSpacing\": '3pt'})\n lbox <= html.DIV(\n f\"{tendvtc}\",\n Class=\"c u fb\",\n style={\"wordSpacing\": '3pt'})\n lbox <= html.DIV(\n \"---------oOo---------\",\n Class=\"c f-2\")\n lbox <= html.DIV(\n \"Số tài khoản: 102010000183907\",\n Class=\"c\")\n lbox <= html.DIV(\n \"Tại: Nh Công Thương Việt Nam - Cn Đông Sài Gòn\",\n Class=\"c\")\n mbox = html.DIV()\n rbox = html.DIV()\n rbox <= html.DIV(\n \"CỘNG HOÀ XÃ HỘI CHỦ NGHĨA VIỆT NAM\",\n Class=\"c u fb\")\n rbox <= html.DIV(\n \"Độc lập - Tự do - Hạnh phúc\",\n Class=\"c fb\")\n rbox <= html.DIV(\n \"---------oOo---------\",\n Class=\"c f-2\")\n sthoi = f\"{ngaylap}\"\n actbox = html.DIV(\n f\"Thủ Đức, ngày {sthoi[-2:]} tháng {sthoi[-4:-2]} năm {sthoi[:-4]}\",\n Class=\"c ngaylap\",\n contenteditable=\"true\")\n\n def suangaylap(ev):\n noidung = ev.innerHTML\n for el in docu.select(\".ngaylap\"):\n el.attrs.innerHTML = noidung\n actbox.bind(\"blur\", suangaylap)\n rbox <= actbox\n zone <= lbox + mbox + rbox\n return zone\n\n\ndef tieudeqtgt(maqt='pkh001', tieude='BẢNG QUYẾT TOÁN GẮN MỚI ĐỒNG HỒ NƯỚC', sohoso='GM08123/20', sodot='202/20MP',\n khachhang='Phạm Thị Lan', diachigandhn='T15 Nguyễn Văn Hưởng- P.Thảo Điền- Q.2'):\n '''\n
    \n
    \n {{tieude}}\n
    \n
    Khách hàng:
    \n
    {{khachhang}}
    \n
    Sô hồ sơ:
    \n
    {{sohoso}}
    \n
    Địa chỉ:
    \n
    {{diachigandhn}}
    \n
    Sô đợt:
    \n
    {{sodot}}
    \n
    \n '''\n zone = html.DIV(\n Class=f\"grid tieudeqtgt\"\n )\n actbox = html.DIV(\n f\"{tieude}\",\n Class=f\"c u fb f5 b0 tieude_{maqt}\",\n style={\"gridArea\": \"1/1/2/5\"},\n contenteditable=\"true\")\n\n def suatieude(ev):\n noidung = ev.innerHTML\n for el in docu.select(f\".tieude_{maqt}\"):\n el.attrs.innerHTML = noidung\n actbox.bind(\"blur\", suatieude)\n zone <= actbox\n zone <= html.DIV(\n f\"Khách hàng: \",\n Class=\"l\")\n zone <= html.DIV(\n f\"{khachhang}\",\n Class=\"l u fb f2\")\n zone <= html.DIV(\n f\"Sô hồ sơ: \",\n Class=\"l\")\n zone <= html.DIV(\n f\"{sohoso}\",\n Class=\"l u fb f2\")\n zone <= html.DIV(\n f\"Địa chỉ: \",\n Class=\"l\")\n zone <= html.DIV(\n f\"{diachigandhn}\",\n Class=\"l fb f2\")\n zone <= html.DIV(\n f\"Sô đợt: \",\n Class=\"l\")\n zone <= html.DIV(\n f\"{sodot}\",\n Class=\"l u fb f2\")\n return zone\n\n\ndef creat_rptQtgt(maqt='pkh001'):\n maqt = f\"qtgt:{maqt}\"\n if maqt in docu:\n zone = docu[maqt]\n else:\n zone = html.DIV(id=maqt)\n docu['body'] <= zone\n trang1 = khungA4()\n\n zone <= trang1\n\n\n# main\ndsinqt = ['pkh001', 'pkh002']\nfor maqt in dsinqt:\n creat_rptQtgt(maqt)\n","sub_path":"services/webapp/static/py/reports/qtgt copy.py","file_name":"qtgt copy.py","file_ext":"py","file_size_in_byte":13549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"622580030","text":"\n\nfrom xai.brain.wordbase.nouns._pastel import _PASTEL\n\n#calss header\nclass _PASTELS(_PASTEL, ):\n\tdef __init__(self,): \n\t\t_PASTEL.__init__(self)\n\t\tself.name = \"PASTELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"pastel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_pastels.py","file_name":"_pastels.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394647447","text":"\"\"\"\nFunctions to calculate alerts\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta, datetime\n\nfrom meerkat_abacus.model import Data\nfrom meerkat_abacus.util.epi_week import epi_year_start_date\n\n\ndef threshold(var_id, limits, session, hospital_limits=None):\n \"\"\"\n Calculate threshold alerts based on daily and weekly limits\n\n Returns alerts for all days where there are more than limits[0] cases\n of var_id in one clinic or where ther are more than limits[1] cases of\n var_id in one clinic for one week.\n\n Args:\n var_id: variable id for alert\n limits: (daily, weekly) limits\n session: Db session\n\n Returns:\n alerts: list of alerts.\n \"\"\"\n\n conditions = [Data.variables.has_key(var_id)]\n data = pd.read_sql(\n session.query(Data.region, Data.district, Data.clinic, Data.date, Data.clinic_type,\n Data.uuid, Data.variables[var_id].label(var_id)).filter(\n *conditions).statement, session.bind)\n if len(data) == 0:\n return None\n # Group by clinic and day\n \n daily = data.groupby([\"clinic\", pd.TimeGrouper(\n key=\"date\", freq=\"1D\")]).sum()[var_id]\n\n daily_over_threshold = daily[daily >= limits[0]]\n alerts = []\n for clinic_date in daily_over_threshold.index:\n clinic, date = clinic_date\n data_row = data[(data[\"clinic\"] == clinic) & (data[\"date\"] == date)]\n if len(data_row) == 0:\n continue\n clinic_type = data_row[\"clinic_type\"].iloc[0]\n uuids = list(data_row[\"uuid\"])\n\n add = False\n if hospital_limits and clinic_type == \"Hospital\":\n if len(uuids) >= hospital_limits[0]:\n add = True\n else:\n if len(uuids) >= limits[0]:\n add = True\n if add:\n alerts.append({\n \"clinic\": clinic,\n \"reason\": var_id,\n \"duration\": 1,\n \"uuids\": uuids,\n \"type\": \"threshold\"\n })\n\n today = datetime.now()\n epi_year_weekday = epi_year_start_date(today).weekday()\n freq = [\"W-MON\", \"W-TUE\", \"W-WED\", \"W-THU\", \"W-FRI\", \"W-SAT\",\n \"W-SUN\"][epi_year_weekday]\n # Group by clinic and epi week\n weekly = data.groupby([\"clinic\", pd.TimeGrouper(\n key=\"date\", freq=freq, label=\"left\")]).sum()[var_id]\n weekly_over_threshold = weekly[weekly >= limits[1]]\n\n for clinic_date in weekly_over_threshold.index:\n clinic, date = clinic_date\n cases = data[(data[\"clinic\"] == clinic) & (data[\"date\"] >= date) & (\n data[\"date\"] < date + timedelta(days=7))]\n if len(cases) == 0:\n continue\n clinic_type = cases[\"clinic_type\"].iloc[0]\n uuids = list(cases.sort_values([\"date\", \"uuid\"])[\"uuid\"])\n\n add = False\n if hospital_limits and clinic_type == \"Hospital\":\n if len(uuids) >= hospital_limits[1]:\n add = True\n else:\n if len(uuids) >= limits[1]:\n add = True\n if add:\n alerts.append({\n \"clinic\": clinic,\n \"reason\": var_id,\n \"duration\": 7,\n \"uuids\": uuids,\n \"type\": \"threshold\"\n })\n\n return alerts\n\n\ndef double_double(var_id, session):\n \"\"\"\n Calculate threshold alerts based on a double doubling of cases. \n\n We want to trigger an alert for a clinic if there has been a doubling of cases\n in two consecutive weeks. I.e if the case numbers look like: 2, 4, 8. We would\n not trigger an alert for 2, 4, 7 or 2, 3, 8. \n\n Args:\n var_id: variable id for alert\n limits: (daily, weekly) limits\n session: Db session\n\n Returns:\n alerts: list of alerts.\n \"\"\"\n conditions = [Data.variables.has_key(var_id)]\n data = pd.read_sql(\n session.query(Data.region, Data.district, Data.clinic, Data.date,\n Data.uuid, Data.variables[var_id].label(var_id)).filter(\n *conditions).statement, session.bind)\n\n if len(data) == 0:\n return None\n\n today = datetime.now()\n epi_year_weekday = epi_year_start_date(today).weekday()\n freq = [\"W-MON\", \"W-TUE\", \"W-WED\", \"W-THU\", \"W-FRI\", \"W-SAT\",\n \"W-SUN\"][epi_year_weekday]\n weekly = data.groupby([\"clinic\", pd.TimeGrouper(\n key=\"date\", freq=freq, label=\"left\", closed=\"left\")]).sum()[var_id]\n alerts = []\n for clinic in weekly.index.get_level_values(level=0).unique():\n clinic_ts = weekly[clinic].resample(freq).sum().fillna(0)\n compare_series = clinic_ts.shift(periods=1, freq=freq)[:-1]\n compare_series_2 = clinic_ts.shift(periods=2, freq=freq)[:-2]\n factor = clinic_ts / compare_series\n factor2 = compare_series / compare_series_2\n factor[1:][compare_series <= 1] = 0\n factor2[1:][compare_series_2 <= 1] = 0\n is_alert = (factor >= 2) & (factor2 >= 2)\n if np.sum(is_alert):\n start_dates = clinic_ts.index[is_alert]\n for start_date in start_dates:\n cases = data[(data[\"clinic\"] == clinic) & (data[\n \"date\"] >= start_date) & (data[\"date\"] < start_date +\n timedelta(days=7))]\n\n uuids = list(cases.sort_values([\"date\", \"uuid\"])[\"uuid\"])\n if len(uuids) > 0:\n alerts.append({\n \"clinic\": clinic,\n \"reason\": var_id,\n \"duration\": 7,\n \"uuids\": uuids,\n \"type\": \"threshold\"\n })\n return alerts\n","sub_path":"meerkat_abacus/alerts.py","file_name":"alerts.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"120262729","text":"\n__all__ = ['init']\n\nimport os, sys, configparser, re\nfrom os.path import exists, isdir, abspath, join, dirname, isabs\n\n\nclass Parser(configparser.ConfigParser):\n # I want to use Python's ConfigParser to read the file, but it lowercases keys by default.\n # This is not acceptable for the [env] section. I would like other sections to lowercase,\n # however, and there doesn't seem to be a good way to do that. I tried providing a Boolean\n # and toggling it but that doesn't work. For now I'm going to keep the case and lowercase\n # the keys myself.\n def __init__(self):\n configparser.ConfigParser.__init__(self, allow_no_value=True, comment_prefixes='#',\n interpolation=configparser.ExtendedInterpolation())\n def optionxform(self, option):\n return option\n\n\ndef init(filename='.config', searchfrom=None, env=None):\n \"\"\"\n filename\n The name of the configuration file.\n\n This can be a simple filename, in which case the file will be searched for. It can also\n be a fully qualified filename such as '/etc/project.conf'.\n\n If not provided, a file named \".config\" will be searched for.\n\n searchfrom\n Optional directory to start searching from. If not provided, the default is the current\n working directory. To search from the directory where the calling code is located, use::\n\n autoconfig.init(searchfrom=__file__)\n\n This parameter is ignored if `filename` is a path since no search is performed.\n\n env\n Additional section names to treat as environment variables. This can be a string for a\n single section or a list of names.\n\n Raises FileNotFoundError if the configuration file is not found.\n \"\"\"\n fqn = _locate_config(filename, searchfrom)\n\n p = Parser()\n p.read(fqn)\n\n _copy_env(fqn, p, env)\n _setup_logging(p)\n\n\n_STDOUT = sys.stdout\n_GREEN = '\\033[1m\\033[32m'\n_RESET = '\\033[1m\\033[0m'\n\nclass _StdoutWrapper(object):\n \"\"\"\n We replace sys.stdout with an instance of this to add color to print\n statements. You should only use print statements when developing /\n debugging. Do not leave them in!\n \"\"\"\n def __init__(self):\n sys.stdout = self\n\n def write(self, *args):\n # Note: Print statements in Python 3 seem to print the text and then a\n # new line. Don't bother to color the newline.\n _STDOUT.write(_GREEN)\n _STDOUT.write(' '.join(args))\n _STDOUT.write(_RESET)\n\n def flush(self):\n _STDOUT.flush()\n\n def __getattr__(self, name):\n return getattr(_STDOUT, name)\n\n\ndef _setup_logging(p):\n if 'logging' not in p.sections():\n return\n\n d = { key.lower(): p.get('logging', key) for key in p.options('logging') }\n # (See the note in Parser about case.)\n\n import logging, logging.handlers\n\n # Setup file and console handlers if requested. If colorlog exists, the console output\n # will be in color.\n\n handlers = []\n filename = d.get('filename')\n if filename:\n format = d.get('format', \"%(asctime)s %(levelname).1s %(name)s %(message)s\")\n h = logging.handlers.TimedRotatingFileHandler(filename, when='midnight', backupCount=6)\n h.setLevel(logging.DEBUG)\n h.setFormatter(logging.Formatter(format))\n handlers.append(h)\n\n console = d.get('console', 'false')\n if console.lower() in ('true', 'short', 'long'):\n format = '%(levelname).1s %(name)s %(message)s'\n if console == 'long':\n format = '%(asctime)s ' + format\n\n try:\n from colorlog import ColoredFormatter\n formatter = ColoredFormatter(\n '%(log_color)s' + format,\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'white',\n 'WARNING': 'yellow',\n 'ERROR': 'bg_red,white',\n 'CRITICAL': 'bg_red,white',\n },\n secondary_log_colors={},\n style='%')\n except:\n formatter = logging.Formatter(format)\n\n h = logging.StreamHandler(sys.stdout)\n h.setLevel(logging.DEBUG)\n h.setFormatter(formatter)\n handlers.append(h)\n\n root = logging.getLogger()\n root.setLevel(logging.INFO)\n\n if handlers:\n root.handlers = handlers\n\n re_sep = re.compile(r'[\\s,]+')\n names = set()\n names.update(name for name in re_sep.split(os.environ.get('DEBUG', '')) if name)\n names.update(name for name in re_sep.split(d.get('debug', '')) if name)\n\n for name in names:\n l = logging.getLogger(name)\n l.setLevel(logging.DEBUG)\n\n # Redirect stdout so we can color print statements too.\n sys.stdout = _StdoutWrapper()\n\n\n\ndef _copy_env(fqn, p, env):\n \"\"\"\n Copies the items from the [env] section, and any additional sections listed in 'env'\n to os.environ.\n\n If PYTHONPATH is provided, it is parsed and prefixed to the system path.\n\n fqn\n The fully qualified path of the configuration file.\n\n p\n The ConfigParser\n\n env\n Optional list of environment sections to add to the environment.\n \"\"\"\n envs = ['env']\n if env:\n assert isinstance(env, (str, list))\n if isinstance(env, str):\n envs.append(env)\n else:\n envs.extend(env)\n\n paths = []\n\n for name in envs:\n if name in p.sections():\n for key, value in p[name].items():\n if value is None or value == '':\n # A key with no value is used to \"unset\".\n if key in os.environ:\n del os.environ[key]\n else:\n # Do we need to check the encoding?\n os.environ[key] = value\n\n if key == 'PYTHONPATH':\n paths.extend(value.split(os.pathsep))\n\n # If we found any PYTHONPATH entries, add them to the system path. Make sure you keep the\n # original order. If they are not fully qualified, they are relative to the configuration\n # file\n\n if paths:\n rootdir = dirname(fqn)\n paths = [ (path if isabs(path) else join(rootdir, path)) for path in paths if path ]\n sys.path[:0] = paths\n\n\n\ndef _locate_config(filename, searchfrom):\n \"\"\"\n Locates the configuration file.\n\n We're going to allow filename to be a path to a different file so we can accept __file__.\n \"\"\"\n if os.sep in filename and searchfrom:\n raise ValueError('Cannot provide a path in `filename` and a `searchfrom` value.')\n\n if isabs(filename):\n if not exists(filename):\n raise FileNotFoundError('Did not find configuration file. filename=%r' % filename)\n return filename\n\n searchfrom = abspath(searchfrom or os.getcwd())\n path = searchfrom\n\n while 1:\n if isdir(path):\n fqn = join(path, filename)\n if exists(fqn) and not isdir(fqn):\n return fqn\n\n parent = dirname(path)\n if parent == path:\n raise FileNotFoundError('Did not find configuration file. filename=%r searchfrom=%s' % (filename, searchfrom))\n path = parent\n","sub_path":"autoconfig.py","file_name":"autoconfig.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586552896","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv\n\n\n\nx = [-5.0, -3.0, -1.0, 1.0, 3.0, 5.0]\ny = [2.9442, 2.8198, 2.3562, 0.7854, 0.32175, 0.1974]\n\n\nx = np.array(x)\nt = np.array([[i ** j for i in x] for j in reversed(range(2))])\nt_tr = np.transpose(t)\ng = np.dot(t, t_tr)\nsecond = np.dot(inv(g), np.dot(t,y))\nprint(second)#коэффы\n\n\nx = np.array(x)\nt = np.array([[i ** j for i in x] for j in reversed(range(3))])\nt_tr = np.transpose(t)\ng = np.dot(t, t_tr)\nthird = np.dot(inv(g), np.dot(t,y))\nprint(third)# -||-\n\n\nx_vals = np.linspace(x[0], x[-1])\ny_sec = [np.polyval(second, i) for i in x_vals]\ny_thrd = [np.polyval(third, i) for i in x_vals]\n\nplt.scatter(x, y, color='r')\nplt.plot(x_vals, y_sec, color='b')\nplt.plot(x_vals, y_thrd, color='b')\nplt.show()\n \ny_err = [np.polyval(second, i) for i in x]\nerr = sum([(y_err[idx] - i) ** 2 for idx, i in enumerate(y)])\nprint('error 1 = ', err)\n\ny_err = [np.polyval(third, i) for i in x]\nerr = sum([(y_err[idx] - i) ** 2 for idx, i in enumerate(y)])\nprint('error 2 =', err)","sub_path":"Lw3/Lw3.2/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513506873","text":"from django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\n\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name='index.html')),\n url(r'^ckeditor/', include('ckeditor.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^captcha/', include('captcha.urls')),\n url(r'feedback-form/', 'feedback.views.message', name='feedback_message_create'),\n url(r'callback-form/', 'feedback.views.callback', name='feedback_callback_create'),\n url(r'^objekty/$', 'index_page.views.objects_list_view', name='objects_list'),\n url(r'^documentatsia/$', 'index_page.views.documents_list_view', name='documents_list'),\n url(r'^t/(.*)$', 'django.shortcuts.render'),\n) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += [\n url(r'^__debug__/', include(debug_toolbar.urls)),\n url(r'^404/$', TemplateView.as_view(template_name='404.html')),\n url(r'^500/$', TemplateView.as_view(template_name='500.html')),\n ]\n\nurlpatterns += [\n url(r'^(?P.*/)$', 'simplepages.views.page', name = 'simplepages'),\n]\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519758574","text":"from core.Stat import CodingStat\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n根目录 = '../'\n\n课表比例文件名 = '课标比例.xlsx'\n\n编码文件前缀 = '自主命题省份高考语文试卷编码——'\n\n列标题 = ['序号', '考卷名称', '年度', '总分', '总题量', '分值', '题面', '知识维度', '认知能力维度',\n '核心素养目标维度(语言)', '核心素养目标维度(思维)', '核心素养目标维度(审美)', '核心素养目标维度(文化)',\n '典型任务', '情境', '备注']\n\n存储中间结果到 = 'out'\n\n存储总结到 = 'out/总结.xlsx'\n\n维度一标题 = \"知识维度\" # 列标题(第一行)\n维度二标题 = \"认知能力维度\" # 行标题(第一列)\n\n维度一映射 = {\n 1: '1语言',\n 2: '2语用',\n 3: '3文体',\n 4: '4文学',\n 5: '5文化'\n}\n\n维度二映射 = {\n 1: '1识记',\n 2: '2理解',\n 3: '3应用',\n 4: '4分析',\n 5: '5评价',\n 6: '6创造',\n}\n\n\nstat = CodingStat(根目录, 编码文件前缀, 列标题, 课表比例文件名, 维度一标题, 维度二标题, 维度一映射, 维度二映射, 存储中间结果到)\nstat.load_files()\n\nsummary = stat.summary(存储总结到)\n","sub_path":"程序/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"253088654","text":"from comm import common\nfrom comm import configHttp\nimport readConfig as readConfig\nfrom comm.Log import MyLog\nimport requests\nfrom comm import configDB\nimport re\nimport os\nimport base64\n\nReadConfig = readConfig.ReadConfig()\nConfigHttp = configHttp.ConfigHttp()\nlocalLogin_xls = common.get_xls(\"pc.xlsx\", \"login\")\ndb=configDB.MyDB\n\n# login\ndef login():\n \"\"\"\n login\n :return: token\n \"\"\"\n # set url登录\n url = common.get_url_from_xml('login')\n ConfigHttp.set_pcurl(url)\n # set header\n\n # set data\n data = {'j_username': \"website;\" + localLogin_xls[0][3] + \";\" + localLogin_xls[0][4] + \";mobile\",\n 'j_password': localLogin_xls[0][4],\n 'rememberMe': \"true\"\n }\n #print(data)\n ConfigHttp.set_data(data)\n\n # login\n response = ConfigHttp.post()\n info = response.json()\n #print(response.text)\n s=response.cookies\n cookies=requests.utils.dict_from_cookiejar(s) #cookie 转字典\n ReadConfig.set_cookies(\"JSESSIONID\",cookies[\"JSESSIONID\"])\n ReadConfig.set_cookies(\"SPRING_SECURITY_REMEMBER_ME_COOKIE\",cookies[\"SPRING_SECURITY_REMEMBER_ME_COOKIE\"])\n if info['responseObject']['responseStatus'] == True:\n print(\"登录成功\")\n else:\n print(info['responseObject']['responseMessage'])\n\ndef getwebuser():\n #set url getwebuser\n url=common.get_url_from_xml('getWebUser')\n ConfigHttp.set_pcurl(url)\n #读cookie\n j = ReadConfig.get_cookie(\"jsessionid\")\n c = ReadConfig.get_cookie(\"spring_security_remember_me_cookie\")\n cookie = \"JSESSIONID=\" +j+\"; SPRING_SECURITY_REMEMBER_ME_COOKIE=\"+ c\n #print(cookie)\n headers = {'Cookie':cookie} #cookie放入header中传输\n # print\n\n ConfigHttp.set_headers(headers)\n response=ConfigHttp.post()\n #print(response.json())\n info=response.json()\n customer_id=info['responseObject']['responseMessage']['userId']\n trueName = info['responseObject']['responseMessage']['trueName']\n #存入congif\n ReadConfig.set_customer(\"customerid\",customer_id)\n ReadConfig.set_customer(\"customername\",trueName)\n\n\n\n# logout\ndef logout():\n\n # set url\n url = common.get_url_from_xml('logout')\n ConfigHttp.set_pcurl(url)\n\n # set header\n data = {'paramJson': \"undefined\"}\n #读cookie\n j = ReadConfig.get_cookie(\"jsessionid\")\n c = ReadConfig.get_cookie(\"spring_security_remember_me_cookie\")\n cookie = \"JSESSIONID=\" +j+\"; SPRING_SECURITY_REMEMBER_ME_COOKIE=\"+ c\n #print(cookie)\n headers = {'Cookie':cookie}\n # print(cookies)\n ConfigHttp.set_data(data)\n\n # logout\n response=ConfigHttp.post()\n #print(response.text)\n\n\ndef h5_Rigistsendcode(self,mobile):\n\n url = common.get_url_from_xml('h5_sendcode')\n ConfigHttp.set_h5url(url)\n #data\n paramJson = {\"userType\":1,\"account\":str(mobile),\"accountType\":0,\"siteId\":21}\n data = {'paramJson' : str(paramJson)}\n ConfigHttp.set_data(data)\n #post\n return_json = ConfigHttp.post()\n info = return_json.json()\n #存codeid\n # ReadConfig.set_patient('codeid', info['responseObject']['responsePk'])\n # print(\"请求验证码返回值:\"+return_json.text)\n codeid=info['responseObject']['responsePk']\n #从数据库中取验证码\n sql = common.get_sql('tocure_platform', 'tocure_customer_send_code', 'select_code')\n #print(sql)\n # sql参数化\n result = db.executeSQL(self, sql=sql, params=mobile)\n s = db.get_one(self, result) # 返回结果eg.('1234',)\n db.closeDB(self)\n code = re.findall(r\"'(.+?)'\", str(s))[0] # 正则取验证码 findall返回元祖,取第一个元素\n # ReadConfig.set_patient('code', code)\n # print(\"验证码为:\"+result)\n return codeid,code\n\n# def h5_Fastlogincode(self,mobile):\n# url = common.get_url_from_xml('h5_sendcode')\n# ConfigHttp.set_h5url(url)\n# #data\n# paramJson = {\"userType\":1,\"account\":str(mobile),\"accountType\":0,\"operateType\":8,\"codeLength\":4,\"siteId\":21,\"typeId\":3}\n# data = {'paramJson' : str(paramJson)}\n# ConfigHttp.set_data(data)\n# return_json = ConfigHttp.post()\n# info = return_json.json()\n# # 存codeid\n# # ReadConfig.set_patient('codeid', info['responseObject']['responsePk'])\n# # print(\"请求验证码返回值:\"+return_json.text)\n# codeid = info['responseObject']['responsePk']\n# # 从数据库中取验证码\n# sql = common.get_sql('tocure_platform', 'tocure_customer_send_code', 'select_code')\n# # print(sql)\n# # sql参数化 执行语句\n# result = db.executeSQL(self, sql=sql, params=mobile)\n# s = db.get_one(self, result) # 返回结果eg.('1234',)\n# db.closeDB(self)\n# code = re.findall(r\"'(.+?)'\", str(s))[0] # 正则取验证码 findall返回元祖,取第一个元素\n# # ReadConfig.set_patient('code', code)\n# # print(\"验证码为:\"+result)\n# return codeid, code\n\n#\n# def h5_restpasswdcode(self,mobile):\n# url = common.get_url_from_xml('h5_sendcode')\n# ConfigHttp.set_h5url(url)\n# #data\n# paramJson = {\"userType\":1,\"account\":str(mobile),\"accountType\":0,\"operateType\":3,\"codeLength\":4,\"siteId\":21,\"typeId\":1}\n# data = {'paramJson' : str(paramJson)}\n# ConfigHttp.set_data(data)\n# return_json = ConfigHttp.post()\n# info = return_json.json()\n# # 存codeid\n# # ReadConfig.set_patient('codeid', info['responseObject']['responsePk'])\n# # print(\"请求验证码返回值:\"+return_json.text)\n# codeid = info['responseObject']['responsePk']\n# # 从数据库中取验证码\n# sql = common.get_sql('tocure_platform', 'tocure_customer_send_code', 'select_code')\n# # print(sql)\n# # sql参数化\n# result = db.executeSQL(self, sql=sql, params=mobile)\n# s = db.get_one(self, result) # 返回结果eg.('1234',)\n# db.closeDB(self)\n# code = re.findall(r\"'(.+?)'\", str(s))[0] # 正则取验证码 findall返回元祖,取第一个元素\n# # ReadConfig.set_patient('code', code)\n# # print(\"验证码为:\"+result)\n# return codeid, code\n\ndef h5_changemobilecode(self,mobile):\n url = common.get_url_from_xml('h5_sendcode')\n ConfigHttp.set_h5url(url)\n #data\n paramJson = {\"typeId\":2,\"accountType\":0,\"siteId\":21,\"userType\":1,\"operateType\":2,\"account\":str(mobile),\"codeLength\":4}\n data = {'paramJson' : str(paramJson)}\n ConfigHttp.set_data(data)\n return_json = ConfigHttp.post()\n info = return_json.json()\n # 存codeid\n # ReadConfig.set_patient('codeid', info['responseObject']['responsePk'])\n print(\"请求验证码返回值:\"+return_json.text)\n codeid = info['responseObject']['responsePk']\n # 从数据库中取验证码\n sql = common.get_sql('tocure_platform', 'tocure_customer_send_code', 'select_code')\n # print(sql)\n # sql参数化\n result = db.executeSQL(self, sql=sql, params=mobile)\n s = db.get_one(self, result) # 返回结果eg.('1234',)\n db.closeDB(self)\n code = re.findall(r\"'(.+?)'\", str(s))[0] # 正则取验证码 findall返回元祖,取第一个元素\n # ReadConfig.set_patient('code', code)\n # print(\"验证码为:\"+result)\n return codeid, code\n\n\n#无效H5账号\ndef deleteAccount(mobile):\n #后台查询账号id\n selecturl=common.get_url_from_xml('selectAccount')\n ConfigHttp.set_backgrounturl(selecturl)\n #data\n queryJson={\"mobile\": mobile, \"sortType\": \"1\"}\n data={ \"queryJson\":str(queryJson),\n \"_search\": \"false\",\n \"rows\": \"10\",\n \"page\": \"1\",\n \"sort\": \"id\",\n \"order\": \"desc\"}\n\n ConfigHttp.set_data(data)\n return_json=ConfigHttp.post()\n info = return_json.json()\n id= info['rows'][0]['id']\n nickname = info['rows'][0]['nickname']\n email = info['rows'][0]['email']\n siteId=info['rows'][0]['siteId']\n customerId=info['rows'][0]['customerId']\n # print(return_json.text)\n\n #无效患者账号\n url= common.get_url_from_xml('deleteAccount')\n ConfigHttp.set_backgrounturl(url)\n #data\n queryJson1={\"id\": id, \"customerId\": customerId, \"nickname\": nickname, \"mobile\": mobile, \"email\": email,\n \"customerType\": \"0\", \"siteId\": siteId, \"isValid\": \"0\"}\n data1 = {\"queryJson\":str(queryJson1)}\n ConfigHttp.set_data(data1)\n result = ConfigHttp.post()\n # print(result.url)\n print(\"无效账号请求返回值\"+result.text)\n\n\n\n# def h5_login():\n# url=common.get_url_from_xml('h5_login')\n# ConfigHttp.set_h5url(url)\n# #data\n# mobile = ReadConfig.get_patient('mobile')\n# password = ReadConfig.get_patient('password')\n# paramJson={\"siteId\":21,\"account\":mobile,\"password\":password}\n# data={'paramJson':str(paramJson)}\n# ConfigHttp.set_data(data)\n# return_json=ConfigHttp.post()\n# info=return_json.json()\n#\n# customer_id=info['responseObject']['responseData']['customerId']\n# # print(customer_id)\n# ReadConfig.set_patient('patient_customerid',str(customer_id))\n# if info['responseObject']['responseStatus'] == True:\n# print(\"登录成功\")\n# else:\n# print(info['responseObject']['responseMessage'])\n\ndef h5_logout():\n url=common.get_url_from_xml('h5_logout')\n ConfigHttp.set_h5url(url)\n #data\n paramJson={}\n data={\"paramJson\": str(paramJson)}\n ConfigHttp.set_data(data)\n return_json=ConfigHttp.post()\n info = return_json.json()\n if info['responseObject']['responseStatus'] == True:\n print(\"退出登录成功\")\n else:\n print(info['responseObject']['responseMessage'])\n\n\ndef uploadPic(picName):\n url = common.get_url_from_xml('h5_getpicurl')\n ConfigHttp.set_h5url(url)\n #data\n # 截取格式\n type = picName.split('.')[1]\n # 路径定义\n picDir = os.path.join(readConfig.proDir, \"testFile\", \"img\", picName)\n # 图片base64处理\n # 打开文件\n f = open(picDir, 'rb')\n # base64加密\n content = base64.b64encode(f.read())\n # 解密为字符串\n content_str = content.decode('utf-8')\n f.close()\n # print(content)\n\n paramJson = {\"fileContent\": content_str,\n \"fileName\": picName,\n \"extName\": type,\n \"caseId\": \"\",\n \"imageType\": 0,\n \"caseCategoryId\": \"\"\n }\n data = {\n 'paramJson': str(paramJson)\n }\n ConfigHttp.set_data(data)\n return_json=ConfigHttp.post()\n print(\"上传图片结果\"+return_json.text)\n info=return_json.json()\n picurl=info['responseObject']['responseData']['logoUrl']\n id= info['responseObject']['responsePk']\n return id,picurl","sub_path":"comm/businessCommon.py","file_name":"businessCommon.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"341495624","text":"london_co = {\n 'r1': {\n 'location': '21 New Globe Walk',\n 'vendor': 'Cisco',\n 'model': '4451',\n 'ios': '15.4',\n 'ip': '10.255.0.1'\n },\n 'r2': {\n 'location': '21 New Globe Walk',\n 'vendor': 'Cisco',\n 'model': '4451',\n 'ios': '15.4',\n 'ip': '10.255.0.2'\n },\n 'sw1': {\n 'location': '21 New Globe Walk',\n 'vendor': 'Cisco',\n 'model': '3850',\n 'ios': '3.6.XE',\n 'ip': '10.255.0.101',\n 'vlans': '10,20,30',\n 'routing': True\n }\n}\ndevname = input(\"Введите имя устройства: \")\nprint()\nif devname in london_co.keys():\n print(london_co.get(devname))\n temp = london_co.get(devname).keys()\n parname = input(\"Введите имя параметра: {}\".format(str(temp)) + \"\\t\").lower()\n if parname in london_co.get(devname):\n print(london_co.get(devname)[parname])\n else:\n print(\"Нет такого параметра\")\n# print(london_co.keys())\n\n# for key in london_co.keys():\n# print(key + \" \" + london_co[key])\n\n\n\n#\n# if devname in london_co.keys():\n# print(london_co.values(devname))\n# else:\n# print(\"Устройства нет в списке\")","sub_path":"BASE_PY01/tasks05/task_5_1.py","file_name":"task_5_1.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310524330","text":"nl = input('Digite um numero inteiro: ')\nv = int(input('Qual base você deseja converter? 1- Binario; 2- Octal e 3- Hexadecimal: '))\nn = int(nl)\n\nnb = ''\nwhile n > 0:\n\n if v == 1:\n cb = bin(n)\n print('coversao binario', cb[2:])\n\n if n % 2 == 0:\n n = int(n/2)\n #nr = 1\n print('resto é:', 0, end='')\n #nb += '0'\n elif n % 2 == 1:\n n = int(n/2)\n #nr = 1\n print('resto é:', 1, end ='')\n #nb += '1'\n if v == 2:\n co = oct(n)\n print('conversao oc', co[2:1])\n elif v == 3:\n ch = hex(n)\n print('conversao hex', ch)[2:1]\n\n\n\n\n\n #nbi = nb[::-1]\n #if int(nl) > 0:\n # assert '0b' + nb == bin(int(nl))\n# p = int(n/8)\n# n = int(n % 8)\n# print('sobra é:', p, n)\n# def nh(n):\n# if n>= 16:\n# if n < 0:\n# print(0),\n# elif n<=1:\n# print(n)\n# else:\n# p = int(n/16)\n# x = int(n % 16)\n# if x < 10:\n## print(n),\n# if x == 10:\n# print('A'),\n# if x == 11:\n# print('B'),\n# if x == 12:\n# print('C'),\n# if x == 13:\n# print('D'),\n# if x == 14:\n# print('E'),\n# if x == 15:\n# print('F'),\n\n# nh(n / 16)","sub_path":"exercicio37aula12python.py","file_name":"exercicio37aula12python.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4428822","text":"\"\"\"\r\nCode is based on:\r\n[1] http://deeplearning.net/tutorial/logreg.html\r\n[2] http://deeplearning.net/tutorial/mlp.html\r\n[3] http://deeplearning.net/tutorial/lenet.html\r\n[4] Materials of Deep Learning and Neural Networks by prof. Aurel Lazar, Columbai University\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\n\r\nimport timeit\r\nimport inspect\r\nimport sys\r\nimport numpy\r\n\r\nimport theano\r\nimport theano.tensor as T\r\nfrom theano.tensor.nnet import conv2d\r\nfrom theano.tensor.signal import downsample\r\n\r\nclass LogisticRegression(object):\r\n \"\"\"\r\n Logistic regression layer for output layer\r\n\r\n \"\"\"\r\n\r\n def __init__(self, input, n_in, n_out):\r\n \"\"\" Initialize the parameters of the logistic regression\r\n\r\n input: symbolic variable that describes the input of the\r\n architecture (one minibatch)\r\n n_in: number of input units\r\n n_out: number of output units (classes)\r\n\r\n \"\"\"\r\n # initialize with 0 the weights W as a matrix of shape (n_in, n_out)\r\n self.W = theano.shared(\r\n value=numpy.zeros(\r\n (n_in, n_out),\r\n dtype=theano.config.floatX\r\n ),\r\n name='W4',\r\n borrow=True\r\n )\r\n # initialize the biases b as a vector of n_out 0s\r\n self.b = theano.shared(\r\n value=numpy.zeros(\r\n (n_out,),\r\n dtype=theano.config.floatX\r\n ),\r\n name='b4',\r\n borrow=True\r\n )\r\n\r\n # Output after softmax (probabilities)\r\n self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)\r\n \r\n # Top3 classes\r\n self.top = T.argsort(self.p_y_given_x, axis=1)[:,-3:]\r\n # Top3 probability\r\n self.topdist = T.sort(self.p_y_given_x, axis=1)[:,-3:]\r\n # Top class\r\n self.y_pred = T.argmax(self.p_y_given_x, axis=1)\r\n\r\n # parameters of the model\r\n self.params = [self.W, self.b]\r\n\r\n # keep track of model input\r\n self.input = input\r\n\r\n def negative_log_likelihood(self, y):\r\n \"\"\"Return the mean of the negative log-likelihood of the prediction\r\n of this model under a given target distribution. \r\n \"\"\"\r\n\r\n return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])\r\n\r\n def errors(self, y):\r\n \"\"\"Return a float representing the number of errors in the minibatch\r\n over the total number of examples of the minibatch ; zero one\r\n loss over the size of the minibatch\r\n\r\n y: corresponds to a vector that gives for each example the\r\n correct label\r\n \"\"\"\r\n\r\n # check if y has same dimension of y_pred\r\n if y.ndim != self.y_pred.ndim:\r\n raise TypeError(\r\n 'y should have the same shape as self.y_pred',\r\n ('y', y.type, 'y_pred', self.y_pred.type)\r\n )\r\n # check if y is of the correct datatype\r\n if y.dtype.startswith('int'):\r\n # the T.neq operator returns a vector of 0s and 1s, where 1\r\n # represents a mistake in prediction\r\n return T.mean(T.neq(self.y_pred, y))\r\n else:\r\n raise NotImplementedError()\r\n\r\nclass HiddenLayer(object):\r\n def __init__(self, rng, input, n_in, n_out, W=None, b=None,\r\n activation=T.tanh):\r\n \"\"\"\r\n Fully connected layer\r\n NOTE : The nonlinearity used here is tanh\r\n\r\n rng: a random number generator used to initialize weights\r\n\r\n input: a symbolic tensor of shape (n_examples, n_in)\r\n\r\n n_in: dimensionality of input\r\n\r\n n_out: number of hidden units\r\n\r\n activation: Non linearity to be applied in the hidden\r\n layer\r\n \"\"\"\r\n self.input = input\r\n\r\n # Initialize weights\r\n if W is None:\r\n W_values = numpy.asarray(\r\n rng.uniform(\r\n low=-numpy.sqrt(6. / (n_in + n_out)),\r\n high=numpy.sqrt(6. / (n_in + n_out)),\r\n size=(n_in, n_out)\r\n ),\r\n dtype=theano.config.floatX\r\n )\r\n if activation == theano.tensor.nnet.sigmoid:\r\n W_values *= 4\r\n\r\n W = theano.shared(value=W_values, name='W3', borrow=True)\r\n\r\n if b is None:\r\n b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)\r\n b = theano.shared(value=b_values, name='b3', borrow=True)\r\n\r\n self.W = W\r\n self.b = b\r\n\r\n # relu actication\r\n def relu(x):\r\n return theano.tensor.switch(x<0, 0, x)\r\n \r\n lin_output = T.dot(input, self.W) + self.b\r\n self.output = (\r\n lin_output if activation is None\r\n else activation(lin_output)\r\n )\r\n # parameters of the model\r\n self.params = [self.W, self.b]\r\n\r\n\r\nclass ConvPoolLayer(object):\r\n \"\"\"Pool Layer of a convolutional network \"\"\"\r\n\r\n def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2), idx=0,\r\n pool_ignore_border=True):\r\n \"\"\"\r\n rng: a random number generator used to initialize weights\r\n\r\n input: symbolic image tensor, of shape image_shape\r\n\r\n filter_shape: (number of filters, num input feature maps,\r\n filter height, filter width)\r\n image_shape: (batch size, num input feature maps,\r\n image height, image width)\r\n\r\n poolsize: the downsampling (pooling) factor (#rows, #cols)\r\n \"\"\"\r\n\r\n assert image_shape[1] == filter_shape[1]\r\n self.input = input\r\n\r\n # there are \"num input feature maps * filter height * filter width\"\r\n # inputs to each hidden unit\r\n fan_in = numpy.prod(filter_shape[1:])\r\n # each unit in the lower layer receives a gradient from:\r\n # \"num output feature maps * filter height * filter width\" /\r\n # pooling size\r\n fan_out = (filter_shape[0] * numpy.prod(filter_shape[2:]) //\r\n numpy.prod(poolsize))\r\n \r\n # initialize weights \r\n W_bound = numpy.sqrt(6. / (fan_in + fan_out))\r\n self.W = theano.shared(\r\n numpy.asarray(\r\n rng.uniform(low=-W_bound, high=W_bound, size=filter_shape),\r\n dtype=theano.config.floatX\r\n ),\r\n name='W'+str(idx),\r\n borrow=True\r\n )\r\n b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX)\r\n self.b = theano.shared(value=b_values, name='b'+str(idx), borrow=True)\r\n\r\n # convolve input feature maps with filters\r\n conv_out = conv2d(\r\n input=input,\r\n filters=self.W,\r\n filter_shape=filter_shape,\r\n image_shape=image_shape\r\n )\r\n\r\n # downsample each feature map individually, using maxpooling\r\n pooled_out = downsample.max_pool_2d(\r\n input=conv_out,\r\n ds=poolsize,\r\n ignore_border=pool_ignore_border\r\n )\r\n\r\n # Output after activation\r\n self.output = T.tanh(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))\r\n\r\n # store parameters of this layer\r\n self.params = [self.W, self.b]\r\n\r\n # keep track of model input\r\n self.input = input\r\n\r\ndef train_net(train_model, validate_model, test_model,\r\n n_train_batches, n_valid_batches, n_test_batches, n_epochs,\r\n verbose = True):\r\n \"\"\"\r\n Function for training and test THEANO model\r\n\r\n train_model: theano function for training with updates defined\r\n\r\n validate_model: theano funvtion for validation\r\n\r\n test_model: theano function for testing\r\n\r\n n_train_batches: number of training batches\r\n\r\n n_valid_batches: number of validation batches\r\n\r\n n_test_batches: number of testing batches\r\n\r\n n_epochs: maximal number of epochs before exiting\r\n\r\n verbose: to print out epoch summary or not to\r\n\r\n \"\"\"\r\n\r\n # early-stopping parameters\r\n patience = 1000000 # look as this many examples regardless\r\n patience_increase = 2 # wait this much longer when a new best is\r\n # found\r\n improvement_threshold = 0.85 # a relative improvement of this much is\r\n # considered significant\r\n validation_frequency = min(n_train_batches, patience // 2)\r\n # go through this many\r\n # minibatche before checking the network\r\n # on the validation set; in this case we\r\n # check every epoch\r\n\r\n best_validation_loss = numpy.inf\r\n best_iter = 0\r\n test_score = 0.\r\n start_time = timeit.default_timer()\r\n\r\n epoch = 0\r\n done_looping = False\r\n\r\n while (epoch < n_epochs) and (not done_looping):\r\n epoch = epoch + 1\r\n for minibatch_index in range(n_train_batches):\r\n\r\n iter = (epoch - 1) * n_train_batches + minibatch_index\r\n\r\n if (iter % 100 == 0) and verbose:\r\n print('training @ iter = ', iter)\r\n cost_ij = train_model(minibatch_index)\r\n\r\n if (iter + 1) % validation_frequency == 0:\r\n\r\n # compute zero-one loss on validation set\r\n validation_losses = [validate_model(i) for i\r\n in range(n_valid_batches)]\r\n this_validation_loss = numpy.mean(validation_losses)\r\n\r\n if verbose:\r\n print('epoch %i, minibatch %i/%i, validation error %f %%' %\r\n (epoch,\r\n minibatch_index + 1,\r\n n_train_batches,\r\n this_validation_loss * 100.))\r\n\r\n # if we got the best validation score until now\r\n if this_validation_loss < best_validation_loss:\r\n\r\n #improve patience if loss improvement is good enough\r\n if this_validation_loss < best_validation_loss * \\\r\n improvement_threshold:\r\n patience = max(patience, iter * patience_increase)\r\n\r\n # save best validation score and iteration number\r\n best_validation_loss = this_validation_loss\r\n best_iter = iter\r\n\r\n # test it on the test set\r\n test_losses = [\r\n test_model(i)\r\n for i in range(n_test_batches)\r\n ]\r\n test_score = numpy.mean(test_losses)\r\n\r\n if verbose:\r\n print((' epoch %i, minibatch %i/%i, test error of '\r\n 'best model %f %%') %\r\n (epoch, minibatch_index + 1,\r\n n_train_batches,\r\n test_score * 100.))\r\n\r\n if patience <= iter:\r\n done_looping = True\r\n break\r\n\r\n end_time = timeit.default_timer()\r\n\r\n # Retrieve the name of function who invokes train_nn() (caller's name)\r\n curframe = inspect.currentframe()\r\n calframe = inspect.getouterframes(curframe, 2)\r\n\r\n # Print out summary\r\n print('Optimization complete.')\r\n print('Best validation score of %f %% obtained at iteration %i, '\r\n 'with test performance %f %%' %\r\n (best_validation_loss * 100., best_iter + 1, test_score * 100.))\r\n print(('The training process for function ' +\r\n calframe[1][3] +\r\n ' ran for %.2fm' % ((end_time - start_time) / 60.)), file=sys.stderr)\r\n\r\n","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":11707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204632853","text":"from pymongo import MongoClient\r\n\r\nuri = \"mongodb://searchbot:search_kankhajura@cluster0-shard-00-00.6nsgq.mongodb.net:27017,cluster0-shard-00-01.6nsgq.mongodb.net:27017,cluster0-shard-00-02.6nsgq.mongodb.net:27017/mgd?ssl=true&replicaSet=atlas-3brzwx-shard-0&authSource=admin&retryWrites=true&w=majority\"\r\nmclient = MongoClient(uri)\r\nmydb = mclient['UserSetting']\r\nm_pref = mydb['pref']\r\nwid = mydb['wid']\r\n\r\nimport re\r\npattern = re.compile(r'([aA-zZ]{2}).([aA-zZ]{3})')\r\ndefault = 1\r\n\r\ndef get_wid(query,user_id = None):\r\n\t# check user pref then\r\n\tfindin = ''\r\n\tw = None\r\n\tcc = False\r\n\tif 'world' in query:\r\n\t\treturn {'woeid':1,'name':'World','country':'World'}\r\n\tc = query.split('.') if '.' in query else query\r\n\t# print(f'{c=}')\r\n\tif (c.__class__ is list):\r\n\t\tx = pattern.match(query)\r\n\t\t# print(x)\r\n\t\ttry:\r\n\t\t\tc = x.group()\r\n\t\texcept AttributeError:\r\n\t\t\tpass\r\n\t\t\t# print('attributes')\r\n\t\tfindin = 'cmd'\r\n\telif len(c) == 2:\r\n\t\tfindin = 'countryCode'\r\n\t\tcc = True\r\n\telif len(c) > 2:\r\n\t\tfindin = 'name'\r\n\r\n\r\n\treg = {\"$regex\": f'^{c}',\"$options\":'i'}\r\n\t\r\n\tif cc is True:\r\n\t\tw = wid.find_one({findin:reg, 'placeType':'Country'},{'woeid':1,'name':1,'country':1})\r\n\telse:\r\n\t\tw = wid.find_one({findin:reg},{'woeid':1,'name':1,'country':1})\r\n\t\r\n\t# print(f' 1️⃣ {w=}' )\r\n\t\t\r\n\tif w is not None:\r\n\t\treturn w\r\n\telse:\r\n\t\treturn default\r\n\t# if (len(cmd.strip()) < 1) and (w := pref_exist(user_id)):\r\n\t# \t# w = w['woeid'] \r\n\t# \treturn w['WOEID']\r\n\t# else:\r\n\t# \tif any(cmd.strip()) is False:\r\n\t# \t\tw = wid.find_one({'cmd':\"in.in\"},{'woeid':1 ,'name':1})\r\n\t# \t\treturn w['woeid']\r\n\t# \telse:\r\n\t# \t\tw = wid.find_one({'cmd':cmd},{'woeid':1})\r\n\t# \t\tif w is not None:\r\n\t# \t\t\treturn w['woeid']\r\n\t# \t\telse:\r\n\t# \t\t\tw = wid.find_one({'cmd':\"in.in\"},{'woeid':1})\r\n\t# \t\t\treturn w\r\n\r\n# city = {\"$regex\":^mum}\r\n# db.all_woed.find({ \"$and\":[countrycode:in, name:city] }\r\n\r\ndef pref_exist(user_id):\r\n\tx = m_pref.find_one(user_id)\r\n\tif x is not None:\r\n\t\treturn x\r\n\telse:\r\n\t\tx = wid.find_one({\"placeType\":\"Country\", \"countryCode\":\"IN\"},{'woeid':1,'name':1,\"country\":1})\r\n\t\t# print(f'{x=}')\r\n\t\treturn x\r\n\r\n# x = \"in.hyd\"\r\n# x = x.split(\".\")\r\n\r\n# print(get_trends(user_id=123456789, query=x))\r\n","sub_path":"mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"545283008","text":"import chdb\nimport config\nfrom common import *\n\nfrom snippet_parser import CITATION_NEEDED_MARKER, REF_MARKER\n\nimport collections\n\n# the markup we're going to use for [citation needed] and tags,\n# pre-marked as safe for jinja.\nSUPERSCRIPT_HTML = '[%s]'\nSUPERSCRIPT_MARKUP = flask.Markup(SUPERSCRIPT_HTML)\nCITATION_NEEDED_MARKUP = flask.Markup(SUPERSCRIPT_HTML)\n\nCategory = collections.namedtuple('Category', ['id', 'title'])\nCATEGORY_ALL = Category('all', '')\ndef get_categories(lang_code, include_default = True):\n categories = getattr(flask.g, '_categories', None)\n if categories is None:\n cursor = get_db(lang_code).cursor()\n cursor.execute('''\n SELECT id, title FROM categories WHERE id != \"unassigned\"\n ORDER BY title;\n ''')\n categories = [CATEGORY_ALL] + [Category(*row) for row in cursor]\n flask.g._categories = categories\n return categories if include_default else categories[1:]\n\ndef get_category_by_id(lang_code, catid, default = None):\n for c in get_categories(lang_code):\n if catid == c.id:\n return c\n return default\n\ndef select_snippet_by_id(lang_code, id):\n cursor = get_db(lang_code).cursor()\n with log_time('select snippet by id'):\n cursor.execute('''\n SELECT snippets.snippet, snippets.section, articles.url,\n articles.title FROM snippets, articles WHERE snippets.id = %s AND\n snippets.article_id = articles.page_id;''', (id,))\n ret = cursor.fetchone()\n return ret\n\ndef select_random_id(lang_code, cat = CATEGORY_ALL):\n cursor = get_db(lang_code).cursor()\n\n ret = None\n if cat is not CATEGORY_ALL:\n with log_time('select with category'):\n cursor.execute('''\n SELECT snippets.id FROM snippets, articles_categories\n WHERE snippets.article_id = articles_categories.article_id AND\n articles_categories.category_id = %s ORDER BY RAND()\n LIMIT 1;''', (cat.id,))\n ret = cursor.fetchone()\n\n if ret is None:\n # Try to pick one id at random. For small datasets, the probability\n # of getting an empty set in a query is non-negligible, so retry a\n # bunch of times as needed.\n p = '1e-4' if not flask.current_app.debug else '1e-2'\n with log_time('select without category'):\n for retry in range(1000):\n cursor.execute(\n 'SELECT id FROM snippets WHERE RAND() < %s LIMIT 1;', (p,))\n ret = cursor.fetchone()\n if ret: break\n\n assert ret and len(ret) == 1\n return ret[0]\n\ndef select_next_id(lang_code, curr_id, cat = CATEGORY_ALL):\n cursor = get_db(lang_code).cursor()\n\n if cat is not CATEGORY_ALL:\n with log_time('select next id'):\n cursor.execute('''\n SELECT next FROM snippets_links WHERE prev = %s\n AND cat_id = %s''', (curr_id, cat.id))\n ret = cursor.fetchone()\n if ret is None:\n # curr_id doesn't belong to the category\n return None\n assert ret and len(ret) == 1\n next_id = ret[0]\n else:\n next_id = curr_id\n for i in range(3): # super paranoid :)\n next_id = select_random_id(lang_code, cat)\n if next_id != curr_id:\n break\n return next_id\n\ndef should_autofocus_category_filter(cat, request):\n return cat is CATEGORY_ALL and not request.MOBILE\n\n@validate_lang_code\ndef citation_hunt(lang_code):\n id = flask.request.args.get('id')\n cat = flask.request.args.get('cat')\n cfg = config.get_localized_config(lang_code)\n\n lang_dir = cfg.lang_dir\n if flask.current_app.debug:\n lang_dir = flask.request.args.get('dir', lang_dir)\n\n if cat is not None:\n cat = get_category_by_id(lang_code, cat)\n if cat is None:\n # invalid category, normalize to \"all\" and try again by id\n cat = CATEGORY_ALL\n return flask.redirect(\n flask.url_for('citation_hunt',\n lang_code = lang_code, id = id, cat = cat.id))\n else:\n cat = CATEGORY_ALL\n\n if id is not None:\n sinfo = select_snippet_by_id(lang_code, id)\n if sinfo is None:\n # invalid id\n flask.request.cfg = cfg\n flask.abort(404)\n snippet, section, aurl, atitle = sinfo\n next_snippet_id = select_next_id(lang_code, id, cat)\n if next_snippet_id is None:\n # the snippet doesn't belong to the category!\n assert cat is not CATEGORY_ALL\n return flask.redirect(\n flask.url_for('citation_hunt',\n id = id, cat = CATEGORY_ALL.id,\n lang_code = lang_code))\n autofocus = should_autofocus_category_filter(cat, flask.request)\n return flask.render_template('index.html',\n snippet = snippet, section = section, article_url = aurl,\n article_title = atitle, current_category = cat,\n next_snippet_id = next_snippet_id,\n cn_marker = CITATION_NEEDED_MARKER,\n cn_html = CITATION_NEEDED_MARKUP,\n ref_marker = REF_MARKER,\n ref_html = SUPERSCRIPT_MARKUP,\n config = cfg,\n lang_dir = lang_dir,\n category_filter_autofocus = autofocus)\n\n id = select_random_id(lang_code, cat)\n return flask.redirect(\n flask.url_for('citation_hunt',\n id = id, cat = cat.id, lang_code = lang_code))\n","sub_path":"handlers/citationhunt.py","file_name":"citationhunt.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261221115","text":"import torch\nfrom utils2.torch import to_device\nimport numpy as np\nimport multiprocessing as mp\nimport ray\n\n@ray.remote\ndef estimate_advantages(memory, value_net, gamma, tau, device='cpu', dtype=torch.double, pid=None):\n\n batch = memory.sample()\n states = torch.from_numpy(np.stack(batch.state)).to(dtype).to(device)\n rewards = torch.from_numpy(np.stack(batch.reward)).to(dtype).to(device)\n actions = torch.from_numpy(np.stack(batch.action)).to(dtype).to(device)\n masks = torch.from_numpy(np.stack(batch.mask)).to(dtype).to(device)\n\n # with torch.no_grad():\n values = value_net(states).detach()\n rewards, masks, values = to_device(torch.device('cpu'), rewards, masks, values)\n tensor_type = type(rewards)\n deltas = tensor_type(rewards.size(0), 1)\n advantages = torch.zeros((rewards.size(0), 1), dtype=dtype)\n # advantages = tensor_type(rewards.size(0), 1)\n prev_value = 0\n prev_advantage = 0\n for i in reversed(range(rewards.size(0))):\n deltas[i] = rewards[i] + gamma * prev_value * masks[i] - values[i]\n advantages[i] = deltas[i] + gamma * tau * prev_advantage * masks[i]\n\n prev_value = values[i, 0]\n prev_advantage = advantages[i, 0]\n\n # print(\"adv shape {}\".format(advantages.shape))\n # print(\"rew shape {}\".format(rewards.shape))\n # print(\"val shape {}\".format(values.shape))\n\n # returns = values + advantages\n returns = rewards\n advantages = rewards.unsqueeze(1) - values\n # advantages = advantages.unsqueeze(1)\n # print(\"adv shape {}\".format(advantages.shape))\n # advantages = (advantages - advantages.mean()) / advantages.std()\n advantages, returns, states, actions = to_device(device, advantages, returns, states, actions)\n\n return (pid, advantages, returns, states, actions)\n\n\ndef estimate_advantages_parallel(memories, value_net, gamma, tau, device='cpu', dtype=torch.float64, num_parallel_workers=mp.cpu_count()):\n # ray.init()\n result_ids = []\n for memory, pid in zip(memories, range(len(memories))):\n result_ids.append(estimate_advantages.remote(memory,\n value_net, gamma, tau, device, dtype, pid))\n\n advantages_list = [None]*len(memories)\n returns_list = [None]*len(memories)\n states_list = [None] * len(memories)\n actions_list = [None] * len(memories)\n for result_id in result_ids:\n pid, advantages, returns, states, actions = ray.get(result_id)\n advantages_list[pid] = advantages\n returns_list[pid] = returns\n states_list[pid] = states\n actions_list[pid] = actions\n\n return advantages_list, returns_list, states_list, actions_list\n\ndef estimate_advantages_parallel_noniid(memories, value_nets_list, gamma, tau, device='cpu', dtype=torch.float64, num_parallel_workers=mp.cpu_count()):\n # ray.init()\n result_ids = []\n for memory, value_net, pid in zip(memories, value_nets_list, range(len(memories))):\n result_ids.append(estimate_advantages.remote(memory,\n value_net, gamma, tau, device, dtype, pid))\n\n advantages_list = [None]*len(memories)\n returns_list = [None]*len(memories)\n states_list = [None] * len(memories)\n actions_list = [None] * len(memories)\n for result_id in result_ids:\n pid, advantages, returns, states, actions = ray.get(result_id)\n advantages_list[pid] = advantages\n returns_list[pid] = returns\n states_list[pid] = states\n actions_list[pid] = actions\n\n return advantages_list, returns_list, states_list, actions_list\n\n","sub_path":"core/common_ray_navi.py","file_name":"common_ray_navi.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611156727","text":"# -*- coding: utf8 -*-\nimport sys\nsys.path.append('..')\n\nfrom magic.magic import ctx\nfrom magic.magic import red\nfrom magic.magic import Magic\n\nimport utils.util as util\nimport handle.user\nimport handle.goods\nimport interceptor.common_interceptor as common_interceptor\nimport interceptor.function_interceptor as function_interceptor\n\nfunction = Magic()\n\n@function.route('/function', methods=['GET'])\n@function.interceptor([\n common_interceptor.check_sid,\n common_interceptor.update_session_expire])\n# function_interceptor.check_args])\ndef obtain_function():\n user_id = ctx.application['uid']\n user_info = handle.user.get_user_info(user_id)\n return function.render_template('function.html', \n user=user_info, payToken=1)\n\n\n@function.route('/goods/sell', methods=['GET'])\n@function.interceptor([\n common_interceptor.check_sid,\n common_interceptor.check_page])\ndef obtain_user_sell_goods():\n app_ctx = ctx.application\n sid = app_ctx['_sid']\n page = app_ctx['page']\n user_id = app_ctx['uid']\n\n user_info = handle.user.get_user_info(user_id)\n goods = handle.goods.get_goods_by_user_sell(sid, page)\n return function.render_template('my_sell.html',\n goods=goods, is_login=True)\n\n\n@function.route('/goods/buy', methods=['GET'])\n@function.interceptor([\n common_interceptor.check_sid,\n common_interceptor.check_page])\ndef obtain_user_buy_goods():\n app_ctx = ctx.application\n sid = app_ctx['_sid']\n page = app_ctx['page']\n user_id = app_ctx['uid']\n\n user_info = handle.user.get_user_info(user_id)\n goods = handle.goods.get_goods_by_user_buy(sid, page)\n return function.render_template('my_buy.html',\n goods=goods, is_login=True)\n\n\n@function.route('/goods/addition', methods=['GET'])\n@function.interceptor([\n common_interceptor.check_sid])\ndef obtain_goods_addition():\n user_id = ctx.application['uid']\n user_info = handle.user.get_user_info(user_id)\n return function.render_template('my_add.html',\n payToken=1, is_login=True)\n\n\n@function.route('/user/goods', methods=['POST'])\n@function.interceptor([\n common_interceptor.check_sid,\n function_interceptor.check_form,\n function_interceptor.trans_form])\ndef create_user_goods():\n app_ctx = ctx.application\n handle.goods.add_goods(app_ctx['_sid'], app_ctx['uid'], app_ctx['name'], \n app_ctx['filename'], app_ctx['tags'], app_ctx['price'], \n app_ctx['description'])\n return util.check_result(True, 'success')\n\n\n@function.route('/goods/info', methods=['GET'])\n@function.interceptor([\n common_interceptor.check_login,\n function_interceptor.check_args_gid])\ndef obtain_goods_info():\n app_ctx = ctx.application\n info = handle.goods.get_goods_info(app_ctx['_sid'], app_ctx['gid'])\n return function.render_template('item_detail.html',\n goods_info=info['goods_info'],\n user_info=info['user_info'],\n is_login=ctx.application['login'])\n\n\n@function.route('/goods', methods=['DELETE'])\n@function.interceptor([\n common_interceptor.check_login,\n function_interceptor.check_data_gid])\ndef delete_goods():\n handle.goods.delete_goods_by_gid(ctx.application['gid'])\n return util.check_result(True, 'success', location='/goods/sell')\n","sub_path":"main/routes/function_route.py","file_name":"function_route.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289261779","text":"#20220205\n#N과 M(2)\n#\n# import sys\n# from itertools import combinations\n# input = sys.stdin.readline\n#\n# n, m = map(int, input().split(' '))\n# li = list(map(str, range(1, n+1)))\n# print('\\n'.join(list(map(' '.join, combinations(li, m)))))\n\n#20220213\nimport sys\ninput = sys.stdin.readline\nn, m = map(int, input().split())\narr = [0] * m\nvisited = [False] * n\n# visited = [False for _ in range(m)]\n\n\ndef dfs(v, depth):\n if m == depth:\n for i in arr:\n print(i, end=\" \")\n print()\n return\n for i in range(v, n):\n if not visited[i]:\n visited[i] = True\n arr[depth] = i+1\n dfs(i, depth+1)\n visited[i] = False\n\n\ndfs(0, 0)","sub_path":"Python/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"530712423","text":"from datetime import datetime\nimport re\nimport sys\nimport time\n\n\nfrom . import __version__, lgr\nfrom .utils import ensure_datetime, ensure_strtime, get_instance\nfrom .consts import (\n collection_drafts,\n dandiset_identifier_regex,\n dandiset_metadata_file,\n metadata_digests,\n)\n\n\ndef upload(\n paths,\n existing=\"refresh\",\n validation=\"require\",\n dandiset_path=None,\n girder_collection=collection_drafts,\n girder_top_folder=None,\n dandi_instance=\"dandi\",\n fake_data=False, # TODO: not implemented, prune?\n allow_any_path=False,\n devel_debug=False,\n):\n # PurePosixPath to be cast to for paths on girder\n from pathlib import Path, PurePosixPath\n from .dandiset import Dandiset\n from .support.digests import Digester\n\n dandiset = Dandiset.find(dandiset_path)\n if not dandiset:\n raise RuntimeError(\n f\"Found no {dandiset_metadata_file} anywhere. \"\n \"Use 'dandi register', 'download', or 'organize' first\"\n )\n\n # Should no longer be needed\n # dandiset_path = Path(dandiset_path).resolve()\n\n # Girder side details:\n\n if not girder_collection:\n girder_collection = collection_drafts\n\n if not girder_top_folder:\n # We upload to staging/dandiset_id\n ds_identifier = dandiset.identifier\n if not ds_identifier:\n raise ValueError(\n \"No 'identifier' set for the dandiset yet. Use 'dandi register'\"\n )\n if not re.match(dandiset_identifier_regex, ds_identifier):\n raise ValueError(\n f\"Dandiset identifier {ds_identifier} does not follow expected \"\n f\"convention {dandiset_identifier_regex!r}. Use \"\n f\"'dandi register' to get a legit identifier\"\n )\n # this is a path not a girder id\n girder_top_folder = ds_identifier\n girder_top_folder = PurePosixPath(girder_top_folder)\n\n if str(girder_top_folder) in (\".\", \"..\", \"\", \"/\"):\n raise ValueError(\n f\"Got folder {girder_top_folder}, but files cannot be uploaded \"\n f\"into a collection directly.\"\n )\n\n import multiprocessing\n from . import girder\n from .pynwb_utils import ignore_benign_pynwb_warnings, get_object_id\n from .metadata import get_metadata\n from .validate import validate_file\n from .utils import find_dandi_files, find_files, path_is_subpath\n from .support.generatorify import generator_from_callback\n from .support.pyout import naturalsize\n\n ignore_benign_pynwb_warnings() # so validate doesn't whine\n\n client = girder.get_client(get_instance(dandi_instance).girder)\n\n try:\n collection_rec = girder.ensure_collection(client, girder_collection)\n except girder.gcl.HttpError as exc:\n if devel_debug:\n raise\n # provide a bit less intimidating error reporting\n lgr.error(\n \"Failed to assure presence of the %s collection: %s\",\n girder_collection,\n (girder.get_HttpError_response(exc) or {}).get(\"message\", str(exc)),\n )\n sys.exit(1)\n\n lgr.debug(\"Working with collection %s\", collection_rec)\n\n try:\n girder.lookup(client, girder_collection, path=girder_top_folder)\n except girder.GirderNotFound:\n raise ValueError(\n f\"There is no {girder_top_folder} in {girder_collection}. \"\n f\"Did you use 'dandi register'?\"\n )\n\n #\n # Treat paths\n #\n if not paths:\n paths = [dandiset.path]\n\n # Expand and validate all paths -- they should reside within dandiset\n paths = find_files(\".*\", paths) if allow_any_path else find_dandi_files(paths)\n paths = list(map(Path, paths))\n npaths = len(paths)\n lgr.info(f\"Found {npaths} files to consider\")\n for path in paths:\n if not (\n allow_any_path\n or path.name == dandiset_metadata_file\n or path.name.endswith(\".nwb\")\n ):\n raise NotImplementedError(\n f\"ATM only .nwb and dandiset.yaml should be in the paths to upload. Got {path}\"\n )\n if not path_is_subpath(str(path.absolute()), dandiset.path):\n raise ValueError(f\"{path} is not under {dandiset.path}\")\n\n # We will keep a shared set of \"being processed\" paths so\n # we could limit the number of them until\n # https://github.com/pyout/pyout/issues/87\n # properly addressed\n process_paths = set()\n from collections import defaultdict\n\n uploaded_paths = defaultdict(lambda: {\"size\": 0, \"errors\": []})\n\n def skip_file(msg):\n return {\"status\": \"skipped\", \"message\": str(msg)}\n\n lock = multiprocessing.Lock()\n\n # TODO: we might want to always yield a full record so no field is not\n # provided to pyout to cause it to halt\n def process_path(path, relpath):\n \"\"\"\n\n Parameters\n ----------\n path: Path\n Non Pure (OS specific) Path\n relpath:\n For location on Girder. Will be cast to PurePosixPath\n\n Yields\n ------\n dict\n Records for pyout\n \"\"\"\n # Ensure consistent types\n path = Path(path)\n relpath = PurePosixPath(relpath)\n try:\n try:\n path_stat = path.stat()\n yield {\"size\": path_stat.st_size}\n except FileNotFoundError:\n yield skip_file(\"ERROR: File not found\")\n return\n except Exception as exc:\n # without limiting [:50] it might cause some pyout indigestion\n yield skip_file(\"ERROR: %s\" % str(exc)[:50])\n return\n\n yield {\"status\": \"checking girder\"}\n\n girder_folder = girder_top_folder / relpath.parent\n\n # we will add some fields which would help us with deciding to\n # reupload or not\n file_metadata_ = {\n \"uploaded_size\": path_stat.st_size,\n \"uploaded_mtime\": ensure_strtime(path_stat.st_mtime),\n # \"uploaded_date\": None, # to be filled out upon upload completion\n }\n\n # A girder delete API target to .delete before uploading a file\n # (e.g. if decided to reupload)\n delete_before_upload = None\n\n def ensure_item():\n \"\"\"This function might need to be called twice, e.g. if we\n are to reupload the entire item.\n\n ATM new versions of the files would create new items since\n the policy is one File per Item\n \"\"\"\n try:\n lock.acquire(timeout=60)\n # TODO: we need to make this all thread safe all the way\n # until uploading the file since multiple threads would\n # create multiple\n # ATM it even fails with No such folder: 5e33658d6eb14e0bf49e97d5\",\n # so will first upload one file and then the rest... not sure why\n # locking doesn't work\n folder_rec = girder.ensure_folder(\n client, collection_rec, girder_collection, girder_folder\n )\n\n # Get (if already exists) or create an item\n item_rec = client.createItem(\n folder_rec[\"_id\"], name=relpath.name, reuseExisting=True\n )\n finally:\n lock.release()\n return item_rec\n\n def ensure_folder():\n try:\n lock.acquire(timeout=60)\n folder_rec = girder.ensure_folder(\n client, collection_rec, girder_collection, girder_folder\n )\n finally:\n lock.release()\n return folder_rec\n\n #\n # 1. Validate first, so we do not bother girder at all if not kosher\n #\n # TODO: enable back validation of dandiset.yaml\n if path.name != dandiset_metadata_file and validation != \"skip\":\n yield {\"status\": \"validating\"}\n validation_errors = validate_file(path)\n yield {\"errors\": len(validation_errors)}\n # TODO: split for dandi, pynwb errors\n if validation_errors:\n if validation == \"require\":\n yield skip_file(\"failed validation\")\n return\n else:\n yield {\"status\": \"validated\"}\n else:\n # yielding empty causes pyout to get stuck or crash\n # https://github.com/pyout/pyout/issues/91\n # yield {\"errors\": '',}\n pass\n\n #\n # Special handling for dandiset.yaml\n # Yarik hates it but that is life for now. TODO\n #\n if path.name == dandiset_metadata_file:\n # TODO This is a temporary measure to avoid breaking web UI\n # dandiset metadata schema assumptions. All edits should happen\n # online.\n yield skip_file(\"should be edited online\")\n return\n # We need to upload its content as metadata for the entire\n # folder.\n folder_rec = ensure_folder()\n remote_metadata = folder_rec[\"meta\"]\n if remote_metadata.get(\"dandiset\", {}) == dandiset.metadata:\n yield skip_file(\"exists (same)\")\n else:\n remote_metadata[\"dandiset\"] = dandiset.metadata\n yield {\"status\": \"uploading dandiset metadata\"}\n client.addMetadataToFolder(folder_rec[\"_id\"], remote_metadata)\n yield {\"status\": \"done\"}\n # Interrupt -- no file to upload\n return\n\n #\n # 2. Ensure having an item\n #\n item_rec = ensure_item()\n\n #\n # 3. Analyze possibly present on the remote files in the item\n #\n file_recs = list(client.listFile(item_rec[\"_id\"]))\n\n # get metadata and if we have all indications that it is\n # probably the same -- we just skip\n stat_fields = [\n # Care only about mtime, ignore ctime which could change\n \"uploaded_mtime\",\n \"uploaded_size\",\n ]\n assert sorted(file_metadata_) == stat_fields\n item_file_metadata_ = {\n k: item_rec.get(\"meta\", {}).get(k, None) for k in stat_fields\n }\n lgr.debug(\n \"Files meta: local file: %s remote file: %s\",\n file_metadata_,\n item_file_metadata_,\n )\n\n if item_file_metadata_[\"uploaded_mtime\"]:\n local_mtime = ensure_datetime(file_metadata_[\"uploaded_mtime\"])\n remote_mtime = ensure_datetime(\n item_file_metadata_.get(\"uploaded_mtime\")\n )\n remote_file_status = (\n \"same\"\n if (file_metadata_ == item_file_metadata_)\n else (\n \"newer\"\n if remote_mtime > local_mtime\n else (\"older\" if remote_mtime < local_mtime else \"diff\")\n )\n )\n else:\n remote_file_status = \"no mtime\"\n exists_msg = f\"exists ({remote_file_status})\"\n\n if len(file_recs) > 1:\n raise NotImplementedError(\n f\"Item {item_rec} contains multiple files: {file_recs}\"\n )\n elif file_recs: # there is a file already\n if existing == \"error\":\n # as promised -- not gentle at all!\n raise FileExistsError(exists_msg)\n if existing == \"skip\":\n yield skip_file(exists_msg)\n return\n # Logic below only for overwrite and reupload\n if existing == \"overwrite\":\n if remote_file_status == \"same\":\n yield skip_file(exists_msg)\n return\n elif existing == \"refresh\":\n if not remote_file_status == \"older\":\n yield skip_file(exists_msg)\n return\n elif existing == \"force\":\n pass\n else:\n raise ValueError(\"existing\")\n\n delete_before_upload = f'/item/{item_rec[\"_id\"]}'\n\n yield {\"message\": exists_msg + \" - reuploading\"}\n\n #\n # 4. Extract metadata - delayed since takes time, but is done\n # before actual upload, so we could skip if this fails\n #\n # Extract metadata before actual upload and skip if fails\n # TODO: allow for for non-nwb files to skip this step\n # ad-hoc for dandiset.yaml for now\n if path.name != dandiset_metadata_file:\n yield {\"status\": \"extracting metadata\"}\n try:\n metadata = get_metadata(path)\n except Exception as exc:\n if allow_any_path:\n yield {\"status\": \"failed to extract metadata\"}\n metadata = {}\n else:\n yield skip_file(\"failed to extract metadata: %s\" % str(exc))\n if not file_recs:\n # remove empty item\n yield {\"status\": \"deleting empty item\"}\n client.delete(f'/item/{item_rec[\"_id\"]}')\n yield {\"status\": \"deleted empty item\"}\n return\n\n #\n # ?. Compute checksums and possible other digests (e.g. for s3, ipfs - TODO)\n #\n yield {\"status\": \"digesting\"}\n try:\n # TODO: in theory we could also cache the result, but since it is\n # critical to get correct checksums, safer to just do it all the time.\n # Should typically be faster than upload itself ;-)\n digester = Digester(metadata_digests)\n file_metadata_.update(digester(path))\n except Exception as exc:\n yield skip_file(\"failed to compute digests: %s\" % str(exc))\n return\n\n #\n # 5. Upload file\n #\n # TODO: we could potentially keep new item \"hidden\" until we are\n # done with upload, and only then remove old one and replace with\n # a new one (rename from \"hidden\" name).\n if delete_before_upload:\n yield {\"status\": \"deleting old\"}\n client.delete(delete_before_upload)\n yield {\"status\": \"old deleted\"}\n # create a a new item\n item_rec = ensure_item()\n\n yield {\"status\": \"uploading\"}\n # Upload file to an item\n # XXX TODO progress reporting back to pyout is actually tricky\n # if possible to implement via callback since\n # callback would need to yield somehow from the context here.\n # yoh doesn't see how that could be done yet. In the worst\n # case we would copy uploadFileToItem and _uploadContents\n # and make them into generators to relay progress instead of\n # via callback\n # https://stackoverflow.com/questions/9968592/turn-functions-with-a-callback-into-python-generators\n # has some solutions but all IMHO are abit too complex\n\n for r in generator_from_callback(\n lambda c: client.uploadFileToItem(\n item_rec[\"_id\"], str(path), progressCallback=c\n )\n ):\n upload_perc = 100 * ((r[\"current\"] / r[\"total\"]) if r[\"total\"] else 1.0)\n if girder._DANDI_LOG_GIRDER:\n girder.lgr.debug(\n \"PROGRESS[%s]: done=%d %%done=%s\",\n str(path),\n r[\"current\"],\n upload_perc,\n )\n uploaded_paths[str(path)][\"size\"] = r[\"current\"]\n yield {\"upload\": upload_perc}\n\n # Get uploaded file id\n file_id, current = client.isFileCurrent(\n item_rec[\"_id\"], path.name, path.absolute()\n )\n if not current:\n yield skip_file(\"File on server was unexpectedly changed\")\n return\n\n #\n # 6. Upload metadata\n #\n metadata_ = {}\n for k, v in metadata.items():\n if v in (\"\", None):\n continue # degenerate, why bother\n # XXX TODO: remove this -- it is only temporary, search should handle\n if isinstance(v, str):\n metadata_[k] = v.lower()\n elif isinstance(v, datetime):\n metadata_[k] = ensure_strtime(v)\n # we will add some fields which would help us with deciding to\n # reupload or not\n # .isoformat() would give is8601 representation but I see in girder\n # already\n # session_start_time 1971-01-01 12:00:00+00:00\n # decided to go for .isoformat for internal consistency -- let's see\n file_metadata_[\"uploaded_datetime\"] = ensure_strtime(time.time())\n metadata_.update(file_metadata_)\n metadata_[\"uploaded_size\"] = path_stat.st_size\n metadata_[\"uploaded_mtime\"] = ensure_strtime(path_stat.st_mtime)\n metadata_[\"uploaded_by\"] = \"dandi %s\" % __version__\n # Also store object_id for the file to help identify changes/moves\n try:\n metadata_[\"uploaded_nwb_object_id\"] = get_object_id(str(path))\n except Exception as exc:\n (lgr.debug if allow_any_path else lgr.warning)(\n \"Failed to read object_id: %s\", exc\n )\n\n # #\n # # 7. Also set remote file ctime to match local mtime\n # # since for type \"file\", Resource has no \"updated\" field.\n # # and this could us help to identify changes being done\n # # to the remote file -- if metadata[\"uploaded_mtime\"]\n # # differs\n # yield {\"status\": \"setting remote file timestamp\"}\n # try:\n # client.setResourceTimestamp(\n # file_id, type=\"file\", created=metadata_[\"uploaded_mtime\"]\n # )\n # except girder.gcl.HttpError as exc:\n # if devel_debug:\n # raise\n # response = girder.get_HttpError_response(exc)\n # message = response.get(\"message\", str(exc))\n # yield {\"status\": \"WARNING\", \"message\": message}\n\n # 7. Upload metadata\n yield {\"status\": \"uploading metadata\"}\n client.addMetadataToItem(item_rec[\"_id\"], metadata_)\n yield {\"status\": \"done\"}\n\n except Exception as exc:\n if devel_debug:\n raise\n # Custom formatting for some exceptions we know to extract\n # user-meaningful message\n message = str(exc)\n if isinstance(exc, girder.gcl.HttpError):\n response = girder.get_HttpError_response(exc)\n if \"message\" in response:\n message = response[\"message\"]\n uploaded_paths[str(path)][\"errors\"].append(message)\n yield {\"status\": \"ERROR\", \"message\": message}\n finally:\n process_paths.remove(str(path))\n\n # We will again use pyout to provide a neat table summarizing our progress\n # with upload etc\n import pyout\n from .support import pyout as pyouts\n\n # for the upload speeds we need to provide a custom aggregate\n t0 = time.time()\n\n def upload_agg(*ignored):\n dt = time.time() - t0\n total = sum(v[\"size\"] for v in uploaded_paths.values())\n if not total:\n return \"\"\n speed = total / dt if dt else 0\n return \"%s/s\" % naturalsize(speed)\n\n pyout_style = pyouts.get_style(hide_if_missing=False)\n pyout_style[\"upload\"][\"aggregate\"] = upload_agg\n\n rec_fields = [\"path\", \"size\", \"errors\", \"upload\", \"status\", \"message\"]\n out = pyout.Tabular(style=pyout_style, columns=rec_fields)\n\n with out, client.lock_dandiset(dandiset.identifier):\n for path in paths:\n while len(process_paths) >= 10:\n lgr.log(2, \"Sleep waiting for some paths to finish processing\")\n time.sleep(0.5)\n\n rec = {\"path\": str(path)}\n process_paths.add(str(path))\n\n try:\n relpath = path.absolute().relative_to(dandiset.path)\n\n rec[\"path\"] = str(relpath)\n if devel_debug:\n # DEBUG: do serially\n for v in process_path(path, relpath):\n print(str(v), flush=True)\n else:\n rec[tuple(rec_fields[1:])] = process_path(path, relpath)\n except ValueError as exc:\n if \"does not start with\" in str(exc):\n # if top_path is not the top path for the path\n # Provide more concise specific message without path details\n rec.update(skip_file(\"must be a child of top path\"))\n else:\n rec.update(skip_file(exc))\n out(rec)\n\n # # Provide summary of errors if any recorded\n # # well -- they are also in summary by pyout. So, for now - do not bother\n # # It would be worthwhile if we decide to log also other errors\n # errors = defaultdict(set)\n # for p, v in uploaded_paths.items():\n # for e in v['errors']:\n # errors[e].add(p)\n # if errors:\n # lgr.error(\"Following errors were detected while uploading\")\n # for e, paths in errors.items():\n # lgr.error(\" %s: %d paths\", e, len(paths))\n","sub_path":"dandi/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":22436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"194947538","text":"import sys\n\nT = int(sys.stdin.readline())\n\ndef find_freqs(string):\n freqs = {}\n \n for s in string:\n freqs[s] = freqs.get(s, 0) + 1\n \n return freqs\n\ndef find_diff(string):\n strlen = len(string)\n left = string[0:strlen//2]\n right = string[strlen//2:]\n \n leftf = find_freqs(left)\n rightf = find_freqs(right)\n \n counter = 0\n \n for k, v in rightf.items():\n f = leftf.get(k, 0)\n if v > f:\n counter += v - f\n \n return counter\n\nfor line in sys.stdin:\n line = line.replace('\\n', '')\n if len(line) % 2 != 0:\n print(-1)\n else:\n print(find_diff(line))\n ","sub_path":"hackerrank/python/Anagram.py","file_name":"Anagram.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77290143","text":"#!/usr/bin/python3\n# access github API and print user id\nimport requests\nimport sys\n\nif __name__ == '__main__':\n credentials = (sys.argv[1], sys.argv[2])\n response = requests.get('http://api.github.com/user', auth=credentials)\n try:\n print(response.json()['id'])\n except KeyError:\n print(\"None\")\n","sub_path":"0x11-python-network_1/10-my_github.py","file_name":"10-my_github.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296631144","text":"import csv\nimport os\nimport random\nimport shutil\nimport subprocess\n\nfrom Data import movementDataSample\nfrom Utils import *\n\n\n# Change these paths to your local instances before running\ndropboxDir = '/home/jimmy/Dropbox (MIT)/6_439 Group Project/' # Path to project directory\ncodeDir = '/home/jimmy/Desktop/439GradSports/' # Path to project code\nbaseDir = dropboxDir\n\ndef main():\n\t#extractSpecificMovementData(movementDataSample)\n\t#extractRandomMovementData(637)\n\twriteSpeedCSV()\n\n\ndef extractSpecificMovementData(fnames):\n\tzipDir = os.path.join(dropboxDir, 'Data/nba-movement-data-master/data/')\n\tcsvDir = os.path.join(dropboxDir, 'Data/events/')\n\n\tmovementDataDir = os.path.join(codeDir, 'data/movement/')\n\teventDataDir = os.path.join(codeDir, 'data/events/')\n\n\tos.chdir(zipDir)\n\ttargetFiles = os.listdir(movementDataDir)\n\tprint(targetFiles)\n\n\tfor file in fnames:\n\t\tprint('\\n{}'.format(file))\n\n\t\t# Output of '7z l {filename}' in command line (only way to see filenames inside .7z without extracting)\n\t\tfile_contents = subprocess.check_output(['7z','l',file]).decode('utf-8')\n\t\tgameID = [x[:x.find('.json')] for x in file_contents.split(' ') if (x.find('.json') > 0)][0]\n\n\t\tprint(gameID)\n\t\tif '{}.json'.format(gameID) not in targetFiles:\n\t\t\tos.system('7z x {} -o{}'.format(\n\t\t\t\tfile, movementDataDir))\n\t\t\tprint('{} not found!'.format(os.path.join(movementDataDir, '{}.json'.format(gameID))))\n\t\telse:\n\t\t\tprint('File {} (Game ID {}) is already in the data folder'.format(file, gameID))\n\n\tgameIDs = [x.split('.')[0] for x in os.listdir(movementDataDir)]\n\n\tprint(csvDir)\n\tfor gameID in gameIDs:\n\t\tcsvfname = '{}.csv'.format(gameID)\n\t\tcsvpath = os.path.join(csvDir, csvfname)\n\t\ttry:\n\t\t\tshutil.copy(csvpath, eventDataDir)\n\t\texcept FileNotFoundError:\n\t\t\tprint('File not found: {}'.format(csvpath))\n\n\treturn gameIDs\n\n\ndef extractRandomMovementData(numFiles):\n\tzipDir = os.path.join(baseDir, 'Data/nba-movement-data-master/data/')\n\tcsvDir = os.path.join(baseDir, '/Data/events/')\n\n\tmovementDataDir = os.path.join(codeDir, 'data/movement/')\n\teventDataDir = os.path.join(codeDir, '/data/events/')\n\n\tos.chdir(zipDir)\n\tfileList = os.listdir()\n\n\tfileSubset = random.sample(fileList, numFiles)\n\n\tfor file in fileSubset:\n\t\tos.system('7z x {} -o{}'.format(\n\t\t\tfile, movementDataDir))\n\n\tgameIDs = [x.split('.')[0] for x in os.listdir(movementDataDir)]\n\n\tfor gameID in gameIDs:\n\t\tcsvfname = '{}.csv'.format(gameID)\n\t\ttry:\n\t\t\tshutil.copy(os.path.join(csvDir, csvfname), eventDataDir)\n\t\texcept FileNotFoundError:\n\t\t\tcontinue\n\n\treturn fileSubset, gameIDs\n\n\ndef writeSpeedCSV():\n\tos.chdir(codeDir)\n\tgameIDs = [x.split('.')[0] for x in os.listdir('./data/movement/')] # Combs through every movement data file in data directory\n\toutfile = '/home/jimmy/Desktop/test/3pt_speeds.csv'\n\ti = 0\n\tfor gameID in gameIDs:\n\t\ti+= 1\n\t\tprint(i)\n\t\tprint(gameID)\n\t\tData = readJson(gameID)\n\t\ttry:\n\t\t\tall3pts = get_all_3pt(Data)\n\t\t\tfor shot in all3pts:\n\t\t\t\tshooterID = shot['shooterID']\n\t\t\t\teventID = shot['eventID']\n\t\t\t\tmovement = get_movements(Data, eventID, shooterID)\n\t\t\t\tif movement is None:\n\t\t\t\t\tcontinue\n\n\t\t\t\tt_shot = get_shot_index(movement) # Time in frames from beginning of the event\n\t\t\t\tif t_shot is None:\n\t\t\t\t\tcontinue\n\n\t\t\t\tt_catch = get_catch_index(movement) # Same\n\n\t\t\t\tt_min_before_highest = get_shot_index_old(movement)\n\n\t\t\t\tif t_catch == t_shot:\n\t\t\t\t\tprint('Event {} - Shooter {} caught ball at {} and shot at {}'.format(\n\t\t\t\t\t\teventID, shooterID, t_catch, t_shot))\n\t\t\t\t\tcontinue\n\n\t\t\t\tis_cns = is_catch_and_shoot(movement, shooterID)\n\n\t\t\t\tt_with_ball = (t_shot - t_catch) / 25\n\n\t\t\t\tv_with_ball = shooter_velocity_between_frames(movement, shooterID, t_catch, t_shot)\n\n\t\t\t\tv_before_shot = dict()\n\t\t\t\t# Find average velocity over n secs before shot for n = 0.5, 1, 1.5, ... 5]\n\t\t\t\tfor n in [x / 2.0 for x in range(1, 11)]:\n\t\t\t\t\tv_before_shot[n] = None\n\t\t\t\t\tif n < t_with_ball:\n\t\t\t\t\t\tv_before_shot[n] = shooter_velocity_between_frames(\n\t\t\t\t\t\t\tmovement, shooterID, int(t_shot - 25*n), t_shot)\n\t\t\t\t\t# print('{} - {}'.format(n, v_before_shot[n]))\n\n\n\t\t\t\tv_before_catch = dict()\n\t\t\t\tfor n in [x / 2.0 for x in range(1, 11)]:\n\t\t\t\t\tv_before_catch[n] = None\n\t\t\t\t\tstart_frame = int(t_catch - 25*n)\n\t\t\t\t\tif start_frame > 0:\n\t\t\t\t\t\tv_before_catch[n] = shooter_velocity_between_frames(\n\t\t\t\t\t\t\tmovement, shooterID, start_frame, t_catch)\n\t\t\t\tshot_clock = get_shot_clock_at_frame(Data, eventID, t_shot)\n\t\t\t\trow = list()\n\t\t\t\trow.append(gameID)\n\t\t\t\trow.append(shooterID)\n\t\t\t\trow.append(eventID)\n\t\t\t\trow.append(ishome(Data,eventID,shooterID))\n\t\t\t\trow.append(shooter_angle_at_time(movement,t_shot))\n\t\t\t\trow.append(shooter_xy_at_time(movement,t_shot)[0])\n\t\t\t\trow.append(shooter_xy_at_time(movement,t_shot)[1])\n\t\t\t\trow.append(shot_clock)\n\t\t\t\trow.append(is_cns)\n\t\t\t\trow.append(3*movement[0])\n\t\t\t\trow.append(t_with_ball)\n\t\t\t\trow.append(v_with_ball)\n\t\t\t\trow.append(shooter_dist_at_time(movement,t_shot))\n\t\t\t\trow.append(ball_angle(movement, t_shot))\n\t\t\t\trow.append(shooter_move_angle(movement, shooterID, t_catch, t_shot))\n\t\t\t\trow.append(shooter_move_tobasket(movement,shooterID, t_catch, t_shot))\n\t\t\t\ttry:\n\t\t\t\t\trow.append(closest_defender_dist(movement, t_shot,Data, eventID, shooterID)[0]) \n\t\t\t\texcept:\n\t\t\t\t\trow.append(-100) \n\t\t\t\ttry:\n\t\t\t\t\trow.append(closest_defender_dist(movement, t_shot,Data, eventID, shooterID)[1]) \n\t\t\t\texcept:\n\t\t\t\t\trow.append(-100) \n\t\t\t\ttry:\n\t\t\t\t\trow.append(closest_defender_velocity(movement, t_catch, t_shot,Data, eventID, shooterID)) \n\t\t\t\texcept:\n\t\t\t\t\trow.append(-100) #row.append(closest_defender_dist(movement, t_shot,Data, eventID, shooterID)[1])\n\t\t\t\t#row.append(closest_defender_velocity(movement,t_catch,t_shot, Data, eventID, shooterID))\n\t\t\t\t\n\t\t\t\t#row.append(t_with_ball)\n\t\t\t\t#row.append(v_with_ball)\n\n\t\t\t\t[row.append(v_before_shot[x]) for x in v_before_shot]\n\t\t\t\t[row.append(v_before_catch[x]) for x in v_before_catch]\n\t\t\t\twith open(outfile, 'a+', newline='') as outf:\n\t\t\t\t\twriter = csv.writer(outf)\n\t\t\t\t\twriter.writerow(row)\n\t\texcept:\n\t\t\tpass\nif __name__ == '__main__':\n\tmain()\n","sub_path":"Processing.py","file_name":"Processing.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183312153","text":"from sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, String, DateTime, Boolean\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nimport tornado.web\n\n\nengine = create_engine('mysql+pymysql://fido_test_user:fido_test_user@localhost/fido_test', echo=False)\n\nBase = declarative_base()\n\nclass User(Base):\n __tablename__ = 'users'\n id = Column(Integer, primary_key=True)\n username = Column(String(30), nullable=False)\n first_name = Column(String(30), nullable=False)\n last_name = Column(String(30), nullable=False)\n email = Column(String(75), nullable=False)\n password = Column(String(128), nullable=False)\n\ndef __repr__(self):\n return \"\" % (self.username)\n\nmetadata = Base.metadata\n\ndef create_all():\n metadata.create_all(engine)\n\n \nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/users\", UsersHandler),\n ]\n settings = dict(\n cookie_secret=\"some_long_secret_and_other_settins\"\n )\n tornado.web.Application.__init__(self, handlers, **settings)\n # Have one global connection.\n self.db = scoped_session(sessionmaker(bind=engine))\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n @property\n def db(self):\n return self.application.db\n\n def get_current_user(self):\n user_id = self.get_secure_cookie(\"user\")\n if not user_id: return None\n return self.db.query(User).get(user_id)\n\n\nclass UsersHandler(BaseHandler):\n def get(self):\n user = User(username=\"yashh\", first_name='yassh',\n last_name='good game',email=\"yash888@gmail.com\",\n password=\"some\")\n self.db.add(user)\n self.db.commit()\n users = self.db.query(User).filter_by(username=\"yashh\").all()\n print(users)\n self.write('hello mysql' + str(users[0]))\n\nif __name__ == \"__main__\":\n app = Application()\n create_all()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n","sub_path":"tryit/test_sqlalchemy.py","file_name":"test_sqlalchemy.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"142138712","text":"num = 5\nprint(\"The Number is:\",num)\ndef square(n):\n global num #This num belongs to main frame. Now num=n means that it will use the num of main frame\n n = n*n\n num=n #The value of n is copied in num that exits in Frame:Square\n print(\"The n is:\",n)\n print(\"The num is:\",num) #There is not a complusion to write a return statement\n #The last statement always means Return\nsquare(7)\nprint(\"The num is:\",num)","sub_path":"Session6A.py","file_name":"Session6A.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"399877686","text":"from datetime import datetime\n\nfrom pulsar.api import BadRequest, Http401, PermissionDenied, Http404\n\nfrom sqlalchemy.exc import StatementError\nfrom sqlalchemy.orm import joinedload\n\nfrom lux.core import AuthenticationError, AuthBackend as AuthBackendBase\nfrom lux.utils.crypt import create_uuid\nfrom lux.utils.auth import normalise_email\nfrom lux.utils.data import compact_dict\n\nfrom .rest.user import CreateUserSchema\n\n\nclass AuthBackend(AuthBackendBase):\n \"\"\"Mixin to implement authentication backend based on\n SQLAlchemy models\n \"\"\"\n def on_request(self, request):\n auth = request.get('HTTP_AUTHORIZATION')\n cache = request.cache\n cache.user = self.anonymous()\n if not auth:\n return\n app = request.app\n try:\n try:\n auth_type, key = auth.split(None, 1)\n except ValueError:\n raise BadRequest('Invalid Authorization header') from None\n auth_type = auth_type.lower()\n if auth_type == 'bearer':\n token = self.get_token(request, key)\n if not token:\n raise BadRequest\n request.cache.token = token\n user = token.user\n elif auth_type == 'jwt':\n payload = self.decode_jwt(request, key)\n payload['token'] = key\n user = app.auth.service_user(payload)\n except (Http401, BadRequest, PermissionDenied):\n raise\n except Exception:\n request.app.logger.exception('Could not authorize')\n raise BadRequest from None\n else:\n if user:\n request.cache.user = user\n\n def get_user(self, session, id=None, token_id=None, username=None,\n email=None, auth_key=None, **kw):\n \"\"\"Securely fetch a user by id, username, email or auth key\n\n Returns user or nothing\n \"\"\"\n models = session.models\n if token_id:\n try:\n return models['tokens'].get_one(session, id=token_id).user\n except Http404:\n return None\n if auth_key:\n try:\n reg = models['registrations'].get_one(session, id=auth_key)\n return reg.user if reg.expiry > datetime.now() else None\n except Http404:\n return None\n try:\n return models['users'].get_one(session, **compact_dict(\n id=id, username=username, email=normalise_email(email)\n ))\n except Http404:\n return\n\n def authenticate(self, session, user=None, password=None, **kw):\n if not user:\n user = self.get_user(session, **kw)\n if user and self.crypt_verify(user.password, password):\n return user\n else:\n raise AuthenticationError('Invalid credentials')\n\n def create_user(self, session, **data):\n users = session.models['users']\n data.setdefault('active', True)\n return users.create_one(session, data, CreateUserSchema)\n\n def create_superuser(self, session, **params):\n params['superuser'] = True\n params['active'] = True\n return self.create_user(session, **params)\n\n def create_token(self, request, user, **kwargs):\n \"\"\"Create the token\n \"\"\"\n odm = request.app.odm()\n with odm.begin() as session:\n kwargs['id'] = create_uuid()\n token = odm.token(user=user, **kwargs)\n session.add(token)\n return token\n\n def get_token(self, request, key):\n odm = request.app.odm()\n token = odm.token\n with odm.begin() as session:\n query = session.query(token).options(joinedload(token.user))\n try:\n token = query.get(key)\n except StatementError:\n raise BadRequest from None\n return token\n","sub_path":"lux/ext/auth/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630333904","text":"import subprocess\nimport sys\n\n# from pdb2xyz import pdb2xyz\nfrom Query_V2 import get_coord_from_frag_id_array\nfrom reading_parameters import get_chem_formula\nimport rmsd\nfrom structural_isomers import is_isomer\nfrom isomers import is_isomer as is_stereo_isomer\nfrom helpers import get_zmat_filename\nfrom xyz2zmat_babel import xyz2zmat\n\n\nGROUP = 'Slipchenko'\nPASSWORD = 'Terri'\n\n\ndef usage(cmd):\n # Takes an input.pdb file, converts to input.xyz and looks for isomers\n print(\"\"\"\nTakes an input.xyz file and looks for isomers\n\nSyntax: python execute_all_scripts.py input.xyz\n\"\"\")\n\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n in_out = []\n if len(args) == 0:\n print('You need to specify at least one input file (.xyz)')\n usage(sys.argv[0])\n sys.exit(1)\n\n xyz_filename = args[0]\n if not xyz_filename.endswith('.xyz'):\n print('Wrong extension in %s' % xyz_filename)\n sys.exit(2)\n \n filename_base = xyz_filename[:-4]\n\n # Step 1: convert pdb to xyz\n #xyz_filename = '{}.xyz'.format(filename_base)\n #print('Writing %s' % xyz_filename)\n #pdb2xyz(pdb_filename, xyz_filename)\n\n zmat_filename = get_zmat_filename(xyz_filename)\n xyz2zmat(xyz_filename, zmat_filename)\n\n # Step 2: Use xyz coordinates to query for efp mysqldb\n formula = get_chem_formula(xyz_filename)\n #formula = \"C1366N373S6O389\"\n # C3724H5700N1026O1102\n #formula = 'H2O1'\n print('formula', formula)\n\n # Step 3: Get fragment coordinates for formula\n coords = get_coord_from_frag_id_array(GROUP, PASSWORD, formula)\n #coords = {6: 'frag_id: 6\\nO 0.0 0.1191094785 0.0\\nH -1.422305967 -0.9451766865 0.0\\nH 1.422305967 -0.9451766865 0.0\\n', 7: 'frag_id: 7\\nO 0.0 0.1191094785 0.0\\nH -1.422305967 -0.9451766865 0.0\\nH 1.422305967 -0.9451766865 0.0\\n'}\n \n # Step 4: Check if each fragment is an isomer\n for frag_id in coords:\n frag_filename = '{}_frag{}.xyz'.format(filename_base, frag_id)\n with open(frag_filename, 'w') as frag_file:\n frag_file.write(coords[frag_id])\n frag_zmat_filename = get_zmat_filename(frag_filename)\n xyz2zmat(frag_filename, frag_zmat_filename)\n\n is_struct_iso = is_isomer(zmat_filename, frag_zmat_filename)\n print('{} and {} are structural isomers: {}'.format(\n zmat_filename, frag_zmat_filename, is_struct_iso))\n\n is_stereo_iso = is_stereo_isomer(zmat_filename, frag_zmat_filename)\n print('{} and {} are stereo isomers: {}'.format(\n zmat_filename, frag_zmat_filename, is_stereo_iso))\n\n if is_struct_iso or is_stereo_iso:\n rmsd_before, rmsd_after = rmsd.calculate_rmsd(frag_filename, xyz_filename)\n print('rmsd_before={}, rmsd_after={}'.format(rmsd_before, rmsd_after))\n\n sys.exit(0)\n\n\n\"\"\"\n\n\n4) you need to split the result of step 3 so you can run it through your isomer search script; \nso you need to compare the xyz coords from step 1 (which is the original xyz frag) to all of\n the results from step 3. \n\n5) You need to make sure that you return the xyz & rmsd value for each fragment found in step 3 \nin a text file that hanjings script can use to visualize; \n\n6) hanjings script will do its thing, and then it will pass back frag_id, so then you need to\n make sure that return_frag_full_parameter(frag_id); \n\"\"\"\n","sub_path":"execute_all_scripts.py","file_name":"execute_all_scripts.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"436204830","text":"import pyautogui as pg\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nimport re\n\nurl = 'https://www.keybr.com/'\ndriver = webdriver.Chrome(\"D:\\\\chromedriver.exe\")\ndriver.get(url)\nsleep(5)\nwebdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()\nsleep(5)\ndef get_type():\n page = driver.page_source\n soup = BeautifulSoup(page,'html.parser')\n tags = soup.find_all(class_='TextInput-item')\n letter_list =[]\n for i in tags:\n letter = i.get_text()\n regex = re.compile('[␣]')\n if (regex.search(letter) == None):\n print(\"appending space\")\n letter_list.append(letter)\n else:\n letter_list.append('space')\n return letter_list\ndef typing(char_set):\n for j in char_set:\n print(\"Clicking: {}\".format(j))\n pg.press(j)\nfor trail in range(1,30):\n chars = get_type()\n typing(chars)","sub_path":"PostLearn/TypeWriter.py","file_name":"TypeWriter.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"415253078","text":"# -*- coding: utf-8 -*-\n'''\nRemarks:\n1) For the print results: refer to file 'Output_Print_Titanic_survival_predict.py'\n2) For related methods: refer to file 'README.md'\n3) For introdution and functions used or unkown before: refer to file 'Description_info.txt'\n'''\n\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport numpy as np\nimport seaborn as sns # Seaborn绘图\nimport matplotlib.pyplot as plt # pyplot绘图\nfrom collections import Counter # 计数器 \nimport time\n\nimport sklearn.preprocessing as sp\nimport sklearn.linear_model as lm\nimport sklearn.model_selection as ms\nimport sklearn.metrics as sm\nimport sklearn.ensemble as se\nimport sklearn.neighbors as sn\nimport sklearn.tree as st\nimport sklearn.svm as SVM\nimport sklearn.neural_network as nn # 神经网络\nfrom sklearn.ensemble import VotingClassifier # \n\nsns.set(style='white')\n\ntime_init = time.time()\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n'''\nLoad data and data initialization\n'''\ntrain = pd.read_csv('./data/train.csv')\ntest = pd.read_csv('./data/test.csv')\nIDtest = test['PassengerId']\n\n\n'''\nOutlier detection\n'''\ndef detect_outliers(df, n ,features):\n '''\n Takes a dataframe df of features and returns a list of the indices\n correspongding to the ovservations containing more than n outliers\n (data is outlier for both n features) accordint to the Tukey method.\n '''\n outlier_indices = []\n # iterate over features(columns)\n for col in features:\n # 1st quartile(25%)\n Q1 = np.percentile(df[col], 25)\n # 3rd quartile(75%)\n Q3 = np.percentile(df[col], 75)\n # IQR\n IQR = Q3 - Q1\n # outlier step\n outlier_step = 1.5 * IQR\n # Indices(list) of outliers for feature col\n outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step)].index\n # append the detected outlier indices for col to the list if outlier idices\n outlier_indices.extend(outlier_list_col)\n # select observations containing more than n outliers for features(data is outlier for both n features)\n outlier_indices = Counter(outlier_indices)\n multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)\n return multiple_outliers \n\n'''\ndata initialization\n'''\n# detect outliers for numerical values features in train data. let n == 2\noutliers_to_drop = detect_outliers(train, 2, ['Age','SibSp','Parch','Fare'])\n# drop outlier: .reset_index(rop=True)--> delete old index and create a new index\ntrain = train.drop(outliers_to_drop, axis=0).reset_index(drop=True)\n# join train and test data. To obtain the same number of features during the categorical conversion\ndataset = pd.concat(objs=[train, test], axis=0, ).reset_index(drop=True)\n# assign missing and null values to np.nan\ndataset = dataset.fillna(np.nan)\n# check for NaN values\nprint('NaN values in dataset:', dataset.isnull().sum(), sep='\\n')\n# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nprint('^^^^^^^^Data set has been initialized!^^^^^^^^^^', '\\n')\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n'''\nFeature Analysis\nFigures about the features are drawn in Jupyter. \n'''\n# Numerical values feature\n# Correlation matrix between numerical features and feature 'Survived'\ncorr_numerical = train[['Survived', 'Age', 'SibSp', 'Parch', 'Fare']].corr()\n\n# .... figures in Jupyter\n\n# Fillna for dataset.Fare with its median value\ndataset['Fare'] = dataset['Fare'].fillna(dataset.Fare.median())\n\n# Fill null and missing values for Embarked with most frequent Embarked\ntrain['Embarked'] = train['Embarked'].fillna('S')\n\n# Extract the first alphabet as the Cabin rank for non-missing: 矢量化方法Series的str属性\ndataset['Cabin'].fillna('X', inplace=True)\ndataset['Cabin'] = dataset.Cabin.str[0]\norder_cabin = dataset['Cabin'].value_counts().index.sort_values()\n# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n'''\nFeature Engineering: details including visualization listed in Jupyter\n'''\n# Label Encode for Sex\nlabel_encoder_Sex = sp.LabelEncoder() # create a label encoder\nlabel_encoder_Sex.fit_transform(dataset['Sex'])\ntrain.Sex = label_encoder_Sex.transform(train['Sex']) # encode for train.Sex: 1-male; 0-female\ndataset.Sex = label_encoder_Sex.transform(dataset['Sex']) # encode for dataset.Sex\n\n# Missing values process for Age\n # Fill ideas : \n # 探究与Age关联性相对较大的特征,如果Age缺失值所在样本的这些强关联性特征与\n # 其他样本存在一致的,则以这些特征一致样本的Age来填充缺失值;\n # 如果均不存在这样的关联性特征一致的样本,则考虑以Age的中值+标准差范围内随机\n # 扰动作为填充值。\n# For the whole dataset: obtain the index of age_null\nage_na_index = dataset[dataset.Age.isnull()].Age.index\n# Research the perhaps correlation with Age among the other features: Sex, SibSp, Parch, Pclass\n# Explore the correlation matrix between these features\nage_corr_features = dataset[['Age', 'Sex', 'SibSp', 'Parch', 'Pclass']].corr()\n# Fill the null and missing values by Age median plus a random error\nage_median = dataset.Age.median()\nage_std = dataset.Age.std()\nn_interp = dataset.Age.isnull().sum()\nrand_age = np.random.randint(age_median - age_std, age_median + age_std, size=n_interp)\n# Fill the null and missing values for Age under different condition\nfor i in age_na_index:\n mask = (dataset.loc[i,'Pclass'] == dataset.Pclass) & (dataset.loc[i,'SibSp'] == dataset.SibSp) # 掩码\n age_pred = dataset.Age[mask].dropna().median()\n if np.isnan(age_pred): # np.isnan(scalar): np.isnan(5): False\n dataset.loc[i,'Age'] = rand_age # df.isnull(): dataframe with values of True of False\n else:\n dataset.loc[i,'Age'] = age_pred\n \n# Rebuid for Name\n# Get list of title from Name\nstr_name_list = [str_name.split(',')[1].split('.')[0].strip() for str_name in dataset['Name']]\n# Restore Name to a new feature Title. Later feature Name should be droped.\ndataset['Title'] = pd.Series(str_name_list)\ndataset['Title'] = dataset['Title'].replace(['Don', 'Rev', 'Dr', 'Mme', 'Ms', 'Major', 'Lady', 'Sir', 'Mlle',\n 'Col', 'Capt', 'the Countess', 'Jonkheer', 'Dona'], 'Unkn')\n# Numerize the catogory : Mr-0, Mrs,Miss-1, Master-2, unkn-3\ntitle_to_num = {'Mr':0, 'Mrs':1, 'Miss':1, 'Master':2, 'Unkn':3}\ndataset['Title'] = dataset['Title'].map(title_to_num) # map映射进行数据转换\n\n# Tilte alreay created, and Name to drop\ndataset = dataset.drop('Name', axis=1) # 指定轴上删除, axis, 多个则['','','']\n\n# Merge for SibSp and Parch\ndataset['Fsize'] = dataset.SibSp + dataset.Parch + 1\n# Cetegorize Fsize to 4 groups: SingleF, SmallF, MediumF, LargeF\ndataset['SingleF'] = dataset['Fsize'].map(lambda i: 1 if i == 1 else 0)\ndataset['SmallF'] = dataset['Fsize'].map(lambda i: 1 if i == 2 else 0)\ndataset['MediumF'] = dataset['Fsize'].map(lambda i: 1 if (i == 3 or i ==4) else 0)\ndataset['LargeF'] = dataset['Fsize'].map(lambda i: 1 if i >=5 else 0)\n\n# Fare Bins Seperate and Skewness Process\nbins = [0, 100, 180, 300, 1000]\nFare_dis = pd.cut(dataset.Fare, bins) # 离散化feature添加到dataset中,后续cabin缺失值处理使用\ndataset['Fare_bins'] = Fare_dis\n# For dataset, apply log to Fare to reduce skewness\ndataset['Fare'] = dataset['Fare'].map(lambda x: np.log(x) if x > 0 else 0)\n\n# Cabin Process\n# Fill the missing values for Cabin\n#(300, 1000] --> B, 100% prob\n#(180, 300] --> B,C, 50% prob\n#(100, 180] --> B,C,D,E, 25% prob\n#(0, 100] --> no treatment\ni1 = dataset[dataset.Fare_bins==dataset.Fare_bins.value_counts().index[3]][dataset.Cabin=='X'].index\ni2 = dataset[dataset.Fare_bins==dataset.Fare_bins.value_counts().index[2]][dataset.Cabin=='X'].index\ni3 = datas=dataset[dataset.Fare_bins==dataset.Fare_bins.value_counts().index[1]][dataset.Cabin=='X'].index\n# (300, 1000] --> B, 100% prob\ndataset.loc[i1,'Cabin'] = 'B'\n# (180, 300] --> B,C, 50% prob \n# every i in i2 set its value to random(B, C)\nfor i in i2:\n dataset.loc[i, 'Cabin'] = np.random.choice(['B', 'C'], 1,replace=False,p=[0.5,0.5])[0]\n# (100, 180] --> B,C,D,E, 25% prob\n# every i in i3 set its value to random(B,C,D,E)\nfor i in i3:\n dataset.loc[i, 'Cabin'] = np.random.choice(['B','C','D','E'], 1,replace=False,p=[0.25]*4)[0]\n\n# Ticket Process: Simplify the Ticket by its prefix.\nTicket = []\nfor i in dataset.Ticket:\n str_ = i.replace('.', '').replace('/', '').split(' ')[0]\n if str_.isdigit():\n Ticket.append('X')\n else:\n Ticket.append(str_)\ndataset['Ticket'] = Series(Ticket)\n\n# Dummy matrix for features\n# Just as mentioned above, category features need to be transformed to 0-1 encord. \n# Here pandas.get_dummies method is used\ndataset = pd.get_dummies(dataset, columns=['Embarked'], prefix='Port')\ndataset = pd.get_dummies(dataset, columns=['Pclass'], prefix='Pclass')\ndataset = pd.get_dummies(dataset, columns=['Ticket'], prefix='Ticket')\ndataset = pd.get_dummies(dataset, columns=['Cabin'], prefix='Cabin')\ndataset = pd.get_dummies(dataset, columns=['Title'], prefix='Title')\n\n# Delete the non-necessary features: \n# df.drop([...], axis=.., inplace=True)\ndataset.drop(['PassengerId','Fare_bins'], axis=1, inplace=True)\n# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n'''\nModel train\n'''\nprint('\\n')\nprint('~~~~~~~~~~~~~~data sets~~~~~~~~~~~~~~')\n# Train and test dataset\n# train dataset\ntrain = dataset.iloc[: len(train), :]\n# real input and real output \ntrain_x = train.drop('Survived', axis=1)\ntrain_y = train['Survived'].astype(int)\n# test dataset\ntest = dataset.iloc[len(train):, :]\n# test input for predict\ntest_x = test.drop('Survived', axis=1) # Survived is the goal, not included in test dataset \nprint(' train_x.size -->', train_x.size, '\\n', 'test_x.size -->', test_x.size, end='\\n\\n')\n\nprint('~~~~~~~~~~~~~~Model Evaluation~~~~~~~~~~~~~~')\n# Model Evaluation\n# cross_val_score for model of LR -- example\n#val_score_LR = ms.cross_val_score(lm.LogisticRegression(random_state=5), \n# train_x, \n# train_y, \n# cv= 5, \n# scoring='f1_weighted').mean()\n#print('val_score_LR -->', val_score_LR) # 0.81861199090608\n\n'''\nCompare 10 popular algorithm\n'''\nrandom_state = 5\n# Cross validate model with Kfold stratified cross val\nkfold = ms.StratifiedKFold(n_splits=10) # k折交叉切分: 样本分层\n# Modeling evaluation for ten different algorithms\nmodel_svc = SVM.SVC(random_state=random_state)\nmodel_lr = lm.LogisticRegression(random_state=random_state)\nmodel_dt = st.DecisionTreeClassifier(random_state=random_state)\nmodel_rf = se.RandomForestClassifier(random_state=random_state)\nmodel_adb = se.AdaBoostClassifier(model_dt, random_state=random_state, learning_rate=0.1)\nmodel_ext = st.ExtraTreeClassifier(random_state=random_state) # 极端随机数??\nmodel_gb = se.GradientBoostingClassifier(random_state=random_state)\nmodel_mlp = nn.MLPClassifier(random_state=random_state)\nmodel_knn = sn.KNeighborsClassifier()\n#model_lda = da.LinearDiscriminantAnalysis() # 线性判别分析\n # warning: variables are colliner\nclassifiers = [model_svc,model_lr,model_dt,model_rf,model_adb,\n model_ext,model_gb,model_mlp,model_knn]\n\n# Cross validate to get cross_val_score for models\n# mean and std for cv_results\ncv_results = []\ncv_means = []\ncv_stds = []\nfor classifier in classifiers:\n cv_result = ms.cross_val_score(classifier,\n train_x,\n train_y,\n cv=kfold,\n scoring='accuracy')\n cv_means.append(cv_result.mean())\n cv_stds.append(cv_result.std())\n cv_results.append(cv_result) \n\n# model_xx, cv_mean, cv_std --> DataFrame\nclassifiers_name = ['svc','LR','DecisionTree','RandomForest','AdbBoost',\n 'ExtraTree','GradientBoosting','MLP','KNN']\ncolumns = {'CrossValMean':cv_means,\n 'CrossValStd':cv_stds,\n 'Algorithm': classifiers_name\n }\ncv_frame = DataFrame(columns)\nprint(cv_frame.sort_values('CrossValMean', ascending=False).loc[:,'Algorithm'], end='\\n\\n')\n\ng = sns.barplot(y='Algorithm', x='CrossValMean', \n data=cv_frame,\n palette='coolwarm',\n orient='h',\n **{'xerr':cv_stds}) # 指定 error bar, factorplot不知道如何设置??\n\n#plt.setp(g.get_xticklabels(), rotation=45) # factorplot 设置rotation不是这样的,不知道怎么设置??\ng.set_xlabel('Accuracy') # factorplot ..._ylabels() 复数\ng.set_title('Cross Validation Scores') # titles(..) 复数\n\nprint('~~~~~~~~~~~~~~Hyperparameter for models~~~~~~~~~~~~~~')\ntime_hyp0 = time.time()\nbest_model_dict = {}\n# GridSearchCV: Hyperparameter tunning \n# models: AdbBoost, RandomForest, EXTRATREES , GradientBoosting, SVC\n# AdbBoost:\nDTC = st.DecisionTreeClassifier()\nAdaDTC = se.AdaBoostClassifier(DTC, random_state=random_state)\nAda_params = {'base_estimator__criterion':['gini', 'entropy'], # 元分类器DTC的参数 \n 'base_estimator__splitter':['best', 'random'], # 同上 1 2 均不能少\n 'algorithm': ['SAMME', 'SAMME.R'], # SAMME.R--default\n 'n_estimators': [10, 20], # default:50 (决策树的个数)\n 'learning_rate': [0.001, 0.003, 0.1, 0.3, 1, 1.5]}\n# note: 对于元分类器base_estimator中的超参数,应该在参数前加上 base_estimator__\n# 构建超参数模型\nmodel_Ada_gsCV = ms.GridSearchCV(AdaDTC, # estimator\n param_grid=Ada_params, # hyper params\n cv=kfold, # k折交叉切分: 样本分层\n verbose=1, # Controls the verbosity: the higher, the more messages.\n scoring='accuracy', # accuracy, f1, precision, recall, r2...\n return_train_score=True,\n refit=True)\nmodel_Ada_gsCV.fit(train_x, train_y)\n# 获取最优:best_params_, best_score_, best_estimator_, best_index_, ..\nbest_model_Ada = model_Ada_gsCV.best_estimator_\nbest_model_dict['AdaBoost'] = best_model_Ada\nbest_score_Ada = model_Ada_gsCV.best_score_\nbest_params_Ada = model_Ada_gsCV.best_params_\n#print(best_score_Ada) # 0.8172531214528944\n\n# RandomForeset\nRFC = se.RandomForestClassifier()\nRFC_params = {'max_features':[1, 3, 10], # \n 'min_samples_split': [2, 5, 10], # 内部节点再划分所需最小样本数\n 'min_samples_leaf': [1, 5], # 叶子节点的最少样本数,低于会被剪枝\n 'n_estimators': [100, 300] # 子树的数量\n }\nmodel_RFC_gsCV = ms.GridSearchCV(RFC, \n RFC_params,\n cv=kfold,\n scoring='accuracy',\n verbose=1)\nmodel_RFC_gsCV.fit(train_x, train_y)\n# 获取最优:best_params_, best_score_, best_estimator_, best_index_, ..\nbest_model_RFC = model_RFC_gsCV.best_estimator_\nbest_model_dict['RandomForest'] = best_model_RFC\nbest_score_RFC = model_RFC_gsCV.best_score_\n#print(best_score_RFC, model_RFC_gsCV.best_params_)\n#Fitting 10 folds for each of 36 candidates, totalling 360 fits\n#[Parallel(n_jobs=1)]: Done 360 out of 360 | elapsed: 7.8min finished\n#0.8354143019296254 \n#{'max_features': 10, 'min_samples_leaf': 5, 'min_samples_split': 5, 'n_estimators': 100}\n\n# EXTRATREES\nExTC = st.ExtraTreeClassifier()\nExTC_params = {'max_features':[1, 3, 10], # \n 'min_samples_split': [2, 5, 10], # 内部节点再划分所需最小样本数\n 'min_samples_leaf': [1, 5] # 叶子节点的最少样本数,低于会被剪枝\n }\nmodel_ExTC_gsCV = ms.GridSearchCV(ExTC,\n ExTC_params,\n cv=kfold,\n scoring='accuracy',\n verbose=1)\nmodel_ExTC_gsCV.fit(train_x, train_y)\n# best model, params, scores\nbest_model_ExTC = model_ExTC_gsCV.best_estimator_\nbest_model_dict['ExtraTress'] = best_model_ExTC\n#print(model_ExTC_gsCV.best_score_)\n\n# GradientBoosting\nGBC = se.GradientBoostingClassifier()\nGBC_params = {'loss':['deviance'], \n 'max_depth':[4, 8], \n 'min_samples_leaf': [100, 150], # 叶子节点的最少样本数,低于会被剪枝\n 'n_estimators': [100, 200, 300],\n 'learning_rate': [0.1, 0.05, 0.01],\n 'max_features': [0.3, 0.1] # 节点分裂时参与判断的最大特征数。int为个数,float为所占比重\n }\nmodel_GBC_gsCV = ms.GridSearchCV(GBC,\n GBC_params,\n cv=kfold,\n scoring='accuracy',\n verbose=1)\nmodel_GBC_gsCV.fit(train_x, train_y)\n# best model, params, scores\nbest_model_GBC = model_GBC_gsCV.best_estimator_\nbest_model_dict['GradientBoost'] = best_model_GBC\n#print(model_GBC_gsCV.best_score_)\n\n\n# SVC\nSVC_estimator = SVM.SVC(probability=True) # 若False,则后续无法获得prob属性和方法\nSVC_estimator_params = {'kernel': ['rbf'], # rbf 径向基核函数 升维变换 \n 'C': [1, 10, 100, 100], # 正则强度 or 惩罚系数\n 'gamma':[1, 0.1, 0.01, 0.001]} # 核函数系数 default=1/n_features\nmodel_SVC_gsCV = ms.GridSearchCV(SVC_estimator,\n SVC_estimator_params,\n cv=kfold,\n scoring='accuracy',\n refit=True, return_train_score=True,\n verbose=1)\nmodel_SVC_gsCV.fit(train_x, train_y)\n# best model, params, scores\nbest_model_SVC = model_SVC_gsCV.best_estimator_\nbest_model_dict['SVC'] = best_model_SVC\n#print(model_SVC_gsCV.best_score_)\n\ntime_hyp1 = time.time()\ntime_pass_hyp = time_hyp1- time_hyp0\nprint('Process of Hyperparameter has taken up {:.3f} seconds in all.'.format(time_pass_hyp), end='\\n\\n')\n\nprint('~~~~~~~~~~~~~Prams training for best_models: Learning Curve~~~~~~~~~~~')\n# Learning Curve: train_size (After chosing the best models)\n# It can be used to \n# 1) detemine if the model is overfitted by train line and test line overlap degree\n# 2) detemine the suitable train_sizes\ndef plot_learning_curve(estimator, x, y, title, cv=None, train_sizes=np.linspace(0.1,1.0,5)):\n '''\n plot learning curve: score vs train_sizes\n If the dtype is float, train_sizes is regarded as a\n fraction of the maximum size of the training set (that is determined\n by the selected validation method)\n '''\n start_time = time.time()\n # obtain the train_sizes, train and test scores by ms.learning_curve\n train_sizes, train_scores, test_scores = ms.learning_curve(estimator,\n x,\n y,\n train_sizes=train_sizes,\n cv=cv)\n # mean and std of train_score\n train_scores_mean = train_scores.mean(axis=1)\n train_scores_std = train_scores.std(axis=1)\n # mean and std of test_score\n test_scores_mean = test_scores.mean(axis=1)\n test_scores_std = test_scores.std(axis=1)\n\n # figure plot\n plt.figure(facecolor='lightgray')\n plt.title(title)\n plt.xlabel('Train sizes')\n plt.ylabel('Score')\n # learning curve: fill color between the lower and upper limitation and plot the line\n plt.fill_between(train_sizes,\n train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std,\n color='limegreen', alpha=0.2)\n plt.plot(train_sizes, train_scores_mean, 'o-', color='green', label='Train score')\n plt.fill_between(train_sizes,\n test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std,\n color='lightblue', alpha=0.2)\n plt.plot(train_sizes, test_scores_mean, 'o-', color='blue', label='Test score')\n # plt.legend\n plt.legend(loc='best')\n plt.tight_layout()\n plt.show()\n time_pro = time.time() - start_time\n print('Process of plot {:} has taken up {:.3f} seconds in all.'.format(title, time_pro), end='\\n\\n')\n\n# plot learning curve: train_scores is higher obviously than test_score: overfitted\nfor str_model, best_model in best_model_dict.items():\n plot_learning_curve(best_model, train_x, train_y, \n '{:} learning curve'.format(str_model), \n cv=kfold)\n\n\nprint('~~~~~~~~~~~~~~~~~~~~~~~~~feature importance~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n# define the list(ele:tuple of feature_importance for best_model\n# plot the bar for sorted feature\nfeature_importances = []\nfor str_model, best_model in best_model_dict.items():\n if not best_model == best_model_SVC: # 'SVC' object has no attribute 'feature_importances_'\n feature_importances.append((str_model, best_model, best_model.feature_importances_))\n\n# plot the bar for feature importance: obtain the rank\nnrows = 2\nncols = 2\nprint('Beginning of ploting feature importance figure:')\nfig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex='all', figsize=(16, 16))\ni = 0 # feature_importances list元素遍历indicator\nfor row in np.arange(nrows):\n for col in np.arange(ncols):\n start_time = time.time()\n str_fi = feature_importances[i][0] \n model_fi = feature_importances[i][1]\n fi = feature_importances[i][2]\n # sort the importance value ascending and get the sorted index\n sorted_indice = fi.argsort()[::-1] # feature_importance_ 降序排序\n g = sns.barplot(x=fi[sorted_indice][:35], # x轴 排序后的fi值 cut the top35 features\n y=train_x.columns[sorted_indice][:35], # 排序后的特征 top35\n orient='h', # bar 水平方向\n ax=axes[row][col]) # 子图坐标轴--which subplot\n g.set_xlabel('Relative Importance Value')\n g.tick_params(labelsize=7)\n g.set_title('{:} feature importance'.format(str_fi))\n i += 1\n time_pro = time.time() - start_time\n print('Feature importance figure for {:} has taken up {:.3f} seconds in ll.'.format(str_fi, time_pro), end='\\n\\n')\n g.set_ylabel('Feature')\n\ntime_stop1 = time.time()\ntime_pass1 = time_stop1 - time_init\nprint('From the start to finish ploting fi figure, it has been {:.3f} seconds in total!'.format(time_pass1)) \n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n# Model test and model ensemble\n'''\nModel test:\n'''\nprint('\\n')\n\n# 5种模型的预测结果y组成一个新的dataframe: pred_ensemble_results\npred_ensemble_data = {}\nensemble_estimators = []\nfor str_model, best_model in best_model_dict.items():\n # .predict(x) 模型预测test data的survival情况\n pred_ensemble_data[str_model] = best_model.predict(test_x)\n ensemble_estimators.append((str_model, best_model))\npred_ensemble_results = DataFrame(pred_ensemble_data)\n\n# 5种模型预测结果的相关性, 并plot矩阵图\ncorr_pred_ensmble_results = pred_ensemble_results.corr()\nfig, ax = plt.subplots()\ng = sns.heatmap(corr_pred_ensmble_results, annot=True, ax=ax)\n\n'''\nModel ensemble: --- combine models\n use a voting classifier to combine the predictions from the 5 classifiers\n I preferred to pass the argument \"soft\" to the voting parameter to take \n into account the probability of each vote\n'''\nprint('Ensemble models to form a VotingClassfier model:')\nVoting_Model = VotingClassifier(estimators=ensemble_estimators, # list of (string, estimator) tuple\n voting='soft')\n# Based on Voting model, model fit for train data\nVoting_Model.fit(train_x, train_y)\n# Based on the train data's fitting condition, do model predict for test data\nVoting_Survived = Series(Voting_Model.predict(test_x), name='Survived')\nresults_df = pd.concat([IDtest, Voting_Survived], axis=1)\nresults_df.set_index(['PassengerId'], inplace=True)\n# save to csv file\nresults_df.to_csv('Ensemble_VotingModel_Titanic.csv')\ntime_terminal = time.time()\ntime_all = time_terminal - time_init\nprint('The predict has been finished successfully!')\nprint('All the process has taken up {:.3f} seconds From the start to the end'.format(time_all))","sub_path":"Titanic_survival_predict_vision01.py","file_name":"Titanic_survival_predict_vision01.py","file_ext":"py","file_size_in_byte":25482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246584604","text":"# Copyright 2021, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Mime training loop.\"\"\"\n\nimport time\nimport attr\nimport collections\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\n\nfrom absl import logging\nimport tensorflow_federated as tff\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport os.path\nimport shutil\nimport subprocess\nimport tempfile\n\nfrom dp_ftrl import dp_fedavg\nfrom dp_ftrl import training_loop\nimport mime\n\n@attr.s(eq=False, order=False, frozen=True)\nclass LoadingState(object):\n \"\"\"Structure for state on the server.\n\n Attributes:\n model: A `tff.learning.ModelWeights` instance.\n optimizer_state: A namedtuple of the optimizer variables.\n round_num: The current training round, as a float.\n dp_clip_norm: L2 norm to clip client gradients.\n dp_noise_std: Standard deviation of Gaussian distribution to sample noise\n to add to gradients for differential privacy.\n \"\"\"\n model = attr.ib()\n optimizer_state = attr.ib()\n round_num = attr.ib()\n dp_clip_norm= attr.ib()\n dp_noise_std=attr.ib()\n # This is a float to avoid type incompatibility when calculating learning rate\n # schedules.\n\ndef run(\n iterative_process_private: tff.templates.IterativeProcess,\n iterative_process_public: tff.templates.IterativeProcess,\n client_datasets_fn_private: Callable[[int, int], Tuple[List, int]], # pylint: disable=g-bare-generic\n client_datasets_fn_public: Callable[[int, int], Tuple[List, int]],\n validation_fn: Callable[[Any], Dict[str, float]],\n total_epochs: int,\n total_rounds: int,\n experiment_name: str,\n warmstart_file: Optional[str] = '',\n train_eval_fn: Optional[Callable[[Any], Dict[str, float]]] = None,\n test_fn: Optional[Callable[[Any], Dict[str, float]]] = None,\n root_output_dir: Optional[str] = '/tmp/fed_opt',\n hparam_dict: Optional[Dict[str, Any]] = None,\n rounds_per_eval: Optional[int] = 1,\n rounds_per_checkpoint: Optional[int] = 50,\n rounds_per_train_eval: Optional[int] = 100,\n server_state_epoch_update_fn: Optional[Callable[\n [dp_fedavg.ServerState], dp_fedavg.ServerState]] = None):\n \"\"\"Runs federated training for a given `tff.templates.IterativeProcess`.\n\n We assume that the iterative process has the following functional type\n signatures:\n\n * `initialize`: `( -> S@SERVER)` where `S` represents the server state.\n * `next`: ` -> ` where `S`\n represents the server state, `{B*}` represents the client datasets,\n and `T` represents a python `Mapping` object.\n\n Args:\n iterative_process_private: A private `tff.templates.IterativeProcess`\n instance to run.\n iterative_process_public: A public `tff.templates.IterativeProcess` instance\n to run.\n client_datasets_fn_private: Function accepts integer arguments (the round\n number and the epoch) and returns a tuple of a list of private client\n datasets to use as data data for that round, and the updated epoch index.\n client_datasets_fn_public: Function accepts integer arguments (the round\n number and the epoch) and returns a tuple of a list of public client\n datasets to use as data data for that round, and the updated epoch index.\n validation_fn: A callable accepting the `model` attribute of the iterative\n process state and returning a dict of evaluation metrics. Used to compute\n validation metrics throughout the training process.\n total_epochs: Nubmer of total epochs if using `ClientIDShuffler` to shuffle\n clients. Use 0 when sampling clients and control by `total_rounds`.\n total_rounds: The number of federated training rounds to perform. If\n `ClientIDShuffler` is used for `client_datasets_fn`, the total rounds will\n take the minimum of `total_rounds` and rounds_per_epoch*`total_epochs`.\n experiment_name: The name of the experiment being run. This will be appended\n to the `root_output_dir` for purposes of writing outputs.\n warmstart_file: File to checkpoint to start training from\n (typically a warmstarted model).\n train_eval_fn: An optional callable accepting the `model` attribute of the\n iterative process state and returning a dict of evaluation metrics. Used\n to compute training metrics over the entire training dataset throughout\n the course of the iterative process. If set to `None`, no such evaluation\n is done.\n test_fn: An optional callable accepting the `model` attribute of the\n iterative process state and returning a dict of test metrics. Used to\n compute test metrics at the end of the training process.\n root_output_dir: The name of the root output directory for writing\n experiment outputs.\n hparam_dict: An optional dictionary specifying hyperparameters of the\n experiment. If provided, the hyperparameters will be written to CSV.\n rounds_per_eval: How often to compute validation metrics.\n rounds_per_checkpoint: How often to checkpoint the iterative process state.\n If you expect the job to restart frequently, this should be small. If no\n interruptions are expected, this can be made larger.\n rounds_per_train_eval: How often to compute metrics over the entire training\n dataset. Note that this is only done if a `train_eval_fn` argument is\n supplied.\n server_state_epoch_update_fn: A function to update the `SeverState` outside\n of TFF iterative process. It is called at the beginning of each epoch\n traversing all the clients. Used to restart tree for FTRL algorithm.\n\n Returns:\n The final `state` of the iterative process after training.\n \"\"\"\n if not isinstance(iterative_process_private, tff.templates.IterativeProcess):\n raise TypeError('iterative_process_private should be type '\n '`tff.templates.IterativeProcess`.')\n if not isinstance(iterative_process_public, tff.templates.IterativeProcess):\n raise TypeError('iterative_process_public should be type '\n '`tff.templates.IterativeProcess`.')\n if not callable(client_datasets_fn_private):\n raise TypeError('client_datasets_fn_private should be callable.')\n if not callable(client_datasets_fn_public):\n raise TypeError('client_datasets_fn_public should be callable.')\n if not callable(validation_fn):\n raise TypeError('validation_fn should be callable.')\n if train_eval_fn is not None and not callable(train_eval_fn):\n raise TypeError('train_eval_fn should be callable.')\n if test_fn is not None and not callable(test_fn):\n raise TypeError('test_fn should be callable.')\n\n initial_state = iterative_process_private.initialize()\n\n checkpoint_mngr, metrics_mngr, tensorboard_mngr = training_loop._setup_outputs(\n root_output_dir, experiment_name, hparam_dict)\n\n if warmstart_file == '':\n logging.info('Asking checkpoint manager to load checkpoint.')\n state, round_num = checkpoint_mngr.load_latest_checkpoint(initial_state)\n\n else:\n loading_state = LoadingState(\n model=initial_state.model,\n optimizer_state=initial_state.optimizer_state,\n round_num=0,\n dp_clip_norm=initial_state.dp_clip_norm,\n dp_noise_std=initial_state.dp_noise_std)\n logging.info('Asking checkpoint manager to load checkpoint.')\n middle_state, round_num = checkpoint_mngr._load_checkpoint_from_path(\n loading_state,\n warmstart_file)\n\n state = mime_v2.ServerState(\n model = middle_state.model,\n optimizer_state = middle_state.optimizer_state,\n round_num=0,\n dp_clip_norm=initial_state.dp_clip_norm,\n dp_noise_std=initial_state.dp_noise_std,\n mean_full_grad=initial_state.mean_full_grad)\n\n logging.info('Finished loading warmstarted checkpoint from {}'.format(warmstart_file))\n\n epoch = 0\n if state is None or total_epochs > 0:\n state = initial_state\n round_num = 0\n logging.info('Initializing experiment from scratch at round %d.', round_num)\n else:\n logging.info('Restarted from checkpoint round %d', round_num)\n round_num += 1 # Increment to avoid overwriting current checkpoint\n metrics_mngr.clear_metrics(round_num)\n\n loop_start_time = time.time()\n\n logging.info(\"Initial Public Iterative Process to get non-zero mean full grad\")\n federated_train_data_public, epoch = client_datasets_fn_public(round_num, epoch)\n # 2. Update the control variates using the public clients\n state_w_opt = iterative_process_public.next(\n state, federated_train_data_public)\n\n state = tff.structure.update_struct(\n state,\n mean_full_grad = state_w_opt.mean_full_grad)\n\n while epoch <= total_epochs and round_num < total_rounds:\n data_prep_start_time = time.time()\n prev_epoch = epoch\n\n federated_train_data_private, epoch = client_datasets_fn_private(round_num, epoch)\n federated_train_data_public, epoch = client_datasets_fn_public(round_num, epoch)\n\n # Server state is updated outside of TFF iterative process, which is used\n # to restart the tree in DP-FTRL.\n if server_state_epoch_update_fn is not None and epoch == prev_epoch + 1:\n logging.info('External server state update at epoch %d', epoch)\n state = server_state_epoch_update_fn(state)\n\n train_metrics = {\n 'prepare_datasets_secs': time.time() - data_prep_start_time\n }\n training_start_time = time.time()\n\n # 1. Update the model weights using the private clients using the old control variates\n logging.info(\"Private Iterative Process\")\n state_w_weights = iterative_process_private.next(\n state, federated_train_data_private)\n\n logging.info(\"Public Iterative Process\")\n # 2. Update the control variates using the public clients\n state_w_opt = iterative_process_public.next(\n state, federated_train_data_public)\n\n # 3. Merge updates from both states into original state variable\n state = tff.structure.update_struct(\n state,\n model = state_w_weights.model,\n optimizer_state = state_w_opt.optimizer_state,\n mean_full_grad = state_w_opt.mean_full_grad,\n round_num=round_num + tf.cast(1, tf.int32))\n\n train_metrics['training_secs'] = time.time() - training_start_time\n\n logging.info('Round {:2d}, {:.2f}s per round in average.'.format(\n round_num, (time.time() - loop_start_time) / (round_num + 1)))\n\n if (round_num % rounds_per_checkpoint == 0 or\n round_num == total_rounds - 1):\n save_checkpoint_start_time = time.time()\n try:\n checkpoint_mngr.save_checkpoint(state, round_num)\n except Exception: # pylint: disable=broad-except\n logging.info('Checkpoint saving exception: %s', Exception)\n train_metrics['save_checkpoint_secs'] = (\n time.time() - save_checkpoint_start_time)\n\n metrics = {'train': train_metrics}\n\n if train_eval_fn and round_num % rounds_per_train_eval == 0:\n # Compute metrics over the entire training dataset\n train_eval_start = time.time()\n train_eval_metrics = train_eval_fn(state.model)\n train_eval_metrics['evaluate_secs'] = time.time() - train_eval_start\n metrics['train_eval'] = train_eval_metrics\n\n if round_num % rounds_per_eval == 0:\n # Compute validation metrics\n evaluate_start_time = time.time()\n validation_metrics = validation_fn(state.model)\n validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time\n metrics['eval'] = validation_metrics\n training_loop._write_metrics(metrics_mngr, tensorboard_mngr, metrics,\n round_num)\n\n round_num += 1\n\n # Final metrics evaluation once the training has completed\n metrics = {}\n\n # Validation metrics\n evaluate_start_time = time.time()\n validation_metrics = validation_fn(state.model)\n validation_metrics['evaluate_secs'] = time.time() - evaluate_start_time\n metrics['eval'] = validation_metrics\n\n # Training set metrics\n if train_eval_fn:\n train_eval_start = time.time()\n train_eval_metrics = train_eval_fn(state.model)\n train_eval_metrics['evaluate_secs'] = time.time() - train_eval_start\n metrics['train_eval'] = train_eval_metrics\n\n # Test set metrics\n if test_fn:\n test_start_time = time.time()\n test_metrics = test_fn(state.model)\n test_metrics['evaluate_secs'] = time.time() - test_start_time\n metrics['test'] = test_metrics\n training_loop._write_metrics(metrics_mngr, tensorboard_mngr, metrics,\n round_num)\n\n return state\n","sub_path":"mime_loop.py","file_name":"mime_loop.py","file_ext":"py","file_size_in_byte":12966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"453700264","text":"# Python OOP\n\nclass Employee:\n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + '.' + last + '@company.com '\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n\nemp_1 = Employee('fanisa', 'Kim', 20000000)\nemp_2 = Employee('bradley', 'user', 12000000)\n\nprint(emp_1.fullname())\n\nprint(emp_1.email)\nprint(emp_2.email)\n\n'''\nmanually create instance data in Python\n\nemp_1.first = 'Fanisa'\nemp_1.last = 'Kim'\nemp_1.email = 'fanisaK@company.com'\nemp_1.pay = 20000000\n\nemp_2.first = 'Bradley'\nemp_2.last = 'User'\nemp_2.email = 'bradleyU@company.com'\nemp_2.pay = 1200000\n\nprint(emp_1)\nprint(emp_2)\n\n'''\n","sub_path":"PythonOOP/classes&instances.py","file_name":"classes&instances.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"540504545","text":"'''\r\n\r\n Name : Screen Recorder Module\r\n Version : 0.1\r\n Creator : Nitin Choudhury\r\n\r\n Last Back-Up : {\r\n Date : 10-06-2021\r\n Time : 16:29\r\n\r\n }\r\n\r\n'''\r\n\r\n\r\n\r\n\r\n\r\nimport pyautogui\r\nimport cv2\r\nimport numpy as np\r\nimport time\r\nimport pyaudio\r\nimport wave\r\nimport concurrent.futures\r\nimport moviepy.editor as mpe\r\nimport os\r\nimport soundcard as sc\r\n\r\n\r\n\r\nclass Recorder:\r\n\r\n def __init__(self, vid_filename=\"tmp_scn.avi\", ext_aud_filename=\"tmp_aud.wav\", outfile=\"out.avi\"):\r\n self.vid_filename = vid_filename\r\n self.ext_aud_filename = ext_aud_filename\r\n self.outfile = outfile\r\n self.stop_record = False\r\n\r\n def __extract_as_tuple__(self, string):\r\n string = string.split(',')\r\n tup = tuple(int(i) for i in string)\r\n\r\n return tup\r\n\r\n def __extract_filename__(self, file):\r\n ext = file.split('.')[-1]\r\n if ext != 'avi':\r\n file += '.avi'\r\n\r\n return file\r\n\r\n\r\n def screen_record(self, frame_size=(0, 0, pyautogui.size()[0], pyautogui.size()[1]), framerate=9.0, fourcc=cv2.VideoWriter_fourcc(*'XVID')):\r\n\r\n Xs = [0, 5, 6, 10, 0]\r\n Ys = [0, 10, 5, 3, 0]\r\n\r\n if type(frame_size) == str:\r\n frame_size = self.__extract_as_tuple__(frame_size)\r\n\r\n res_tuple = (frame_size[2]-frame_size[0], frame_size[3]-frame_size[1])\r\n filename = self.__extract_filename__(self.vid_filename)\r\n\r\n outVid = cv2.VideoWriter(filename, fourcc, framerate, res_tuple)\r\n init_time = time.time()\r\n while True:\r\n frame = pyautogui.screenshot(region=frame_size)\r\n\r\n mouseX, mouseY = pyautogui.position()\r\n\r\n np_frame = np.array(frame)\r\n np_frame = cv2.cvtColor(np_frame, cv2.COLOR_BGR2RGB)\r\n\r\n Xthis = [2*x+mouseX for x in Xs]\r\n Ythis = [2*y+mouseY for y in Ys]\r\n points = list(zip(Xthis, Ythis))\r\n points = np.array(points, 'int32')\r\n cv2.fillPoly(np_frame, [points], color=[255, 255, 250])\r\n cv2.polylines(np_frame, [points], isClosed=True, color=[0, 0, 0], thickness=1)\r\n\r\n outVid.write(np_frame)\r\n\r\n width = int(pyautogui.size()[0]/2)\r\n height = int(pyautogui.size()[1]/2)\r\n\r\n cv2.namedWindow(\"Screen Recorder\", cv2.WINDOW_NORMAL)\r\n cv2.resizeWindow(\"Screen Recorder\", width, height)\r\n\r\n cv2.imshow(\"Screen Recorder\", np_frame)\r\n\r\n breakKeys = [ord('Q'), ord('q'), 27]\r\n if cv2.waitKey(1) in breakKeys:\r\n break\r\n\r\n self.stop_record = True\r\n end_time = time.time()\r\n\r\n outVid.release()\r\n cv2.destroyAllWindows()\r\n\r\n rec_duration = round(end_time - init_time)\r\n creds = {\r\n \"filename\" : filename,\r\n \"frame_size\" : frame_size,\r\n \"resolution\" : res_tuple,\r\n \"frame_rate\" : framerate,\r\n \"fourcc\" : fourcc,\r\n \"recording_duration\" : rec_duration\r\n }\r\n\r\n return creds\r\n\r\n def record_ext_audio(self, rec_format=pyaudio.paInt16, rec_rate=44100, rec_input=True, rec_frames_per_buffer=1024):\r\n\r\n rec_channels=int(str(sc.default_speaker()).split()[-2].split('(')[-1])\r\n\r\n py_audio = pyaudio.PyAudio()\r\n rec = py_audio.open(format=rec_format, channels=rec_channels, rate=rec_rate, input=rec_input, frames_per_buffer=rec_frames_per_buffer)\r\n\r\n audio_frames = []\r\n\r\n init_time = time.time()\r\n\r\n try:\r\n while (self.stop_record==False):\r\n data = rec.read(rec_frames_per_buffer)\r\n audio_frames.append(data)\r\n\r\n except KeyboardInterrupt:\r\n pass\r\n\r\n rec.stop_stream()\r\n rec.close()\r\n py_audio.terminate()\r\n end_time = time.time()\r\n\r\n rec_time = int(end_time - init_time)\r\n\r\n wf = wave.open(self.ext_aud_filename, 'wb')\r\n wf.setnchannels(rec_channels)\r\n wf.setsampwidth(py_audio.get_sample_size(rec_format))\r\n wf.setframerate(rec_rate)\r\n wf.writeframes(b''.join(audio_frames))\r\n wf.close()\r\n\r\n metadata = {\r\n \"filename\" : self.ext_aud_filename,\r\n \"format\" : rec_format,\r\n \"channel\" : rec_channels,\r\n \"rate\" : rec_rate,\r\n \"input\" : rec_input,\r\n \"frame per buffer\" : rec_frames_per_buffer,\r\n \"recording duration\" : rec_time\r\n }\r\n\r\n return metadata\r\n\r\n\r\n def extAudVidMerger(self):\r\n vid_clip = mpe.VideoFileClip(self.vid_filename)\r\n aud_clip = mpe.AudioFileClip(self.ext_aud_filename)\r\n duration = min(vid_clip.duration, aud_clip.duration)\r\n vid_clip = vid_clip.subclip(0, duration)\r\n aud_clip = aud_clip.subclip(0, duration)\r\n\r\n fin_clip = vid_clip.set_audio(aud_clip)\r\n fin_clip.ipython_display()\r\n\r\n if self.outfile.split('.')[-1] != 'mp4':\r\n self.outfile += '.mp4'\r\n\r\n os.rename('./__temp__.mp4', self.outfile)\r\n\r\n metadata = {\r\n \"filename\" : self.outfile,\r\n \"duration\" : duration\r\n }\r\n\r\n vid_clip.close()\r\n aud_clip.close()\r\n\r\n return metadata\r\n\r\n def clean_env(self):\r\n flag = True\r\n\r\n try:\r\n os.remove(self.vid_filename)\r\n os.remove(self.ext_aud_filename)\r\n\r\n except PermissionError:\r\n flag = False\r\n\r\n return flag\r\n\r\n def rec_ScnExtAud(self):\r\n with concurrent.futures.ThreadPoolExecutor() as executor:\r\n t1 = executor.submit(self.screen_record)\r\n t2 = executor.submit(self.record_ext_audio)\r\n\r\n vid_metadata = t1.result()\r\n aud_metadata = t2.result()\r\n\r\n output_metadata = self.extAudVidMerger()\r\n self.clean_env()\r\n\r\n return vid_metadata, aud_metadata, output_metadata\r\n\r\n\r\nif __name__ == '__main__':\r\n outfile = input(\"ENTER OUTPUT FILENAME {example : Example.mp4} : \")\r\n recorder = Recorder(outfile=outfile)\r\n\r\n vid_metadata, aud_metadata, output_metadata = recorder.rec_ScnExtAud()\r\n print(\"VIDEO METADATA : \", vid_metadata)\r\n print(\"AUDIO METADATA : \", aud_metadata)\r\n print(\"OUTPUT METADATA : \", output_metadata)","sub_path":"modules/recorder_backup.py","file_name":"recorder_backup.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232303584","text":"import util\nfrom mechanize import Browser\nfrom bs4 import BeautifulSoup\nimport re\nimport logging\nimport urlparse\nfrom enum import Enum\nfrom general import General\n\n\nclass BuildingTypes(Enum):\n \"\"\"\n 1. Mina de metal\n 2. Mina de critstal\n 3. Sintetizador de delterio\n 4. Planta de energia solar\n 5. Planta de fusao\n ...\n \"\"\"\n MetalMine = \"1\"\n CrystalMine = \"2\"\n DeuteriumSynthesizer = \"3\"\n SolarPlant = \"4\"\n FusionReactor = \"12\"\n SolarSatellite = \"202\"\n MetalStorage = \"22\"\n CrystalStorage = \"23\"\n DeuteriumTank = \"24\"\n\nclass Building(object):\n def __init__(self, name, level):\n self.name = name\n self.level = level\n\nclass Buildings:\n def __init__(self, browser, universe):\n self.url_provider = util.UrlProvider(universe)\n self.logger = logging.getLogger('ogame-bot')\n self.browser = browser\n self.general_client = General(browser, universe)\n\n def parse_buildings(self, buildings):\n planet_buildings = {}\n count = 0\n for building_type in BuildingTypes:\n planet_buildings[building_type] = Building(buildings[count][0], buildings[count][1])\n count += 1\n return planet_buildings\n\n def get_buildings(self, planet):\n self.logger.info('Getting buildings data')\n url = self.url_provider.get_page_url('resources', planet)\n res = self.browser.open(url)\n soup = BeautifulSoup(res.read(), \"lxml\")\n refs = soup.findAll(\"span\", { \"class\" : \"textlabel\" })\n res = []\n for ref in refs:\n if ref.parent['class'] == ['level']:\n aux = ref.parent.text.replace('\\t','')\n shipData = re.sub(' +', '', aux).encode('utf8')\n res.append( tuple(shipData.split('\\n')))\n\n parsed_res = map(tuple, map(util.sanitize, [filter(None, i) for i in res]))\n buildings = self.parse_buildings(parsed_res)\n return buildings\n\n def auto_build_structure(self, planet):\n if self.construction_mode(planet):\n self.logger.info('Planet is already in construction mode')\n return\n else:\n resources = self.general_client.get_resources(planet)\n buildings = self.get_buildings(planet)\n\n crystal_mine_level = buildings.get(BuildingTypes.CrystalMine).level\n metal_mine_level = buildings.get(BuildingTypes.MetalMine).level\n deuterium_synthesizer_level = buildings.get(BuildingTypes.DeuteriumSynthesizer).level\n metal_storage_level = buildings.get(BuildingTypes.MetalStorage).level\n crystal_storage_level = buildings.get(BuildingTypes.CrystalStorage).level\n deuterium_tank_level = buildings.get(BuildingTypes.DeuteriumTank).level\n\n if resources.energy < 0:\n self.build_structure_item(BuildingTypes.SolarPlant, planet)\n else:\n if crystal_mine_level - metal_mine_level > 2:\n if crystal_storage_level == 0 or crystal_mine_level / crystal_storage_level > 3:\n self.build_structure_item(BuildingTypes.CrystalStorage, planet)\n else:\n self.build_structure_item(BuildingTypes.CrystalMine, planet)\n else:\n if deuterium_synthesizer_level - metal_mine_level > 5:\n if deuterium_tank_level == 0 or deuterium_synthesizer_level / deuterium_tank_level > 3:\n self.build_structure_item(BuildingTypes.DeuteriumTank, planet)\n else:\n self.build_structure_item(BuildingTypes.DeuteriumSynthesizer, planet)\n else:\n if metal_storage_level == 0 or metal_mine_level / metal_storage_level > 3:\n self.build_structure_item(BuildingTypes.MetalStorage, planet)\n else:\n self.build_structure_item(BuildingTypes.MetalMine, planet)\n\n def build_structure(self, type, planet):\n if self.construction_mode(planet):\n self.logger.info('Planet is already in construction mode')\n return\n else:\n self.build_structure_item(type.value, planet)\n\n def build_structure_item(self, type, planet = None):\n self.logger.info('Building %s on planet %s' %(type, planet.name))\n self.browser.select_form(name='form')\n self.browser.form.new_control('text','menge',{'value':'1'})\n self.browser.form.fixup()\n self.browser['menge'] = '1'\n\n self.browser.form.new_control('text','type',{'value': str(type)})\n self.browser.form.fixup()\n self.browser['type'] = str(type)\n\n self.browser.form.new_control('text','modus',{'value':'1'})\n self.browser.form.fixup()\n self.browser['modus'] = '1'\n\n self.logger.info(\"Submitting form\")\n self.browser.submit()\n\n def construction_mode(self, planet = None):\n url = self.url_provider.get_page_url('resources', planet)\n self.logger.info('Opening url %s' % url)\n resp = self.browser.open(url)\n soup = BeautifulSoup(resp.read())\n # if the planet is in construction mode there shoud be a div with the class construction\n return soup.find(\"div\", {\"class\" : \"construction\"}) != None\n","sub_path":"ogbot/scraping/buildings.py","file_name":"buildings.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590128461","text":"#!/usr/bin/python3.4\n\n# Standard import\nimport os\nimport sys\nimport time\nimport argparse\nimport traceback\n\n# Proprietary import\nsys.path.append('../utils/')\nfrom daemonizer import Daemonizer\nfrom threadmanager import ThreadManager\nfrom loggerfactory import LoggerFactory\nimport config\n\n\nd=Daemonizer(config.daemon_socket,config.daemon_signature)\n\n#####################################################\n########### START OF COMMAND LINE PARSING ###########\n#####################################################\n\nparser=argparse.ArgumentParser()\nparser.add_argument('-c',help='Command',required=True,choices=['start','stop','status'])\nargs=parser.parse_args()\n\nif args.c=='start':\n try:\n pid=d.start()\n if pid==0:\n # Children\n pass\n elif pid==-1:\n print(\"Already running with PID \"+d.get_pid())\n sys.exit(0)\n else:\n # Parent\n print('Started with pid '+str(pid))\n sys.exit(0)\n except Exception as exc:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n print(\"Unable to start the daemon: \"+str(exc)+\" - TBINFO:\"+str(traceback.extract_tb(exc_tb)))\n sys.exit(1)\n\nelif args.c=='stop':\n try:\n d.stop()\n except Exception as exc:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n print(\"Unable to stop the daemon:\"+str(exc)+\" - TBINFO:\"+str(traceback.extract_tb(exc_tb)))\n sys.exit(1)\n # Exit from the current process\n sys.exit(0)\n\nelif args.c=='status':\n try:\n running,pid=d.get_pid()\n except Exception as exc:\n print(exc.description)\n sys.exit(1)\n if running:\n print('Running, pid '+pid)\n else:\n print('Not running')\n sys.exit(0)\n\n############## END OF COMMAND LINE PARSING ###########\n## We get here only if we just have been daemonized ##\n######################################################\n\nlog=LoggerFactory.get_file_logger(config.log_filename,\"MAIN\",config.log_level)\nlog.critical(\"STARTING\")\n\ntm=ThreadManager()\ntry:\n tm.init_threads()\n tm.start_all()\nexcept Exception as exc:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n log.critical(\"EXCEPTION WHILE INITIALIZING THREAD. TERMINATING.\"+str(traceback.extract_tb(exc_tb)))\n d.sigterm_handler=tm.stop_all\n d.stop()\n sys.exit(1)\n\nd.sigterm_handler=tm.stop_all\n\nwhile True:\n time.sleep(60)\n\n","sub_path":"solarplant/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143645155","text":"__author__ = 'allen'\n\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom binascii import a2b_hex\nfrom binascii import b2a_hex\nfrom struct import pack\nfrom struct import unpack\n\ndef bxor(b1, b2): # use xor for bytes\n result = bytearray()\n for b1, b2 in zip(b1, b2):\n result.append(b1 ^ b2)\n return bytes(result)\n\ndef encrypt(key, pt, mode):\n rfd = Random.new()\n key = a2b_hex(key)\n cipher = AES.new(key, AES.MODE_ECB)\n pt.encode('utf-8')\n if mode == 'CBC':\n dummy_len = 16 - (len(pt) % 16)\n for i in range(dummy_len):\n pt += chr(dummy_len)\n\n iv = rfd.read(16)\n ct = b2a_hex(iv)\n prev_block = iv\n for i in range(len(pt)//16):\n block = pt[i*16:i*16+16]\n block = bxor(bytes(block, encoding='utf-8'), prev_block)\n enc = cipher.encrypt(block)\n ct += b2a_hex(enc)\n prev_block = enc\n return ct\n\n if mode == 'CTR':\n iv = rfd.read(16)\n inc = unpack('B', iv[15:16])\n ct = b2a_hex(iv)\n for i in range(len(pt)//16+1):\n iv_packed = iv[:15]+pack('B', inc[0]+i)\n ct += b2a_hex(bxor(cipher.encrypt(iv_packed), bytes(pt[i*16:i*16+16], encoding='utf-8')))\n return ct\n\ndef decrypt(key, ct, mode):\n key = a2b_hex(key)\n cipher = AES.new(key, AES.MODE_ECB)\n ct = a2b_hex(ct)\n pt = bytes()\n if mode == 'CBC':\n prev_block = ct[:16]\n for i in range(1, len(ct)//16):\n block = ct[i*16:i*16+16]\n dec = cipher.decrypt(block)\n pt += bxor(dec, prev_block)\n prev_block = block\n\n pt = pt[:-ord(pt[-1:].decode('utf-8'))]\n pt = pt.decode('utf-8')\n return pt\n if mode == 'CTR':\n inc = unpack('B', ct[15:16])\n print(ct[:16])\n for i in range(1, len(ct)//16+1):\n iv_packed = ct[:15]+pack('B', inc[0]+i-1)\n pt += bxor(cipher.encrypt(iv_packed), ct[i*16:i*16+16])\n return pt\n\n\nprint(encrypt('140b41b22a29beb4061bda66b6747e14',\n 'Basic CBC mode encryption needs padding.',\n 'CBC'))\nprint(decrypt('36f18357be4dbd77f050515c73fcf9f2',\n '770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa0e311bde9d4e01726d3184c34451',\n 'CTR'))\nprint(encrypt('36f18357be4dbd77f050515c73fcf9f2',\n 'Always avoid the two time pad!',\n 'CTR'))\n\n#CTR examples\n#140b41b22a29beb4061bda66b6747e14\n#4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81\n#b'L\\xa0\\x0f\\xf4\\xc8\\x98\\xd6\\x1e\\x1e\\xdb\\xf1\\x80\\x06\\x18\\xfb('\n\n#36f18357be4dbd77f050515c73fcf9f2\n#770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa0e311bde9d4e01726d3184c34451\n#b'w\\x0b\\x80%\\x9e\\xc3;\\xeb%a5\\x8a\\x9f-\\xc6\\x17'","sub_path":"Cryptography/2 week/pa2.py","file_name":"pa2.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356191216","text":"#!/usr/bin/env python\n\"\"\"\nTransforms cmd_vel to differential mode for a real robot that uses pololu\n\"\"\"\nimport rospy\nfrom geometry_msgs.msg import Twist, Vector3\n\n\ndef update_cmd(msg):\n L = 400.\n om = msg.angular.z\n v = 6000 - 200. * msg.linear.x\n vd = v + om * L / 2.0\n vg = v - om * L / 2.0\n cmd = Vector3()\n cmd.x = vd\n cmd.y = vg\n cmd_pub.publish(cmd)\n\n\nrospy.init_node('differential')\ndist_sub = rospy.Subscriber('cmd_vel', Twist, update_cmd)\ncmd_pub = rospy.Publisher('cmd_diff', Vector3, queue_size=1)\nrospy.spin()\n","sub_path":"ros_ws/src/actuators/nodes/differential_catamaran.py","file_name":"differential_catamaran.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455624051","text":"import numpy as np\nfrom ._analyzedisp import AnalyzeDisp\nimport scipy.interpolate as itp\nimport scipy.optimize as optm\nimport scipy.fftpack as fft\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nimport subprocess as sub\nimport os\nimport inspect\nfrom copy import copy\nimport pickle as pkl\nimport shutil\nimport tempfile\nfrom prettytable import PrettyTable\nimport warnings\nimport matplotlib as mpl\nimport matplotlib.gridspec as gridspec\nfrom matplotlib import ticker\nimport matplotlib.font_manager as font_manager\nfrom datetime import datetime\nfrom plotly import tools\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport plotly.graph_objs as go\n\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n import h5py\n\nimport ipdb\n\n\nbackend = mpl.get_backend()\npath_juliaScript = os.path.dirname(os.path.abspath(__file__))\npath_juliaScript = os.path.join(path_juliaScript, 'ComputeLLE.jl')\ntmp_dir = tempfile.mkdtemp()\nos.rmdir(tmp_dir) # delete folder as the temp file will not be in it but will be used as a prefix\n# print('-'*50)\n# print('Path to temporary dir to save .h5 files with prefix:')\n# print(tmp_dir)\n# print('-'*50)\n# print('Path to Julia script: ')\n# print(path_juliaScript)\n# print('-'*50)\n\n\n\n# Check which type of python we are launching\n\ntry:\n className = get_ipython().__class__.__name__\n if className == 'ZMQInteractiveShell':\n pyType = 'jupyter'\n elif className == 'TerminalInteractiveShell':\n pyType = 'ipython'\nexcept:\n # launching trhough a normal python\n pyType = 'normal'\n\n# print(pyType)\n\n\nclass MyLogger():\n '''\n Custom made logger as the logger default package cannot be pickled\n '''\n\n def __init__(self, fname):\n self.fname = fname\n open(self.fname,'a').write('\\n' + '-'*75 + '\\n')\n\n def info(self, method, message):\n time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n mess = '[ ' + time + ' - ' + method + ' ] ' + message + '\\n'\n open(self.fname,'a').write(mess)\n\nclass Latexify():\n '''\n Class that handle saving the figures in a nice way compatible with\n the column/page size of different latex template\n\n input [] = optional:\n - figname = name to save the figure (without extension)\n -\n - fig = matplotlib handle to the figure\n - [fig_width]: default = 1column\n - [frmt]: default = pdf\n - [fig_height] : default = 6.5\n - [font_size] : default = 8\n '''\n __author__ = \"Gregory Moille\"\n __copyright__ = \"Copyright 2018, NIST\"\n __credits__ = [\"Gregory Moille\",\n \"Kartik Srinivasan\"]\n __license__ = \"GPL\"\n __version__ = \"2.0.1\"\n __maintainer__ = \"Gregory Moille\"\n __email__ = \"gregory.moille@nist.gov\"\n __status__ = \"Development\"\n\n def __init__(self, **kwarg):\n # get parameters\n figname = kwarg.get('figname', '')\n fig = kwarg.get('fig', None)\n fig_width = kwarg.get('fig_width', '1column')\n self.frmt = kwarg.get('frmt', 'pdf')\n self.fig_height = kwarg.get('fig_height', 6.5)\n self.font_size = kwarg.get('font_size', 8)\n if isinstance(fig_width, str):\n if fig_width.lower() == '1column':\n self.fig_width = 8.6\n elif fig_width.lower() == '2column':\n self.fig_width = 14\n if fig_width.lower() == '1columnbeamer':\n self.fig_width = 10.79846 / 2\n if not kwarg.get('fig_height', False):\n self.fig_height = 6.5 * 10.79846 / 24\n if fig_width.lower() == '2columnbeamer':\n self.fig_width = 10.79846\n if not kwarg.get('fig_height', False):\n self.fig_height = 6.5 * 10.79846 / 14\n else:\n self.fig_width = fig_width\n\n inch = 2.54\n self.fig_width = self.fig_width / inch\n self.fig_height = self.fig_height / inch\n self.f = fig\n self.figname = figname\n self.SavePlot()\n\n def SavePlot(self):\n # -- Define Font Properties --\n # -----------------------------------------------------\n # fontpath = '/System/Library/Fonts'\n font_prop = font_manager.FontProperties(size=8)\n plt.ion()\n # -- Define Param of Plot --\n # -----------------------------------------------------\n params = {'backend': 'ps',\n 'text.latex.preamble': [r'\\usepackage{gensymb}',\n r'\\usepackage{siunitx}',\n r'\\sisetup{detect-all}',\n r'\\usepackage{helvet}',\n r'\\usepackage{sansmath}',\n r'\\sansmath', ],\n 'text.latex.unicode': False,\n # fontsize for x and y labels(was 10)\n 'axes.labelsize': self.font_size,\n 'axes.titlesize': self.font_size,\n 'axes.linewidth': 0.5,\n 'xtick.major.width': 1,\n 'xtick.minor.width': 1,\n 'ytick.major.width': 1,\n 'ytick.minor.width': 1,\n 'legend.fontsize': self.font_size, # was 10\n 'xtick.labelsize': self.font_size,\n 'ytick.labelsize': self.font_size,\n 'text.usetex': False,\n 'figure.figsize': [self.fig_width, self.fig_height],\n # 'font.family': 'sans-serif',\n 'font.size': self.font_size,\n 'lines.linewidth': 0.25,\n }\n mpl.rcParams.update(params)\n\n plt.pause(0.1)\n self.f.set_facecolor('None')\n # -- Redo Font --\n # -----------------------------------------------------\n for ax in self.f.axes:\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n\n for line in ax.yaxis.get_ticklines():\n line.set_markeredgewidth(0.25)\n line.set_markersize(3)\n plt.tick_params(which='minor', length=2, width=0.25)\n\n for line in ax.xaxis.get_ticklines():\n line.set_markeredgewidth(0.25)\n line.set_markersize(3)\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(self.font_size)\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(self.font_size)\n for axis in ['top', 'bottom', 'left', 'right']:\n ax.spines[axis].set_visible(True)\n ax.spines[axis].set_edgecolor('k')\n ax.spines[axis].set_linewidth(0.25)\n ax.axesPatch.set_facecolor('None')\n\n # ax.grid('off')\n xstr = ax.get_xlabel()\n ax.set_xlabel(xstr, size=self.font_size)\n ystr = ax.get_ylabel()\n ax.set_ylabel(ystr, size=self.font_size)\n leg = ax.axes.get_legend()\n # Check if ther is a legend\n # ----------------------------------------\n if leg:\n txt = leg.properties()['texts']\n lbl_lines = leg.properties()['lines']\n for ii in txt:\n ii.set_fontsize(self.font_size)\n for ii in lbl_lines:\n ii.set_linewidth(0.25)\n #change linestyle for line2D\n for ch in ax.get_children():\n if type(ch) == mpl.lines.Line2D:\n ch.set_linewidth(0.25)\n ch.set_markersize(2)\n ch.set_markeredgewidth(4)\n ch.set_markeredgecolor('None')\n # -- Update plot --\n # -----------------------------------------------------\n self.f.set_size_inches(self.fig_width, self.fig_height)\n self.f.canvas.draw()\n plt.draw()\n plt.pause(0.05)\n if not self.figname == '':\n self.f.savefig(self.figname + '.' + self.frmt, format = self.frmt)\n plt.pause(0.05)\n self.GoBackToNormal()\n plt.ioff()\n\n def GoBackToNormal(self):\n file = mpl.get_data_path() + '/matplotlibrc'\n mpl.rcParams.update(mpl.rc_params_from_file(\n file))\n self.f.canvas.draw()\n\nclass LLEsolver(object):\n '''\n Class to solve the Lugiato Lefever Equation\n Initialization input ([]=facultative):\n\n **res **\n\n - Qi : intrinsic Q of the resonator\n - Qc : coupling Q of the resonator\n - R : ring radius\n - gamma : Non linear index of the material\n - dispfile : str pointing to a .csv file where the azimuthal mode orders and corresponding resonances are saved\n\n **sim **\n\n - Tscan : length of the simulation (in unit of round trip)\n - mu_fit : number of mode to fit\n - mu_sim : number of mode to simulate\n - domega_init : initial detuning of the pump\n - domega_end : final detuning of the pump\n - [domga_stop] : where to stop the scan in detuning but keep doing the simulation\n\n **debug **: Save a trace in a logfile in the working directory of the different actions pyLLE perform (default = True)\n '''\n _c0 = 299792458\n hbar = 6.634e-34/(2*np.pi)\n __author__ = \"Gregory Moille\"\n __copyright__ = \"Copyright 2018, NIST\"\n __credits__ = [\"Gregory Moille\",\n \"Qing Li\",\n \"Xiyuan Lu\",\n \"Kartik Srinivasan\"]\n __license__ = \"GPL\"\n __version__ = \"1.0.0\"\n __maintainer__ = \"Gregory Moille\"\n __email__ = \"gregory.moille@nist.gov\"\n __status__ = \"Development\"\n\n def __init__(self, **kwargs):\n self.res = kwargs.get('res', {})\n self.sim = kwargs.get('sim', {})\n self.sim_norm = kwargs.get('sim_norm', None)\n self._debug = kwargs.get('debug', True)\n self._plotPower = None\n self._plotSpecta = None\n self._indSpectra = 0\n self._plotTime = None\n self._indTime = 0\n\n # find all the needed parameters\n assert 'Qi' in self.res.keys(), 'Please provide Qi'\n assert 'Qc' in self.res.keys(), 'Please provide Qc'\n assert 'R' in self.res.keys(), 'Please provide R'\n assert 'Tscan' in self.sim.keys(), 'Please provide Tscan'\n assert 'dispfile' in self.res.keys(), 'Please provide dispfile'\n\n # -- Setup the Logger ---\n if self._debug:\n self._logger = MyLogger(\"LLE.log\")\n self._logger.info('__init__', 'New LLE')\n else:\n self._logger = None\n\n def _Translator(self,D):\n Dnew = {}\n self._greek ={'α': 'alpha',\n 'β':'beta',\n 'γ': 'gamma',\n 'ω': 'omega',\n 'δ': 'd',\n 'Δ': 'D',\n 'μ': 'mu',\n 'λ': 'lambda',\n 'ε': 'epsilon',\n 'φ': 'phi'}\n for k in D.keys():\n new_k = ''\n for char in list(k):\n if char in list(self._greek.keys()):\n new_k += self._greek[char]\n else:\n new_k += char\n Dnew[new_k] = D[k]\n return Dnew\n\n def Analyze(self, plot=False, f=None, ax=None, label=None, plottype='all', zero_lines = True, mu_sim = None):\n '''\n Call pyLLE.analyzedisp.AnalyzeDisp to get the dispersion of the resonator we want to simulate\n '''\n\n if plot and (not pyType == 'jupyter'):\n if f is None and ax is None:\n f, ax = plt.subplots(dpi=120)\n elif f is None and not(ax is None):\n if not type(ax) is list:\n f = ax.figure\n else:\n f, ax = plt.subplots(dpi=120)\n print('Only 1 subplots supported, created a new figure')\n elif not(f is None) and ax is None:\n ax = f.axes[0]\n else:\n if type(ax) is list:\n f, ax = plt.subplots(dpi=120)\n else:\n f = None\n ax = None\n if not('f_pmp' in self.sim.keys()):\n self.sim['f_pmp'] = self._c0/self.sim['lbd_pmp']\n\n\n ## modification 12/21/2018\n if not type(self.sim['f_pmp'])==list:\n self.sim['f_pmp']= [self.sim['f_pmp']]\n\n do_plot = plot\n\n if self._debug:\n Info = '\\n\\tFilename: {}\\n'.format(self.res['dispfile'])\n for ff in self.sim['f_pmp']:\n Info += '\\tf_pmp: {:.3f} THz'.format(ff*1e-12)\n self._logger.info('LLEsovler.Analyze', \"Analyzing dispersion file\" + Info)\n\n self.sim = self._Translator(self.sim)\n self.res = self._Translator(self.res)\n\n if mu_sim is None:\n μsim = self.sim['mu_sim']\n else:\n μsim = mu_sim\n\n self._analyze = AnalyzeDisp(file=self.res['dispfile'],\n f_center=self.sim['f_pmp'][0], # modification 12/21/2018\n rM_fit=self.sim['mu_fit'],\n rM_sim=μsim,\n R=self.res['R'],\n debug=do_plot,\n f=f,\n ax=ax,\n label=label,\n plottype=plottype,\n zero_lines = zero_lines,\n logger = self._logger,\n pyType = pyType)\n if do_plot and (not pyType == 'jupyter'):\n f.canvas.draw()\n plt.pause(0.25)\n f.show()\n\n PrM_fit, Dint_fit, neff_pmp, ng_pmp, f, ax = self._analyze.GetDint()\n self._PrM_fit = PrM_fit\n self.sim['Dint'] = Dint_fit\n self.res['ng'] = ng_pmp\n self.res['neff'] = neff_pmp\n\n self.disp = {}\n self.disp['freq'] = self._analyze.rf\n self.disp['ng'] = self._analyze.ng\n self.disp['neff'] = self._analyze.neff\n self.disp['D'] = self._analyze.D\n self.disp['Dint'] = self._analyze.Dint\n self.disp['dphi'] = self._analyze.dφ\n self.sim['dphi'] = self._analyze.dφ\n\n if (not pyType == 'jupyter'):\n self.fDint = f\n self.axDint = ax\n return f, ax\n else:\n return f\n\n def Setup(self):\n '''\n Setup the simulation for the Julia back-end.\n Save the two main dictionary self.sim and self.res into a readable hdf5 file for Julia in the temporary location define by the os\n '''\n # -- Make the hdf5 file --\n # ------------------------------------------------------------\n try:\n os.remove(tmp_dir + 'ParamLLEJulia.h5')\n os.remove(tmp_dir + 'ResultsJulia.h5')\n except:\n pass\n\n dic_sim = {'Pin': ('Pin',1e3, 'mW'),\n 'Tscan': ('Tscan',1e-6, 'x1e6 Round Trip'),\n 'f_pmp': ('f_pmp',1e-12, 'THz'),\n 'domega_init': (u'\\u03B4\\u03C9_init',1e-9/(2*np.pi), u'x2\\u03C0 GHz'),\n 'domega_end': (u'\\u03B4\\u03C9_end',1e-9/(2*np.pi), u'x2\\u03C0 GHz'),\n 'mu_sim': (u'\\u03BC_sim',1, ''),\n 'mu_fit': (u'\\u03BC_fit',1, ''),}\n\n dic_res = {'R': ('R',1e6, 'µm'),\n 'Qi': ('Qi',1e-6, 'M'),\n 'Qc': ('Qc',1e-6, 'M'),\n 'gamma': (u'\\u03B3', 1, ''),}\n\n\n if not type(self.sim['f_pmp'][1::]) == list:\n self.sim['f_pmp'] = [self.sim['f_pmp']]\n\n ind_aux = []\n ind_pmp = np.argmin(np.abs(self.disp['freq']- self.sim['f_pmp'][0]))\n # ipdb.set_trace()\n for ii in range(len(self.sim['f_pmp'][1::])):\n dummy = np.argmin(np.abs(self.disp['freq']- self.sim['f_pmp'][ii+1]))\n ind_aux += [ind_pmp - dummy]\n\n if ind_aux == []:\n ind_aux = -1\n self.sim['ind_aux'] = ind_aux\n print(ind_aux)\n\n\n self.sim['debug'] = int(self._debug)\n Info = '-- Solving standard LLE --\\n'\n Info += '\\tSimulation Parameters\\n'\n for k, it in self.res.items():\n if k in dic_res.keys():\n Info +='\\t\\t{} = {:.2f} {}\\n'.format(dic_res[k][0], it*dic_res[k][1],dic_res[k][2])\n\n\n Info += '\\tSimulation Parameters\\n'\n for k, it in self.sim.items():\n if k in dic_sim.keys():\n if type(it) is list:\n try:\n Info += '\\t\\t{} = [{:.2f},{:.2f}] {}\\n'.format(dic_sim[k][0],\n it[0]*dic_sim[k][1],\n it[1]*dic_sim[k][1],\n dic_sim[k][2])\n except:\n Info += '\\t\\t{} = {:.2f} {}\\n'.format(dic_sim[k][0],\n it[0]*dic_sim[k][1],\n dic_sim[k][2])\n else:\n Info +='\\t\\t{} = {:.2f} {}\\n'.format(dic_sim[k][0], it*dic_sim[k][1],dic_sim[k][2])\n\n print(Info)\n if self._debug:\n try:\n self._logger.info('LLEsovler.Setup', Info)\n except:\n Info = ''.join([self._greek[ii] if ii in self._greek.keys() else ii for ii in Info])\n self._logger.info('LLEsovler.Setup', Info)\n\n\n # -- create h5file --\n h5f = h5py.File(tmp_dir + 'ParamLLEJulia.h5', 'w')\n if self._debug:\n self._logger.info('LLEsovler.Setup','Saving parameters in: {}'.format(tmp_dir + 'ParamLLEJulia.h5'))\n\n\n h5f.create_group('sim')\n h5f.create_group('res')\n cnt = 0\n\n for key, it in self.sim.items():\n if not key == 'δω_disp':\n if type(it) is str:\n it = np.string_(it)\n h5f.create_dataset('sim/{}'.format(key), data=[it])\n for key, it in self.res.items():\n if not key == 'δω_disp':\n if type(it) is str:\n it = np.string_(it)\n h5f.create_dataset('res/{}'.format(key), data=[it])\n\n h5f.close()\n\n def SolveTemporal(self, tol = 1e-3, maxiter = 6, step_factor = 0.1):\n '''\n Call Julia to solve the LLE\n '''\n self._solver = 'temporal'\n\n if self._debug:\n self._logger.info('LLEsovler.SolveTemporal','Solving Temporal LLE with Julia....')\n Info = 'tol = {} -- maxiter = {} step_factpr = {}'.format(tol, maxiter, step_factor)\n self._logger.info('LLEsovler.SolveTemporal',Info)\n\n\n hLine = '-'*70\n\n print(hLine)\n\n date = time.localtime()\n date = \"{}-{:0>2}-{:0>2} \".format(date.tm_year,\n date.tm_mon,\n date.tm_mday) +\\\n \"{:0>2}:{:0>2}:{:0>2}\".format(date.tm_hour,\n date.tm_min,\n date.tm_sec)\n start = time.time()\n print(date)\n\n if sys.platform == 'darwin':\n julia = 'julia'\n if sys.platform == 'linux2':\n julia = 'julia'\n if sys.platform == 'win32':\n julia = os.path.expanduser('~') + '\\\\AppData\\\\Local\\\\Julia-0.6.4\\\\bin\\\\julia.exe'\n\n command = [julia, path_juliaScript , tmp_dir, str(tol), str(maxiter), str(step_factor)]\n self.JuliaSolver = sub.Popen(command, stdout=sub.PIPE)\n print('Launching Julia....', end = '')\n line = ''\n len_lin = len(line)\n fname = tmp_dir + 'log.log'\n print(fname)\n conv_err = False\n\n def Pbar(perc, pgrs, tb_up):\n bar_width = 50\n pgrs = '*'*int(np.floor(perc/2))\n width = ' '* (bar_width - len(pgrs))\n perc_str = ' {}%'.format(perc)\n line = 'Computing LLE [' + pgrs + width + ']' + perc_str\n if conv_err:\n line = line + ' /!\\ Convergence issue'\n if self._debug:\n self._logger.info('LLEsovler.SolveTemporal','/!\\ Convergence issue')\n length = len(line)\n return line, length, pgrs, tb_up\n\n\n tb_up = 2\n pgrs = ''\n perc_old = 0\n perc = -1\n\n line = ''\n\n # wait for the solver to actually start\n while not perc == 0:\n try:\n perc = int(open(fname).readlines()[-1].strip())\n except Exception as e:\n pass\n\n print('\\rLaunching Julia: Done')\n perc = -1\n while not perc == 100 and self.JuliaSolver.poll() == None:\n try:\n ll = open(fname).readlines()[-1].strip()\n try:\n perc = int(ll)\n if not perc_old == perc:\n line, length, pgrs, tb_up= Pbar(perc, pgrs, tb_up)\n print('\\r' + line, end = '')\n perc_old = perc\n\n except Exception as e:\n if ll.split()[0] == 'Failed':\n conv_err = True\n except Exception as e:\n pass\n\n time_taken = time.time() - start\n end = time.time()\n hours, rem = divmod(end-start, 3600)\n minutes, seconds = divmod(rem, 60)\n time_taken = \"Simulation Time \" + \\\n \"{:0>2}h:{:0>2}min:{:0>4.1f}s\".format(int(hours),\n int(minutes),\n seconds)\n print('\\n')\n print(time_taken)\n print('-'*70)\n if self._debug:\n self._logger.info('LLEsovler.SolveTemporal', time_taken)\n\n\n def SolveSteadySteate(self):\n '''\n Newton Method to find the root of the steady state equation\n '''\n\n self._solver = 'steady'\n if self._debug:\n self._logger.info('LLEsovler.SolveSteadySteate','Solving Steady State LLE with Python....')\n print('-'*70)\n date = time.localtime()\n date = \"{}-{:0>2}-{:0>2} \".format(date.tm_year,\n date.tm_mon,\n date.tm_mday) +\\\n \"{:0>2}:{:0>2}:{:0>2}\".format(date.tm_hour,\n date.tm_min,\n date.tm_sec)\n start = time.time()\n print(date)\n\n # -- CHeck Parity of the µ --\n μ_sim = copy(self.sim['mu_sim'])\n ind = 0\n if not μ_sim[0] == -μ_sim[1]:\n μ_sim = [-np.max(np.abs(μ_sim)), np.max(np.abs(μ_sim))]\n INFO = 'Not symmetric mode calculation -> switching to it with µ_sim = {}\\n'.format(μ_sim)\n print(INFO)\n if self._debug:\n try:\n self._logger.info('LLEsovler.SolveSteadySteate',INFO)\n except:\n Info = ''.join([self._greek[ii] if ii in self._greek.keys() else ii for ii in Info])\n self._logger.info('LLEsovler.SolveSteadySteate',INFO)\n\n dum = self.Analyze(mu_sim = μ_sim, plot = False, f = None)\n\n\n # -- setting up parameters --\n β2 = self._analyze.β2\n Pin = self.sim['Pin']\n γ = self.res['gamma']\n L = 2*np.pi*self.res['R']\n ω0 = self.sim['f_pmp'][0]*2*np.pi\n Q0 = self.res['Qi']\n Qc = self.res['Qc']\n tR = L*self.res['ng']/self._c0\n α = 1/2 * (ω0/Q0 + ω0/Qc) * tR\n θ = ω0/Qc*tR\n δω = -self.sim['domega']* tR\n\n nlc = -1j*γ*L\n μ = np.arange(μ_sim[0], μ_sim[1]+1)\n pmp_ind = np.where(μ == 0)[0][0]\n ω = μ*2*np.pi/tR + ω0\n ν = ω/(2*np.pi)\n # -- setting up input power --\n Ein = np.zeros(μ.size)\n Ein[pmp_ind] = np.sqrt(Pin) * μ.size\n Ein_couple = np.sqrt(θ)*Ein\n\n # -- Define Initial Guess --\n sech = lambda x: 1/np.cosh(x)\n η = δω/α # need to be fixed\n B0 = np.sqrt(2*η)\n f = np.sqrt(θ* Pin* γ* L/α**3)\n φ0 = np.arccos(np.sqrt(8*η)/np.pi/f)\n τ = np.linspace(-0.5,0.5, μ.size)*tR\n Φ0 = f/η**2 -1j* f/η\n ut0 = np.sqrt(α/γ/L) * (Φ0+ B0 * np.exp(1j*φ0) * sech(B0*np.sqrt(α/(np.abs(β2)*L))*τ))\n Em0 = fft.fftshift(fft.fft(ut0))\n x_init = np.concatenate((Em0.real, -Em0.imag))\n\n # -- Define the Steady State LLE Equation --\n φ = -α + 1j*δω - 1j*self.sim[\"dphi\"]\n Em= lambda xx: xx[0:int(xx.shape[0]/2)] + 1j*xx[int(xx.shape[0]/2)]\n Ut= lambda xx: fft.ifft(Em(xx));\n fm= lambda xx: φ*Em(xx) + nlc*fft.fft(np.abs(Ut(xx))**2*Ut(xx)) + Ein_couple;\n fvec= lambda xx: np.concatenate((fm(xx).real, fm(xx).imag))\n\n # -- Solver the Steady State --\n out = optm.root(fvec, x_init, method='lm', jac=None, tol=1e-20)\n Ering = Em(out.x)/μ.size\n Ewg = Ein/μ.size -Ering*np.sqrt(θ)\n\n self.steady = {'Ering':Ering, 'Ewg':Ewg}\n if not pyType == 'jupyter':\n f, ax = plt.subplots(dpi=120)\n ax.plot(1e-12*ν, 30 + 10*np.log10(np.abs(Ewg)**2), label='Waveguide')\n ax.plot(1e-12*ν, 30 + 10*np.log10(np.abs(Ering)**2), label='Ring')\n ax.legend()\n f.show()\n return f, ax\n\n else:\n trace0 = go.Scatter(x = 1e-12*ν,y = 30 + 10*np.log10(np.abs(Ering)**2),\n mode = 'lines', name='Res. Power')\n trace1 = go.Scatter(x = 1e-12*ν,y = 30 + 10*np.log10(np.abs(Ewg)**2),\n mode = 'lines', name='Out Power')\n data = [trace1, trace0]\n layout = dict(xaxis = dict(title = 'Frequency (THz)'),\n yaxis = dict(title = 'Power (dBm)'),\n )\n fig = go.Figure(data=data, layout=layout)\n iplot(fig)\n return fig\n\n def RetrieveData(self):\n '''\n Load the output hdf5 saved by julia and transform it in a user-friendly dictionary to be more pythonistic\n '''\n\n time.sleep(0.5)\n drct = tmp_dir\n S = h5py.File(tmp_dir + 'ResultsJulia.h5', 'r')\n if self._debug:\n self._logger.info('LLEsovler.RetrieveData','Retrieving results from Julia in {}'.format(tmp_dir + 'ResultsJulia.h5'))\n sol = {}\n keys = ['u_probe','Em_probe', 'Ewg']\n for k in keys:\n rl = 'Results/{}Real'.format(k)\n im = 'Results/{}Imag'.format(k)\n sol[k] = S[rl][:] + 1j*S[im][:]\n sol['ω'] = S['Results/ωReal'][:]\n sol['comb_power'] = S['Results/comb_powerReal'][:]\n sol['detuning'] = S[\"Results/detuningReal\"][:]\n S.close()\n os.remove(tmp_dir + 'ParamLLEJulia.h5')\n os.remove(tmp_dir + 'ResultsJulia.h5')\n sol['freq'] = sol['ω']/(2*np.pi)\n sol['theta'] = np.linspace(-np.pi,np.pi, sol['u_probe'].shape[0])\n self.sol = sol\n\n def PlotCombPower(self, do_matplotlib = False):\n '''\n Plot a figure with 3 subplots.\n\n - Top subplot = map of the spectra for the steps taken by the LLE (step sub-sampled to be 1000)\n - middle subplot = temporal map of the intensity inside the resonator for the steps of the LLE\n - bottom subplot = normalized comb power\n\n **Output**\n\n - f, ax: handle of figure and axes of the matplotlib figure displayed\n '''\n\n\n freq = self.sol['freq']*1e-12\n Epb = self.sol['Ewg']\n Epb[Epb==0] = 1e-20\n Epb = 30 + 10*np.log10(np.abs(Epb)**2)\n\n E2 = (np.abs(self.sol['u_probe'])**2)\n E2 = E2/E2.max()\n tR = 2*np.pi*self.res['R']*self.res['ng']/self._c0\n t = np.linspace(-0.5, 0.5, freq.size) * tR\n\n CmbPow = self.sol['comb_power'] /self.sol['comb_power'].max()\n det = self.sol['detuning']*1e-9/(2*np.pi)\n\n step = np.arange(0, 1000)\n self._plotPower = True\n if not pyType == 'jupyter' or do_matplotlib:\n # -- Create the Figure --\n f = plt.figure()\n gs = gridspec.GridSpec(3,2, width_ratios=[1,0.015],wspace=0.05)\n ax = [None]*6\n ax[0] = plt.subplot(gs[0])\n ax[1] = plt.subplot(gs[1])\n ax[2] = plt.subplot(gs[2],sharex=ax[0])\n ax[3] = plt.subplot(gs[3])\n ax[4] = plt.subplot(gs[4],sharex=ax[0])\n cmap = plt.get_cmap(\"tab10\")\n\n # -- Plot Everything --\n aa = ax[0].pcolormesh(step, freq,Epb,\n rasterized=True,\n vmin = Epb.max()-120,\n vmax = Epb.max())\n\n bb = ax[2].imshow(E2,aspect='auto',\n origin = 'lower',\n interpolation='bessel')\n tr_12 = 1e-12*np.floor(1e12*tR)/2\n # print(np.argmin(np.abs(tr_12- t)))\n ind = [np.argmin(np.abs(-tr_12- t)),\n np.argmin(np.abs(t)),\n np.argmin(np.abs(tr_12- t))]\n ax[2].set_yticks(ind)\n ax[2].set_yticklabels([-tr_12*1e12,\n 0,\n tr_12*1e12])\n\n\n ax[4].plot(step, CmbPow)\n ax.append(ax[4].twinx())\n ax[6].plot(step,det,\n c = cmap.colors[1])\n\n # -- Make it Pretty --\n ax[0].set_ylabel('Frequency (THz)')\n ax[2].set_ylabel('Time (ps)')\n ax[4].set_xlabel('LLE Step (sub-sampled)')\n ax[4].set_ylabel('Norm. Comb Pwr')\n ax[6].set_ylabel('Detuning (GHz)')\n ax[0].set_xlim([0,1000])\n [label.set_visible(False) for label in ax[0].get_xticklabels()]\n [label.set_visible(False) for label in ax[2].get_xticklabels()]\n\n\n bar_spec = f.colorbar(aa,cax = ax[1],orientation=\"vertical\")\n bar_temp = f.colorbar(bb,cax = ax[3],orientation=\"vertical\")\n bar_spec.set_label('Spec. P (dB)')\n bar_temp.set_label('|E|²')\n tick_locator1 = ticker.MaxNLocator(nbins=4)\n tick_locator2 = ticker.MaxNLocator(nbins=2)\n bar_spec.locator = tick_locator1\n bar_temp.locator = tick_locator2\n bar_spec.update_ticks()\n bar_temp.update_ticks()\n\n if not pyType == 'jupyter':\n f.show()\n self.fPcomb = f\n self.axPcomb = ax\n\n return f, ax\n\n else:\n\n Sspec = go.Heatmap(x=step, y=freq, z=Epb,\n colorbar=dict(len=0.37, y=0.83, title='Power (dBm)'),\n yaxis='y3',\n colorscale='Viridis',\n zmax = 0,\n zmin = -120,\n )\n\n Stime = go.Heatmap(x = step, y = t*1e12, z = E2,\n colorbar=dict(len=0.34, y=0.47, title = '|E|^2'),\n yaxis='y2',\n colorscale='Viridis')\n\n Cpwr = go.Scatter(x=step, y=CmbPow,\n yaxis='y1',\n name='Comb Power')\n\n Detuning = go.Scatter(x=step, y=det,\n yaxis='y4',\n name='Detuning')\n\n data = [Cpwr, Detuning, Stime, Sspec]\n layout = go.Layout(\n xaxis=dict(domain=[0, 1],anchor='y1',title= 'LLE Step'),\n xaxis2=dict(domain=[0, 1],anchor='y1',title= 'couocu', ),\n xaxis3=dict(domain=[0, 1],anchor='y1'),\n xaxis4=dict(domain=[0, 1],anchor='y1'),\n yaxis1=dict(domain=[0, 0.29],title = 'Comb Power',),\n yaxis2=dict(domain=[0.33, 0.62],anchor='x1',title = 'Fast Time',),\n yaxis3=dict(domain=[0.66, 1],anchor='x1',title = 'Frequency (THz)',),\n yaxis4=dict(domain=[0.66, 1],anchor='x1',overlaying='y1',title = 'Detuning (GHz)',side='right'),\n showlegend=False,)\n fig = go.Figure(data=data, layout=layout)\n iplot(fig)\n\n return fig\n\n def PlotCombSpectra(self, ind, f=None, ax=None, label=None, pwr='both', do_matplotlib = False, plot = True):\n '''\n Plot the spectra for a given index in the 1000 sub-sampled LLE steps\n\n **Input**\n\n - ind : index in the LLE step to plot the spectra\n - f : matplotlib figure handle (if None, new figure)\n - ax : matplotlib axe handle\n - label : label for the legend\n - pwr : 'both', 'ring', 'wg' depending on the spectra wanted (inside the ring, the waveguide or both)\n\n **Output**\n\n - freq : frequency in Hz\n - Sout : spectral density of power in the waveguide (dBm)\n - Sring : spectral density of power in the ring (dBm)\n - f : matplotlib figure handle\n - ax : matplotlib axes handle\n '''\n\n freq = self.sol['freq']*1e-12\n Sring = 30 + 10*np.log10(np.abs(self.sol['Em_probe'][:, ind])**2)\n Sout = 30 + 10*np.log10(np.abs(self.sol['Ewg'][:, ind])**2)\n self.spectra = {'Sout': Sout,\n 'Sres': Sring,\n 'freq': freq*1e-12}\n\n\n if not pyType == 'jupyter' or do_matplotlib:\n if f is None and ax is None:\n f, ax = plt.subplots(dpi=120)\n elif f is None and not(ax is None):\n if not type(ax) is list:\n f = ax.figure\n else:\n f, ax = plt.subplots(dpi=120)\n print('Only 1 subplots supported, created a new figure')\n elif not(f is None) and ax is None:\n ax = f.axes[0]\n else:\n if type(ax) is list:\n f, ax = plt.subplots(dpi=120)\n\n\n\n if pwr.lower() == 'both':\n ax.plot(freq, Sout, label='Output P')\n ax.plot(freq, Sring, '.', ms=4, label='In ring P')\n if pwr.lower() == 'ring':\n ax.plot(freq, Sring, ms=4, label=label)\n if pwr.lower() == 'wg':\n ax.plot(freq, Sout, label=label)\n\n ax.set_ylabel('Power (dBm)')\n ax.set_xlabel('Frequency (THz)')\n if not(label is None):\n ax.legend()\n if not pyType == 'jupyter':\n f.canvas.draw()\n f.show()\n plt.pause(0.25)\n\n self.fSpectra = f\n self.axSpectra = ax\n\n return f, ax\n else:\n trace0 = go.Scatter(x = freq,y = Sring,\n mode = 'lines',name = 'Res. Power')\n trace1 = go.Scatter(x = freq,y = Sout,\n mode = 'lines',name = 'Wg. Power')\n\n if pwr.lower() == 'both':\n data = [trace1, trace0]\n if pwr.lower() == 'ring':\n data = [trace0]\n if pwr.lower() == 'wg':\n data = [trace1]\n\n layout = dict(xaxis = dict(title = 'Frequency (THz)'),\n yaxis = dict(title = 'Power (dBm)'),\n )\n fig = go.Figure(data=data, layout=layout)\n if plot:\n iplot(fig)\n\n self._plotSpecta = True\n self._indSpectra = ind\n\n\n\n return fig\n\n def PlotSolitonTime(self, ind, f=None, ax=None, label=None, do_matplotlib = False):\n '''\n Plot the spectra for a given index in the 1000 sub-sampled LLE step\n\n **Input**\n\n - ind : index in the LLE step to plot the spectra\n - f : matplotlib figure handle (if None, new figure)\n - ax : matplotlib axe handle\n - label : label for the legend\n\n **Output**\n\n - τ : Time in the resonator\n - U : Temporal Electric field for the given step of the LLE\n - f : matplotlib figure handle\n - ax : matplotlib axe handle\n '''\n\n\n tR = 2*np.pi*self.res['R']*self.res['ng']/self._c0\n freq = self.sol['freq']\n\n τ = np.linspace(-0.5, 0.5, freq.size) * tR\n U = np.abs(self.sol['u_probe'][:,ind])**2\n\n self.fasttime ={'U': U,\n 'tau': τ}\n if not pyType == 'jupyter' or do_matplotlib:\n f, ax = plt.subplots(dpi=120)\n ax.plot(τ*1e12 , U/U.max())\n ax.set_xlabel('Time (ps)')\n ax.set_ylabel('Soliton Energy (a.u)')\n if not pyType == 'jupyter':\n f.show()\n return f, ax\n else:\n trace0 = go.Scatter(x = τ*1e12,y = U,\n mode = 'lines')\n data = [trace0]\n layout = dict(xaxis = dict(title = 'Time (ps)'),\n yaxis = dict(title = '|E|^2 (norm)'),\n )\n fig = go.Figure(data=data, layout=layout)\n iplot(fig)\n\n self._plotTime = True\n self._indTime = ind\n\n def SaveResults(self, fname, path='./'):\n '''\n Save the whole class with pickle to be able to easilly call it back or retrieve the results after saving\n\n **Input**\n\n - fname : name to save. The '.pkl' extension will be added\n - path : path to save the results (defaults './')\n '''\n to_save = copy(self)\n to_save.sim.pop('domega_disp', None)\n to_save.sim.pop('domega_disp', None)\n del to_save.JuliaSolver\n fname = path + fname + '.pkl'\n print(fname)\n pkl.dump(to_save, open(fname,'bw'))\n\n def SavePlots2File(self,basename = './', format = 'pdf'):\n if self._plotPower:\n fpwr, axpwr = self.PlotCombPower(do_matplotlib = True)\n Latexify(figname = basename + 'CombPower', fig = fpwr, frmt = format)\n if self._plotSpecta:\n fspec, axspec = self.PlotCombSpectra(self._indSpectra, do_matplotlib = True)\n Latexify(figname = basename + 'CombSpectra', fig = fspec, frmt = format)\n if self._plotTime:\n ftime, axtome = self.PlotSolitonTime(self._indTime, do_matplotlib = True)\n Latexify(figname = basename + 'FastTime', fig = ftime, frmt = format)\n\n def __repr__(self):\n to_print = ''\n to_print = 'Dispersion load from:\\t{}\\n\\n'.format(self.res['dispfile'])\n to_print += 'Resonator Parameters:\\n'\n res_table = PrettyTable(['Parameters', 'Value', 'Units'])\n res_table.add_row(['R', \"{:.3f}\".format(self.res['R']*1e6),'µm'])\n res_table.add_row(['Qi', \"{:.3f}\".format(self.res['Qi']*1e-6),'x1e6'])\n res_table.add_row(['Qc', \"{:.3f}\".format(self.res['Qc']*1e-6),'x1e6'])\n if 'gamma' in self.res:\n res_table.add_row(['γ', \"{:.3f}\".format(self.res['gamma']),''])\n if 'n2' in self.res:\n res_table.add_row(['n2', \"{:.3f}\".format(self.res['n2']*1e19),'x1e-19 m2/W'])\n to_print += res_table.get_string()\n to_print += '\\n'\n\n to_print += 'Simulation Parameters:\\n'\n sim_table = PrettyTable(['Parameters', 'Value', 'Units'])\n\n if 'Pin' in self.sim:\n sim_table.add_row(['Pin',\"{:.3f}\".format(self.sim['Pin']*1e3),'mW'])\n if 'f_pmp' in self.sim:\n sim_table.add_row(['f_pmp',\"{:.3f}\".format(self.sim['f_pmp']*1e-12),'THz'])\n if 'μ_sim' in self.sim:\n sim_table.add_row(['μ_sim',\"{}\".format(self.sim['mu_sim']),''])\n if 'Tscan' in self.sim:\n sim_table.add_row(['Tscan',\"{:.3f}\".format(self.sim['Tscan']*1e-5),'x1e5 tR'])\n if 'domega_init' in self.sim:\n sim_table.add_row(['δω_init',\"{:.3f}\".format(self.sim['domega_init']*1e-9),'GHz'])\n if 'domega_end' in self.sim:\n sim_table.add_row(['δω_end',\"{:.3f}\".format(self.sim['domega_end']*1e-9),'GHz'])\n to_print += sim_table.get_string()\n to_print += '\\n'\n\n return to_print\n","sub_path":"pyLLE/_llesolver.py","file_name":"_llesolver.py","file_ext":"py","file_size_in_byte":40427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293727471","text":"###There's something wrong with the normal rak811 library for the recently produced set of parts we purchased... supposedly this is an option\n\nimport messages\nimport time\nimport rak811v2\nRak811v2 = rak811v2.Rak811v2\n\n\n## Device address\ndev_addr = 0x02 ## Client\n\n### Destination address\ndest_addr = 0x01 ## Gateway\n\n#### Setting configs\nprint('init')\n\nlora = Rak811v2()\n\nprint('Reset radio')\nlora.hard_reset()\n\nprint('Get version')\nv = lora.version\nprint(v[0])\n\n\nprint('\\nSet configuration modes for LoRa p2p')\nlora.set_config('lora:work_mode:1')\nresp = lora.get_info()\n# print(resp)\nfor x in resp:\n print('\\t',x)\n\n\nprint('\\nSet self as sender mode')\nlora.set_config('lorap2p:transfer_mode:2')\nresp = lora.get_info()\n# print(resp)\nfor x in resp:\n print('\\t',x)\n\n\nprint('\\nSet P2P parameters')\nlora.set_config('lorap2p:915000000:10:0:1:8:16')\nresp = lora.get_info()\nfor x in resp:\n print('\\t',x)\n\n\n#### End of configs\n\n### Messages to transmit\n\ni=1\nwhile True:\n print()\n print('loop iter %d' % i)\n print()\n \n str_to_send = \"Hello World! msg cnt: %d\\r\\n\" % i\n print('Sending \"%s\"' % str_to_send)\n\n message = messages.TXMessage(i, dest_addr, str_to_send)\n tx_bytes = message.get_bytes()\n\n # lora.send_lorap2p(str_to_send)\n lora.send_lorap2p(tx_bytes)\n print('Sent')\n\n time.sleep(30)\n i+=1","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76313064","text":"def prettify_text(text_to_pretty, list_2_subtract, ptrn=''):\n \"\"\"\n This is a function witch clean string from signs of punctuation\n :param text_to_pretty: input string\n :param list_2_subtract: list or tuple sign punctuation witch will substring\n :param ptrn: pattern\n :type text_to_pretty: str\n :type list_2_subtract: list or tuple\n :type ptrn: str\n :return: string\n :rtype: str\n \"\"\"\n for simbol in list_2_subtract:\n text_to_pretty = text_to_pretty.replace(simbol, ptrn).lower()\n\n return text_to_pretty\n\n\ndef prettify_text2(input_str):\n '''\n :param input_str: input text\n :return: list of words\n '''\n list_sign_punctuation = [',', '...', ';', ':', '- ', '(', ')', '\"']\n result = prettify_text(input_str, list_sign_punctuation)\n\n list_sign_punctuation2 = ('.', '?', '!')\n result = prettify_text(result, list_sign_punctuation2, ' ')\n\n list_pretext = [' a ', ' an ', ' to ', ' is ', ' are ', ' was ', ' were ', ' will ', ' would ', ' could ', ' and ',\n ' or ', ' if ', ' he ', ' she ', ' it ', ' this ', ' my ', ' the ', ' on ', ' of ', ' in ', ' no ',\n ' with ', ' but ', ' that ', ' than ', 'the ', 'on ', 'of ', 'with ', 'but ', 'that ', 'than ']\n result = prettify_text(result, list_pretext, ' ')\n\n clean_text_list = result.split(\" \")\n white_space = ''\n while white_space in clean_text_list:\n clean_text_list.remove(white_space)\n\n white_space = '\\n'\n while white_space in clean_text_list:\n clean_text_list.remove(white_space)\n\n return clean_text_list\n\n\ndef create_list_uniq_words(list_a):\n \"\"\"\n This is a function witch create text list with unique words from list_a.\n :param list_a: list words\n :type list_a: list or tuple\n :return: list_c\n :rtype: list\n \"\"\"\n list_c = []\n for element in list_a:\n if element not in list_c:\n list_c.append(element)\n\n return list_c\n\n\ndef count_keywords(list_a, list_b):\n \"\"\"\n This is a function witch count keywords in list and return dictionary with count value .\n :param list_a: list words\n :param list_b: dictionary of key words\n :type list_a: list or tuple\n :type list_b: list or tuple\n :return: dictionary\n :rtype: dict\n \"\"\"\n dict_out = {}\n for val in list_b:\n dict_out[val] = list_a.count(val)\n\n return dict_out\n\n\ndef show_top_keywords(dict_in, top=3):\n \"\"\"\n This is a function witch take dictionary and return only top value.\n :param dict_in: dictionary list words as a key and frequency as value\n :param top: top value\n :type dict_in: dict\n :type top: int\n :return: dictionary\n :rtype: dict\n \"\"\"\n dict_1 = {}\n dict_out = {}\n\n for k in sorted(dict_in, key=dict_in.get, reverse=True):\n dict_1[k] = dict_in[k]\n\n for key, value in dict_1.items():\n if top == 0:\n break\n dict_out[key] = value\n top -= 1\n\n return dict_out\n\n\ndef format_result(input_str):\n \"\"\"\n This is a function witch take input string and return result of text analyze\n in special format.\n :param input_str: input string\n :type input_str: str\n :return: output text\n :rtype: str\n \"\"\"\n\n clean_text_list = prettify_text2(input_str)\n\n words_quantity = len(clean_text_list)\n print(f'- words quantity: {words_quantity}')\n\n uniq_words = create_list_uniq_words(clean_text_list)\n string = ', '.join(uniq_words)\n print(f'- text dictionary: {string}')\n\n count_words = count_keywords(clean_text_list, uniq_words)\n\n top_words = show_top_keywords(count_words, 3)\n\n new_list = [key + ' - ' + str(value) for key, value in top_words.items()]\n string4 = ', '.join(new_list)\n print(f'- keywords: {string4}')\n\n new_list2 = [key + ' - ' + str(int(int(value) / int(words_quantity) * 100)) + '%'\n for key, value in count_words.items()]\n string3 = ', '.join(new_list2)\n print(f'- frequency: {string3}')\n\n return\n\n\nif __name__ == '__main__':\n\n my_string = 'The owners of the Zaandam, Holland America, said that more than 130 people on board had reported ' \\\n 'suffering \"flu-like symptoms\" and respiratory issues.' \\\n 'Nobody has left the ship since it docked in Chile two weeks ago.' \\\n 'Holland America said it planned to transfer passengers to a sister ship.' \\\n 'The Zaandam and the Rotterdam are both off the western, Pacific coast of Panama.' \\\n 'The Zaandam is trying to sail to Florida. But the Panamanian authorities have said no vessel with ' \\\n 'confirmed coronavirus cases on board can pass through the Panama Canal.'\n format_result(my_string)\n","sub_path":"pivak_gennadii/05/text_analyzer.py","file_name":"text_analyzer.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"402883869","text":"from django.contrib import admin\nfrom django.apps import apps\n\nimport models\n\n# any model that requires a custom admin view must be registered here\nexcluded_models = [models.Page, models.Site, models.PageFeatures]\n\n\nclass PageAdmin(admin.ModelAdmin):\n search_fields = ('url', )\n list_display = ('id', 'url', 'page_views', 'created', 'last_updated')\n\n\nclass SiteAdmin(admin.ModelAdmin):\n search_fields = ('domain', 'name')\n list_display = ('id', 'domain', 'name', 'ignore_site', 'created', 'last_updated')\n list_editable = (\n ('name', 'ignore_site')\n )\n\n\nclass FeaturesAdmin(admin.ModelAdmin):\n list_display = (\n 'page',\n 'title_length',\n 'title_sentiment',\n 'title_num_entities',\n 'num_links',\n 'num_internal_links',\n 'num_external_links',\n 'first_heading_length',\n 'num_h1',\n 'num_h2',\n 'num_h3',\n 'body_text_length',\n 'body_text_num_words'\n )\n\n\nadmin.site.register(models.Site, SiteAdmin)\nadmin.site.register(models.Page, PageAdmin)\nadmin.site.register(models.PageFeatures, FeaturesAdmin)\n\n# automatically register all models using the default ModelAdmin\n# excludes models with custom admin views\napp = apps.get_app_config('ratings')\nfor model_name, model in app.models.items():\n if model in excluded_models:\n continue\n admin.site.register(model, admin.ModelAdmin)\n","sub_path":"backend/iffy/ratings/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156251539","text":"import numpy as np\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\n\nimport ephem\nimport datetime\nfrom datetime import timedelta\n\n# Setup lat long of telescope\nhome = ephem.Observer()\n\nhome.long = np.deg2rad(74.7421430) # +E\nhome.lat = np.deg2rad(13.3408810) # +N\nhome.elevation = 0 # meters\nhome.date = datetime.datetime.now()\n\n# Always get the latest ISS TLE data from:\n# http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html\niss = ephem.readtle('ISS',\n '1 25544U 98067A 16274.50033672 .00016717 00000-0 10270-3 0 9003',\n '2 25544 51.6383 252.7108 0006713 21.8902 338.2536 15.54019889 21364'\n )\n\n# Make some datetimes\ncurrent_time = datetime.datetime.now()\npast_time = current_time + timedelta(hours=-1)\ndt = [current_time + timedelta(seconds=1*x) for x in range(0, 24*60*60)]\ndt_past = [past_time + timedelta(seconds=1*x) for x in range(0, 60*60)]\n\n\n# Compute satellite locations at each datetime\nsat_lat, sat_lon,sat_latp, sat_lonp = [], [],[ ], []\nfor date in dt:\n home.date = date\n iss.compute(home)\n sat_lon.append(np.rad2deg(iss.sublong))\n sat_lat.append(np.rad2deg(iss.sublat))\n\nfor date in dt_past:\n home.date = date\n iss.compute(home)\n sat_lonp.append(np.rad2deg(iss.sublong))\n sat_latp.append(np.rad2deg(iss.sublat))\n\nfor i in range(len(sat_lon)):\n if sat_lon[i]<0:\n sat_lon[i]=360+sat_lon[i]\nfor i in range(len(sat_lonp)):\n if sat_lonp[i]<0:\n sat_lonp[i]=360+sat_lonp[i]\n\n\n\n# miller projection\nmap = Basemap(projection='mill',lon_0=180)\n# plot coastlines, draw label meridians and parallels.\nmap.drawcoastlines()\nmap.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])\nmap.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])\n# fill continents 'coral' (with zorder=0), color wet areas 'aqua'\nmap.drawmapboundary(fill_color='aqua')\n#map.fillcontinents(color='coral',lake_color='aqua')\n# shade the night areas, with alpha transparency so the\n# map shows through. Use current time in UTC.\ndate = datetime.datetime.utcnow()\nx,y=map(sat_lon,sat_lat)\nx = np.atleast_1d(x)\ny = np.atleast_1d(y)\n\nxp,yp=map(sat_lonp,sat_latp)\nxp = np.atleast_1d(xp)\nyp = np.atleast_1d(yp)\n\nCS=map.nightshade(date)\n\nplt.scatter(xp,yp,color='y',s=5,label=\"Past Hour\")\nplt.ion()\n\nfor i in range(len(sat_lon)):\n plt.scatter(x[i],y[i],color='r',label=\"realtime\")\n plt.pause(1)\n\nwhile True:\n plt.pause(1)\n\nplt.title('Day/Night Map for %s (UTC)' % date.strftime(\"%d %b %Y %H:%M:%S\"))\n#plt.show()\n","sub_path":"ref_modules/plotdaynight.py","file_name":"plotdaynight.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"87968993","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\ndef train_test_validate_split(df, test_size=0.25, random_state=42):\n \n if test_size > 0.25:\n test_size = 0.25\n\n totalrows = len(df)\n test_rows = totalrows * test_size\n remaining_rows = totalrows - test_rows \n val_size = test_rows/remaining_rows\n\n train, test = train_test_split(df, test_size=test_size, random_state=random_state)\n train, validate = train_test_split(train, test_size=val_size, random_state=random_state)\n\n return train, test, validate\n\nimport pandas as pd\n\n\ndf = pd.read_csv(\"http://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data\")\ntn, tt, v = train_test_validate_split(df, test_size=0.25, random_state=42)\n\nprint('Test Size=', len(tt))\nprint('Validate Size=', len(v))\nprint('Train Size=', len(tn))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"400769410","text":"\"\"\"\nThis module is responsible for loading the documentation from Python objects.\n\nIt uses [`inspect`](https://docs.python.org/3/library/inspect.html) for introspecting objects,\niterating over their members, etc.\n\"\"\"\n\nimport importlib\nimport inspect\nimport pkgutil\nimport re\nfrom functools import lru_cache\nfrom itertools import chain\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set, Union\n\nfrom pytkdocs.objects import Attribute, Class, Function, Method, Module, Object, Source\nfrom pytkdocs.parsers.attributes import get_class_attributes, get_instance_attributes, get_module_attributes, merge\nfrom pytkdocs.parsers.docstrings import PARSERS\nfrom pytkdocs.properties import RE_SPECIAL\n\n\nclass ObjectNode:\n \"\"\"\n Helper class to represent an object tree.\n\n It's not really a tree but more a backward-linked list:\n each node has a reference to its parent, but not to its child (for simplicity purposes and to avoid bugs).\n\n Each node stores an object, its name, and a reference to its parent node.\n \"\"\"\n\n def __init__(self, obj: Any, name: str, parent: Optional[\"ObjectNode\"] = None) -> None:\n \"\"\"\n Initialization method.\n\n Arguments:\n obj: A Python object.\n name: The object's name.\n parent: The object's parent node.\n \"\"\"\n try:\n obj = inspect.unwrap(obj)\n except Exception: # noqa: S110 (we purposely catch every possible exception)\n # inspect.unwrap at some point runs hasattr(obj, \"__wrapped__\"),\n # which triggers the __getattr__ method of the object, which in\n # turn can raise various exceptions. Probably not just __getattr__.\n # See https://github.com/pawamoy/pytkdocs/issues/45\n pass\n\n self.obj: Any = obj\n \"\"\"The actual Python object.\"\"\"\n\n self.name: str = name\n \"\"\"The Python object's name.\"\"\"\n\n self.parent: Optional[ObjectNode] = parent\n \"\"\"The parent node.\"\"\"\n\n @property\n def dotted_path(self) -> str:\n \"\"\"The Python dotted path of the object.\"\"\"\n parts = [self.name]\n current = self.parent\n while current:\n parts.append(current.name)\n current = current.parent\n return \".\".join(reversed(parts))\n\n @property\n def file_path(self) -> str:\n \"\"\"The object's module file path.\"\"\"\n return inspect.getabsfile(self.root.obj)\n\n @property\n def root(self) -> \"ObjectNode\":\n \"\"\"The root of the tree.\"\"\"\n if self.parent is not None:\n return self.parent.root\n return self\n\n def is_module(self) -> bool:\n \"\"\"Is this node's object a module?\"\"\"\n return inspect.ismodule(self.obj)\n\n def is_class(self) -> bool:\n \"\"\"Is this node's object a class?\"\"\"\n return inspect.isclass(self.obj)\n\n def is_function(self) -> bool:\n \"\"\"Is this node's object a function?\"\"\"\n return inspect.isfunction(self.obj)\n\n def is_property(self) -> bool:\n \"\"\"Is this node's object a property?\"\"\"\n return isinstance(self.obj, property)\n\n def parent_is_class(self) -> bool:\n \"\"\"Is the object of this node's parent a class?\"\"\"\n return bool(self.parent and self.parent.is_class())\n\n def is_method(self) -> bool:\n \"\"\"Is this node's object a method?\"\"\"\n return self.parent_is_class() and isinstance(self.obj, type(lambda: 0))\n\n def is_staticmethod(self) -> bool:\n \"\"\"Is this node's object a staticmethod?\"\"\"\n if not self.parent:\n return False\n return self.parent_is_class() and isinstance(self.parent.obj.__dict__.get(self.name, None), staticmethod)\n\n def is_classmethod(self) -> bool:\n \"\"\"Is this node's object a classmethod?\"\"\"\n if not self.parent:\n return False\n return self.parent_is_class() and isinstance(self.parent.obj.__dict__.get(self.name, None), classmethod)\n\n\ndef get_object_tree(path: str) -> ObjectNode:\n \"\"\"\n Transform a path into an actual Python object.\n\n The path can be arbitrary long. You can pass the path to a package,\n a module, a class, a function or a global variable, as deep as you\n want, as long as the deepest module is importable through\n `importlib.import_module` and each object is obtainable through\n the `getattr` method. It is not possible to load local objects.\n\n Args:\n path: the dot-separated path of the object.\n\n Raises:\n ValueError: when the path is not valid (evaluates to `False`).\n ImportError: when the object or its parent module could not be imported.\n\n Returns:\n The leaf node representing the object and its parents.\n \"\"\"\n if not path:\n raise ValueError(f\"path must be a valid Python path, not {path}\")\n\n # We will try to import the longest dotted-path first.\n # If it fails, we remove the right-most part and put it in a list of \"objects\", used later.\n # We loop until we find the deepest importable submodule.\n obj_parent_modules = path.split(\".\")\n objects: List[str] = []\n\n while True:\n parent_module_path = \".\".join(obj_parent_modules)\n try:\n parent_module = importlib.import_module(parent_module_path)\n except ImportError:\n if len(obj_parent_modules) == 1:\n raise ImportError(\"No module named '%s'\" % obj_parent_modules[0])\n objects.insert(0, obj_parent_modules.pop(-1))\n else:\n break\n\n # We now have the module containing the desired object.\n # We will build the object tree by iterating over the previously stored objects names\n # and trying to get them as attributes.\n current_node = ObjectNode(parent_module, parent_module.__name__)\n for obj_name in objects:\n obj = getattr(current_node.obj, obj_name)\n current_node.child = ObjectNode(obj, obj_name, parent=current_node) # type: ignore\n current_node = current_node.child # type: ignore\n\n leaf = current_node\n\n # We now try to get the \"real\" parent module, not the one the object was imported into.\n # This is important if we want to be able to retrieve the docstring of an attribute for example.\n # Once we find an object for which we could get the module, we stop trying to get the module.\n # Once we reach the node before the root, we apply the module if found, and break.\n real_module = None\n while current_node.parent is not None:\n if real_module is None:\n real_module = inspect.getmodule(current_node.obj)\n if inspect.ismodule(current_node.parent.obj):\n if real_module is not None and real_module is not current_node.parent.obj:\n current_node.parent = ObjectNode(real_module, real_module.__name__)\n break\n current_node = current_node.parent\n\n return leaf\n\n\nclass Loader:\n \"\"\"\n This class contains the object documentation loading mechanisms.\n\n Any error that occurred during collection of the objects and their documentation is stored in the `errors` list.\n \"\"\"\n\n def __init__(\n self,\n filters: Optional[List[str]] = None,\n docstring_style: str = \"google\",\n docstring_options: Optional[dict] = None,\n inherited_members: bool = False,\n ) -> None:\n \"\"\"\n Initialization method.\n\n Arguments:\n filters: A list of regular expressions to fine-grain select members. It is applied recursively.\n docstring_style: The style to use when parsing docstrings.\n docstring_options: The options to pass to the docstrings parser.\n inherited_members: Whether to select inherited members for classes.\n \"\"\"\n if not filters:\n filters = []\n\n self.filters = [(f, re.compile(f.lstrip(\"!\"))) for f in filters]\n self.docstring_parser = PARSERS[docstring_style](**(docstring_options or {})) # type: ignore\n self.errors: List[str] = []\n self.select_inherited_members = inherited_members\n\n def get_object_documentation(self, dotted_path: str, members: Optional[Union[Set[str], bool]] = None) -> Object:\n \"\"\"\n Get the documentation for an object and its children.\n\n Arguments:\n dotted_path: The Python dotted path to the desired object.\n members: `True` to select members and filter them, `False` to select no members,\n or a list of names to explicitly select the members with these names.\n It is applied only on the root object.\n\n Return:\n The documented object.\n \"\"\"\n if members is True:\n members = set()\n\n root_object: Object\n leaf = get_object_tree(dotted_path)\n\n if leaf.is_module():\n root_object = self.get_module_documentation(leaf, members)\n elif leaf.is_class():\n root_object = self.get_class_documentation(leaf, members)\n elif leaf.is_staticmethod():\n root_object = self.get_staticmethod_documentation(leaf)\n elif leaf.is_classmethod():\n root_object = self.get_classmethod_documentation(leaf)\n elif leaf.is_method():\n root_object = self.get_regular_method_documentation(leaf)\n elif leaf.is_function():\n root_object = self.get_function_documentation(leaf)\n elif leaf.is_property():\n root_object = self.get_property_documentation(leaf)\n else:\n root_object = self.get_attribute_documentation(leaf)\n\n root_object.parse_all_docstrings(self.docstring_parser)\n\n return root_object\n\n def get_module_documentation(self, node: ObjectNode, select_members=None) -> Module:\n \"\"\"\n Get the documentation for a module and its children.\n\n Arguments:\n node: The node representing the module and its parents.\n select_members: Explicit members to select.\n\n Return:\n The documented module object.\n \"\"\"\n module = node.obj\n path = node.dotted_path\n name = path.split(\".\")[-1]\n source: Optional[Source]\n\n try:\n source = Source(inspect.getsource(module), 1)\n except OSError as error:\n try:\n with Path(node.file_path).open() as fd:\n code = fd.readlines()\n if code:\n source = Source(code, 1)\n else:\n source = None\n except OSError:\n self.errors.append(f\"Couldn't read source for '{path}': {error}\")\n source = None\n\n root_object = Module(\n name=name, path=path, file_path=node.file_path, docstring=inspect.getdoc(module), source=source\n )\n\n if select_members is False:\n return root_object\n\n # type_hints = get_type_hints(module)\n select_members = select_members or set()\n\n attributes_data = get_module_attributes(module)\n root_object.parse_docstring(self.docstring_parser, attributes=attributes_data)\n\n for member_name, member in inspect.getmembers(module):\n if self.select(member_name, select_members): # type: ignore\n child_node = ObjectNode(member, member_name, parent=node)\n if child_node.is_class() and node.root.obj is inspect.getmodule(member):\n root_object.add_child(self.get_class_documentation(child_node))\n elif child_node.is_function() and node.root.obj is inspect.getmodule(member):\n root_object.add_child(self.get_function_documentation(child_node))\n elif member_name in attributes_data:\n root_object.add_child(self.get_attribute_documentation(child_node, attributes_data[member_name]))\n\n try:\n package_path = module.__path__\n except AttributeError:\n pass\n else:\n for _, modname, _ in pkgutil.iter_modules(package_path):\n if self.select(modname, select_members):\n leaf = get_object_tree(f\"{path}.{modname}\")\n root_object.add_child(self.get_module_documentation(leaf))\n\n return root_object\n\n def get_class_documentation(self, node: ObjectNode, select_members=None) -> Class:\n \"\"\"\n Get the documentation for a class and its children.\n\n Arguments:\n node: The node representing the class and its parents.\n select_members: Explicit members to select.\n\n Return:\n The documented class object.\n \"\"\"\n class_ = node.obj\n docstring = inspect.cleandoc(class_.__doc__ or \"\")\n root_object = Class(name=node.name, path=node.dotted_path, file_path=node.file_path, docstring=docstring)\n\n # Even if we don't select members, we want to correctly parse the docstring\n attributes_data: Dict[str, Dict[str, Any]] = {}\n for cls in reversed(class_.__mro__[:-1]):\n merge(attributes_data, get_class_attributes(cls))\n context: Dict[str, Any] = {\"attributes\": attributes_data}\n if \"__init__\" in class_.__dict__:\n attributes_data.update(get_instance_attributes(class_.__init__))\n context[\"signature\"] = inspect.signature(class_.__init__)\n root_object.parse_docstring(self.docstring_parser, attributes=attributes_data)\n\n if select_members is False:\n return root_object\n\n select_members = select_members or set()\n\n # Build the list of members\n members = {}\n inherited = set()\n direct_members = class_.__dict__\n all_members = dict(inspect.getmembers(class_))\n for member_name, member in all_members.items():\n if not (member is type or member is object) and self.select(member_name, select_members):\n if member_name not in direct_members:\n if self.select_inherited_members:\n members[member_name] = member\n inherited.add(member_name)\n else:\n members[member_name] = member\n\n # Iterate on the selected members\n child: Object\n for member_name, member in members.items():\n child_node = ObjectNode(member, member_name, parent=node)\n if child_node.is_class():\n child = self.get_class_documentation(child_node)\n elif child_node.is_classmethod():\n child = self.get_classmethod_documentation(child_node)\n elif child_node.is_staticmethod():\n child = self.get_staticmethod_documentation(child_node)\n elif child_node.is_method():\n child = self.get_regular_method_documentation(child_node)\n elif child_node.is_property():\n child = self.get_property_documentation(child_node)\n elif member_name in attributes_data:\n child = self.get_attribute_documentation(child_node, attributes_data[member_name])\n else:\n continue\n if member_name in inherited:\n child.properties.append(\"inherited\")\n root_object.add_child(child)\n\n # First check if this is Pydantic compatible\n if \"__fields__\" in direct_members or (self.select_inherited_members and \"__fields__\" in all_members):\n root_object.properties = [\"pydantic-model\"]\n for field_name, model_field in all_members[\"__fields__\"].items():\n if self.select(field_name, select_members) and ( # type: ignore\n self.select_inherited_members\n # When we don't select inherited members, one way to tell if a field was inherited\n # is to check if it exists in parent classes __fields__ attributes.\n # We don't check the current class, nor the top one (object), hence __mro__[1:-1]\n or field_name not in chain(*(getattr(cls, \"__fields__\", {}).keys() for cls in class_.__mro__[1:-1]))\n ):\n child_node = ObjectNode(obj=model_field, name=field_name, parent=node)\n root_object.add_child(self.get_pydantic_field_documentation(child_node))\n\n # Check if this is a marshmallow class\n elif \"_declared_fields\" in direct_members or (\n self.select_inherited_members and \"_declared_fields\" in all_members\n ):\n root_object.properties = [\"marshmallow-model\"]\n for field_name, model_field in all_members[\"_declared_fields\"].items():\n if self.select(field_name, select_members) and ( # type: ignore\n self.select_inherited_members\n # Same comment as for Pydantic models\n or field_name\n not in chain(*(getattr(cls, \"_declared_fields\", {}).keys() for cls in class_.__mro__[1:-1]))\n ):\n child_node = ObjectNode(obj=model_field, name=field_name, parent=node)\n root_object.add_child(self.get_marshmallow_field_documentation(child_node))\n\n # Handle dataclasses\n elif \"__dataclass_fields__\" in direct_members or (\n self.select_inherited_members and \"__dataclass_fields__\" in all_members\n ):\n root_object.properties = [\"dataclass\"]\n\n for field in all_members[\"__dataclass_fields__\"].values():\n if self.select(field.name, select_members) and ( # type: ignore\n self.select_inherited_members\n # Same comment as for Pydantic models\n or field.name\n not in chain(*(getattr(cls, \"__dataclass_fields__\", {}).keys() for cls in class_.__mro__[1:-1]))\n ):\n child_node = ObjectNode(obj=field.type, name=field.name, parent=node)\n root_object.add_child(self.get_annotated_dataclass_field(child_node))\n\n return root_object\n\n def get_function_documentation(self, node: ObjectNode) -> Function:\n \"\"\"\n Get the documentation for a function.\n\n Arguments:\n node: The node representing the function and its parents.\n\n Return:\n The documented function object.\n \"\"\"\n function = node.obj\n path = node.dotted_path\n source: Optional[Source]\n signature: Optional[inspect.Signature]\n\n try:\n signature = inspect.signature(function)\n except TypeError as error:\n self.errors.append(f\"Couldn't get signature for '{path}': {error}\")\n signature = None\n\n try:\n source = Source(*inspect.getsourcelines(function))\n except OSError as error:\n self.errors.append(f\"Couldn't read source for '{path}': {error}\")\n source = None\n\n return Function(\n name=node.name,\n path=node.dotted_path,\n file_path=node.file_path,\n docstring=inspect.getdoc(function),\n signature=signature,\n source=source,\n )\n\n def get_property_documentation(self, node: ObjectNode) -> Attribute:\n \"\"\"\n Get the documentation for an attribute.\n\n Arguments:\n node: The node representing the attribute and its parents.\n\n Return:\n The documented attribute object.\n \"\"\"\n prop = node.obj\n path = node.dotted_path\n properties = [\"property\", \"readonly\" if prop.fset is None else \"writable\"]\n source: Optional[Source]\n\n try:\n signature = inspect.signature(prop.fget)\n except (TypeError, ValueError) as error:\n self.errors.append(f\"Couldn't get signature for '{path}': {error}\")\n attr_type = None\n else:\n attr_type = signature.return_annotation\n\n try:\n source = Source(*inspect.getsourcelines(prop.fget))\n except (OSError, TypeError) as error:\n self.errors.append(f\"Couldn't get source for '{path}': {error}\")\n source = None\n\n return Attribute(\n name=node.name,\n path=path,\n file_path=node.file_path,\n docstring=inspect.getdoc(prop.fget),\n attr_type=attr_type,\n properties=properties,\n source=source,\n )\n\n @staticmethod\n def get_pydantic_field_documentation(node: ObjectNode) -> Attribute:\n \"\"\"\n Get the documentation for a Pydantic Field.\n\n Arguments:\n node: The node representing the Field and its parents.\n\n Return:\n The documented attribute object.\n \"\"\"\n prop = node.obj\n path = node.dotted_path\n properties = [\"pydantic-field\"]\n if prop.required:\n properties.append(\"required\")\n\n return Attribute(\n name=node.name,\n path=path,\n file_path=node.file_path,\n docstring=prop.field_info.description,\n attr_type=prop.type_,\n properties=properties,\n )\n\n @staticmethod\n def get_marshmallow_field_documentation(node: ObjectNode) -> Attribute:\n \"\"\"\n Get the documentation for a Marshmallow Field.\n\n Arguments:\n node: The node representing the Field and its parents.\n\n Return:\n The documented attribute object.\n \"\"\"\n prop = node.obj\n path = node.dotted_path\n properties = [\"marshmallow-field\"]\n if prop.required:\n properties.append(\"required\")\n\n return Attribute(\n name=node.name,\n path=path,\n file_path=node.file_path,\n docstring=prop.metadata.get(\"description\"),\n attr_type=type(prop),\n properties=properties,\n )\n\n @staticmethod\n def get_annotated_dataclass_field(node: ObjectNode, attribute_data: Optional[dict] = None) -> Attribute:\n \"\"\"\n Get the documentation for an dataclass annotation.\n\n Arguments:\n node: The node representing the annotation and its parents.\n attribute_data: Docstring and annotation for this attribute.\n\n Return:\n The documented attribute object.\n \"\"\"\n if attribute_data is None:\n if node.parent_is_class():\n attribute_data = get_class_attributes(node.parent.obj).get(node.name, {}) # type: ignore\n else:\n attribute_data = get_module_attributes(node.root.obj).get(node.name, {})\n\n return Attribute(\n name=node.name,\n path=node.dotted_path,\n file_path=node.file_path,\n docstring=attribute_data[\"docstring\"],\n attr_type=attribute_data[\"annotation\"],\n properties=[\"dataclass-field\"],\n )\n\n def get_classmethod_documentation(self, node: ObjectNode) -> Method:\n \"\"\"\n Get the documentation for a class-method.\n\n Arguments:\n node: The node representing the class-method and its parents.\n\n Return:\n The documented method object.\n \"\"\"\n return self.get_method_documentation(node, [\"classmethod\"])\n\n def get_staticmethod_documentation(self, node: ObjectNode) -> Method:\n \"\"\"\n Get the documentation for a static-method.\n\n Arguments:\n node: The node representing the static-method and its parents.\n\n Return:\n The documented method object.\n \"\"\"\n return self.get_method_documentation(node, [\"staticmethod\"])\n\n def get_regular_method_documentation(self, node: ObjectNode) -> Method:\n \"\"\"\n Get the documentation for a regular method (not class- nor static-method).\n\n We do extra processing in this method to discard docstrings of `__init__` methods\n that were inherited from parent classes.\n\n Arguments:\n node: The node representing the method and its parents.\n\n Return:\n The documented method object.\n \"\"\"\n method = self.get_method_documentation(node)\n if node.parent:\n class_ = node.parent.obj\n if RE_SPECIAL.match(node.name):\n docstring = method.docstring\n parent_classes = class_.__mro__[1:]\n for parent_class in parent_classes:\n try:\n parent_method = getattr(parent_class, node.name)\n except AttributeError:\n continue\n else:\n if docstring == inspect.getdoc(parent_method):\n method.docstring = \"\"\n break\n return method\n\n def get_method_documentation(self, node: ObjectNode, properties: Optional[List[str]] = None) -> Method:\n \"\"\"\n Get the documentation for a method.\n\n Arguments:\n node: The node representing the method and its parents.\n properties: A list of properties to apply to the method.\n\n Return:\n The documented method object.\n \"\"\"\n method = node.obj\n path = node.dotted_path\n source: Optional[Source]\n\n try:\n source = Source(*inspect.getsourcelines(method))\n except OSError as error:\n self.errors.append(f\"Couldn't read source for '{path}': {error}\")\n source = None\n except TypeError:\n source = None\n\n return Method(\n name=node.name,\n path=path,\n file_path=node.file_path,\n docstring=inspect.getdoc(method),\n signature=inspect.signature(method),\n properties=properties or [],\n source=source,\n )\n\n @staticmethod\n def get_attribute_documentation(node: ObjectNode, attribute_data: Optional[dict] = None) -> Attribute:\n \"\"\"\n Get the documentation for an attribute.\n\n Arguments:\n node: The node representing the method and its parents.\n attribute_data: Docstring and annotation for this attribute.\n\n Returns:\n The documented attribute object.\n \"\"\"\n if attribute_data is None:\n if node.parent_is_class():\n attribute_data = get_class_attributes(node.parent.obj).get(node.name, {}) # type: ignore\n else:\n attribute_data = get_module_attributes(node.root.obj).get(node.name, {})\n return Attribute(\n name=node.name,\n path=node.dotted_path,\n file_path=node.file_path,\n docstring=attribute_data.get(\"docstring\", \"\"),\n attr_type=attribute_data.get(\"annotation\", None),\n )\n\n def select(self, name: str, names: Set[str]) -> bool:\n \"\"\"\n Tells whether we should select an object or not, given its name.\n\n If the set of names is not empty, we check against it, otherwise we check against filters.\n\n Arguments:\n name: The name of the object to select or not.\n names: An explicit list of names to select.\n\n Returns:\n Yes or no.\n \"\"\"\n if names:\n return name in names\n return not self.filter_name_out(name)\n\n @lru_cache(maxsize=None)\n def filter_name_out(self, name: str) -> bool:\n \"\"\"\n Filter a name based on the loader's filters.\n\n Arguments:\n name: The name to filter.\n\n Returns:\n True if the name was filtered out, False otherwise.\n \"\"\"\n if not self.filters:\n return False\n keep = True\n for fltr, regex in self.filters:\n is_matching = bool(regex.search(name))\n if is_matching:\n if str(fltr).startswith(\"!\"):\n is_matching = not is_matching\n keep = is_matching\n return not keep\n","sub_path":"src/pytkdocs/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":27931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79411139","text":"#-------------------------------------------------------------------\r\n#Created by Virgile Colrat - LNIS 09/20/2020 \r\n#\r\n#This python module gathers the function usefull for the control of the \r\n#MFCs instument using a USB->serial adapter. To function properly,\r\n#it is needed to install the following python packages: \r\n# - pyvisa (Detailed instruction on how to install pyvisa\r\n# on MAC, Windows or linux https://pyvisa.readthedocs.io/en/1.8/getting.html)\r\n#\t-\tserial\r\n#A detailed list of all the commands available to the MFCs used in the experiment\r\n#can be found here:\r\n#https://documents.alicat.com/manuals/Gas_Flow_Controller_Manual.pdf\r\n#There are 2 types of function in this module, the basic function (found in instrument\r\n# documentation) and \"advance\" function that are a combination of basic function and are used\r\n#to simplify the use of the instrument in this experiment\r\n#-------------------------------------------------------------------\r\n\r\n\r\nimport serial\r\n#########################################################\r\n## basic functions ##\r\n## The following functions are the direct application ##\r\n## of the functions described in the EW-32907-XX ##\r\n## documentation ##\r\n######################################################### \r\n\r\n#OpenMFC: opens up the port on which the instrument is connected\r\ndef OpenMFC(comPort):\r\n\tser = serial.Serial(comPort, 19200, timeout=10, rtscts=0, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, xonxoff=False)\r\n\treturn ser\r\n\r\n#MeasureAndReturnPoll: does one measurment and returns it immediatly\r\ndef MeasureAndReturnPoll(comPort, iD):\r\n\tmessage=iD+\"\\r\\n\"\r\n\tres =''.join(format(ord(i), 'b') for i in message)\r\n\tcomPort.write(res)\r\n\treturn(comPort.read())\r\n\r\n#BeginStream: start the streaming of the data, the MFC send continuously data to the computer, the data has to be polled in the main function\r\ndef BeginStream(comPort, iD):\r\n\tmessage=iD+\"@=@\\r\\n\"\r\n\tres =''.join(format(ord(i), 'b') for i in message)\r\n\tcomPort.write(res)\r\n\r\n#StopStream: stops the streaming of data\r\ndef StopStream(comPort, iD):\r\n\tmessage=\"@@=\"+iD+\"\\r\\n\"\r\n\tres =''.join(format(ord(i), 'b') for i in message)\r\n\tcomPort.write(res)\r\n\r\n#SetStreamInterval: sets the time interval between 2 measurment (in milliseconds) in streaming mode\r\ndef SetStreamInterval(comPort, iD, timeInterval):\r\n\tmessage=iD+\" w91=\"+str(timeInterval)+\"\\r\\n\"\r\n\tres =''.join(format(ord(i), 'b') for i in message)\r\n\tcomPort.write(res)\r\n\r\n#SetSetpoint: sets the flow at which the MFC should work\r\ndef SetSetpoint(comPort, flowSetpoint):\r\n\tmessage=\"as\"+str(flowSetpoint)\r\n\tres =''.join(format(ord(i), 'b') for i in message)\r\n\t#res=serialcmd.encode()\r\n\tres=str.encode(message)\r\n\tcomPort.write(res)\r\n\r\ndef ChangeId(comPort):\r\n\tstring=\"A@=B\"\r\n\tres=string.encode()\r\n\tarr = bytes(string, 'utf-8')\r\n\tarr2 = bytes(string, 'ascii')\r\n\tarr3 = bytes(string, 'ansi')\r\n\tcomPort.write(res)\r\n\tcomPort.write(arr)\r\n\tcomPort.write(arr2)\r\n\tcomPort.write(arr3)\r\n\tcomPort.write(b'A@=B')\r\n\tprint(\"ok ?\")\r\n#########################################################\r\n## Advanced functions ##\r\n######################################################### \r\n\r\ndef streamData(comPort, iD, timeInterval, flowSetpoint):\r\n\tSetStreamInterval(comPort, iD, timeInterval)\r\n\tBeginStream(comPort, iD)\r\n\tSetSetpoint(comPort, flowSetpoint)\r\n\r\n","sub_path":"Source_test_chip_matthieu/MFC_Control.py","file_name":"MFC_Control.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"629605565","text":"from user import User\n\nclass Seller(User):\n \"\"\"\n Represent a seller.\n Subclass of User.\n \"\"\"\n\n def __init__(self, nickname):\n \"\"\"\n Initialize a seller\n \"\"\"\n super().__init__(nickname)\n self.comand_list = [\"search\", \"analyze\"]\n\n\n\n\nif __name__ == '__main__':\n seller = Seller(\"Solomiia\")\n seller.get_comands()\n","sub_path":"seller.py","file_name":"seller.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423852272","text":"mode = ''\r\nwhile mode != 'l' and mode != 'n':\r\n mode = input('[l] Local ou [n] Network?\\n');\r\n\r\n\r\nif mode == 'l':\r\n import game\r\n\r\n g = game.Game()\r\n\r\n g.p1 = g.newPlayer(1, g.ships[:], g.p1Field, g.p1BombField)\r\n input('Aperta enter, vacilão')\r\n g.clear()\r\n\r\n g.p2 = g.newPlayer(2, g.ships[:], g.p2Field, g.p2BombField)\r\n input('Enter man...')\r\n g.clear()\r\n\r\n g.start()\r\nelse:\r\n sc = ''\r\n while sc != 's' and sc != 'c':\r\n sc = input('[s] Server ou [c] Cliente?\\n');\r\n if sc == 's':\r\n import server\r\n\r\n s = server.Server()\r\n s.connect()\r\n\r\n else:\r\n import client\r\n\r\n c = client.Client()","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290809774","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2017.\n@contact: 449628536@qq.com\n@software: learn-py\n@file: len1_positional_arguments.py\n@time: 2017/11/14 下午2:31\n'''\n\n\ndef test_var_args(f_arg, *argv):\n print('first normal arg:', f_arg)\n for arg in argv:\n print('another arg thought *argv:', arg)\n\n\ntest_var_args('yasoob', 'python', 'eggs', 'test')\n","sub_path":"inter-py/len1_positional_arguments.py","file_name":"len1_positional_arguments.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"127539722","text":"\"\"\"Module for representing a simple game\"\"\"\r\n\r\nimport sys\r\nimport datetime\r\nimport pygame\r\nfrom grid import Occupation\r\nfrom grid import Grid\r\nimport a_star\r\n\r\ndef read_map_from_file(file_name, grid):\r\n \"\"\"Function for reading a map from a file and creating a matching grid\"\"\"\r\n\r\n file = None\r\n\r\n try:\r\n file = open(file_name, 'r')\r\n except IOError:\r\n print(\"Could not open file:\", file_name)\r\n return grid\r\n\r\n for i in range(0, 15):\r\n line = file.readline()\r\n for j in range(0, 15):\r\n char = line[j * 2]\r\n if char == 'B':\r\n grid.set_occupation_pos(Occupation.BLOCKED, j, i)\r\n elif char == 'S':\r\n grid.set_occupation_pos(Occupation.START, j, i)\r\n elif char == 'G':\r\n grid.set_occupation_pos(Occupation.GOAL, j, i)\r\n\r\n return grid\r\n\r\n\r\n\r\n# pylint: disable=no-member\r\n# Because pylint does not seemingly work with pygame\r\n\r\nDONE = False\r\npygame.init()\r\nSCREEN = pygame.display.set_mode((632, 632))\r\nCLOCK = pygame.time.Clock()\r\n\r\nBLOCKS_IN_WIDTH = 15\r\nBLOCKS_IN_HEIGHT = 15\r\n\r\nGRID = Grid(BLOCKS_IN_WIDTH, BLOCKS_IN_HEIGHT, 40, 40)\r\n\r\nif len(sys.argv) > 1:\r\n GRID = read_map_from_file(sys.argv[1], GRID)\r\n\r\n\r\nwhile not DONE:\r\n SCREEN.fill((0, 0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n DONE = True\r\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:\r\n GRID.update_occupation()\r\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\r\n GRID.set_occupation(Occupation.BLOCKED)\r\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 2:\r\n GRID.set_occupation(Occupation.NONE)\r\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:\r\n if GRID.get_start() == (-1, -1) or GRID.get_goal() == (-1, -1):\r\n print(\"Missing a start or a goal\")\r\n continue\r\n\r\n start = GRID.get_start()\r\n start = (start[0], (BLOCKS_IN_HEIGHT - 1) - start[1])\r\n goal = GRID.get_goal()\r\n goal = (goal[0], (BLOCKS_IN_HEIGHT - 1) - goal[1])\r\n path = a_star.a_star(GRID.to_tuple(), start, goal)\r\n GRID.clear_paths()\r\n\r\n if path is not None:\r\n if (path[0][0], (BLOCKS_IN_HEIGHT - 1) - path[0][1]) == GRID.get_start():\r\n path = path[1:]\r\n if (path[-1][0], (BLOCKS_IN_HEIGHT - 1) - path[-1][1]) == GRID.get_goal():\r\n path = path[:-1]\r\n\r\n for x_position, y_position in path:\r\n y_position = (BLOCKS_IN_HEIGHT - 1) - y_position\r\n GRID.set_occupation_pos(Occupation.PATH, x_position, y_position)\r\n GRID.render(SCREEN)\r\n pygame.display.flip()\r\n CLOCK.tick(10)\r\n else:\r\n print(\"Impossible to create path\")\r\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\r\n GRID.clear_paths()\r\n\r\n GRID.render(SCREEN)\r\n\r\n pygame.display.flip()\r\n CLOCK.tick(60)\r\n\r\n#GRID.write_to_file((str(datetime.datetime.now()) + \" map.txt\").replace(\" \", \"_\").replace(\"-\", \"_\").replace(\":\", \"_\"))\r\n","sub_path":"grid_game.py","file_name":"grid_game.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36911115","text":"import pandas as pd\nimport numpy as np\n# import mglearn\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\nfrom pandas import DataFrame\nimport sqlite3\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.model_selection import train_test_split\nfrom scipy.ndimage.interpolation import shift\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, classification_report\nfrom sklearn.metrics import classification_report, roc_curve\nimport seaborn as sns\n\nstart_date = datetime.strptime(\"2009-01-01\", \"%Y-%m-%d\")\nfinish_date = datetime.strptime(\"2011-12-31 23:59\", \"%Y-%m-%d %H:%M\")\nnumber_tower = \"Data_1st\"\n\nquery = '''SELECT Date, %s FROM Data WHERE Date >= \\'%s\\' AND Date <= \\'%s\\';''' % (\n str(number_tower), start_date, finish_date)\nconn = sqlite3.connect(\"mydatabase.db\")\ncursor = conn.cursor()\ndataset = pd.read_sql_query(query, conn)\ndataset.Date = dataset['Date'].apply(pd.to_datetime)\ndataset.index = dataset.Date\ndataset.drop('Date', axis='columns', inplace=True)\n\nmagnitude = 4\nquery2 = '''SELECT * FROM earthquake WHERE Time >= \\'%s\\' AND Time <= \\'%s\\' AND Magnitude >= %s;''' \\\n % (start_date, finish_date, magnitude)\nearthquake_df = pd.read_sql_query(query2, conn)\n# earthquake_df['Time'] = earthquake_df['Time'].apply(pd.to_datetime)\nearthquake_df.index = earthquake_df.Time\nearthquake_df.drop('Time', axis='columns', inplace=True)\n\nbuff_X = np.array(dataset[f'{start_date.date()}'])\nbuff_X = buff_X.transpose()\ndate_list = list()\ncount = 1\nX = np.array(list())\n\nfor date in pd.date_range(start_date + timedelta(days=1), finish_date):\n\n if count < 7:\n buff_arr = np.array(dataset[f'{date.date()}'])\n if buff_X.shape[0] == 0:\n buff_X = np.array(buff_arr.transpose())\n else:\n buff_X = np.vstack((buff_X, buff_arr.transpose()))\n\n count += 1\n if count == 7:\n count = 0\n date_list.append(date.date() - timedelta(days=6))\n if X.shape[0] == 0:\n X = np.array(buff_X.ravel())\n else:\n X = np.vstack((X, buff_X.ravel()))\n buff_X = np.array(list())\nif buff_X.shape[0] != 0:\n # zer = np.zeros((1, X.shape[1] - buff_X.ravel().shape[0]))\n buff_X = np.append(buff_X, np.zeros((1, X.shape[1] - buff_X.ravel().shape[0])))\n X = np.vstack((X, buff_X))\n\ny = list()\ncount = 0\nseism = False\nfor date in pd.date_range(start_date, finish_date):\n count += 1\n flg = earthquake_df.index.str.find(str(date.date()))\n if 0 in flg:\n seism = True\n if count == 7:\n count = 0\n if seism:\n y.append(1)\n else:\n y.append(0)\n seism = False\nif count != 0:\n if seism:\n y.append(1)\n else:\n y.append(0)\n\ny = np.array(y)\ny = shift(y, -2, cval=0) # shift for n week(2 in this moment)\n\nparam_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100],\n 'gamma': [0.001, 0.01, 0.1, 1, 10, 100]}\ngrid_search = GridSearchCV(SVC(), param_grid, cv=5)\n\n# if 1 in y:\n# print(len(y))\n# print(y)\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)\ngrid_search.fit(X_train, y_train)\n\nforest = RandomForestClassifier(n_estimators=1, random_state=4, n_jobs=6, max_depth=3)\nforest.fit(X_train, y_train)\n\ngbrt = GradientBoostingClassifier(random_state=2, max_depth=1, learning_rate=1)\ngbrt.fit(X_train, y_train)\n\n#metrics\nprint('Правильность на обуч наборе: {:.3f}'.format(gbrt.score(X_train, y_train)))\nprint('Правильность на тестовом наборе: {:.3f}'.format(gbrt.score(X_test, y_test)))\n\n# print(forest)\nprint('Правильность на обуч наборе: {:.3f}'.format(forest.score(X_train, y_train)))\nprint('Правильность на тестовом наборе: {:.3f}'.format(forest.score(X_test, y_test)))\n# confusion = confusion_matrix(y_test, forest.predict(X_test)) #матрица ошибок\nprint(classification_report(y_test, forest.predict(X_test), target_names=[\"earthquake\", \"none earthquake\"]))\nprint(classification_report(y_test, gbrt.predict(X_test)))\n\nprecision_rf, recall_rf, thresholds_rf = precision_recall_curve(y_test, forest.predict_proba(X_test)[:, 1])\nprecision_gbrt, recall_gbrt, thresholds_gbrt = precision_recall_curve(y_test, gbrt.decision_function(X_test))\n\nplt.plot(precision_rf, recall_rf, label='RF')\nplt.plot(precision_gbrt, recall_gbrt, label='GBRT')\nplt.xlabel(\"Precision\")\nplt.ylabel('Recall')\nplt.legend('best')\nplt.legend(loc=2)\nplt.show()\n\nfpr_rf, tpr_rf, thresholds_rf = roc_curve(y_test, forest.predict_proba(X_test)[:, 1])\nfpr_gbrt, tpr_gbrt, thresholds_gbrt = roc_curve(y_test, gbrt.decision_function(X_test))\nplt.plot(fpr_rf, tpr_rf, label='ROC RF')\nplt.plot(fpr_gbrt, tpr_gbrt, label='ROC GBRT')\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.legend(loc=4)\nplt.show()\n","sub_path":"Earthquake_predict/Forest.py","file_name":"Forest.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11404210","text":"import json\nclass ParseJson():\n def get_jsonvalue(self,content,node):\n pass\n\n def update_jsonvalue(self,wholejson,casestatus):\n for keyitem in casestatus.keys():\n wholejson[keyitem] = casestatus[keyitem]\n return wholejson\n\nif __name__==\"__main__\":\n jsonvalue={\"power_on_time_value\": 0,\n \"mode\": \"cool\",\n \"power_off_time_value\": 0,\n \"wind_swing_ud\": \"off\",\n \"dry\": \"off\",\n \"eco\": \"off\",\n \"purifier\": \"off\",\n \"error_code\": 10,\n \"power_on_timer\": \"off\",\n \"comfort_power_save\": \"off\",\n \"prevent_cold\": \"off\",\n \"small_temperature\": 0,\n \"power_off_timer\": \"off\",\n \"kick_quilt\": \"off\",\n \"power\": \"off\",\n \"version\": 39,\n \"wind_swing_lr\": \"off\",\n \"ptc\": \"off\",\n \"temperature\": 17,\n \"wind_speed\": 102,\n \"strong_wind\": \"off\"\n }\n a=ParseJson().update_jsonvalue(jsonvalue,{\"power\": \"on\",\"pow11\":\"2222\"})\n print(a)\n\n\n","sub_path":"AITEST/common/Parsejson.py","file_name":"Parsejson.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"194111311","text":"\nk = 12\nt = 25\n\nwith open('dataset_159_5.txt','r') as f:\n dna = []\n for line in f:\n line = line.strip()\n dna.append(line)\n\n###############################################################################\n\ndef motif_profile_forming(motif_list):\n profile_matrix = []\n matrix = []\n for i in range(k):\n matrix.append(0)\n for i in range(4):\n profile_matrix.append(matrix.copy())\n \n for i in range(k):\n base_string = ''\n for j in motif_list:\n base_string = base_string + j[i]\n A_freq = base_string.count('A') / len(base_string) \n C_freq = base_string.count('C') / len(base_string) \n G_freq = base_string.count('G') / len(base_string) \n T_freq = base_string.count('T') / len(base_string)\n \n profile_matrix[0][i] = A_freq\n profile_matrix[1][i] = C_freq\n profile_matrix[2][i] = G_freq\n profile_matrix[3][i] = T_freq\n\n return profile_matrix\n \n###############################################################################\n\ndef profile_most_probable(text, k, profile_matrix):\n base_index = ['A','C','G','T']\n pattern_list = []\n probable_list = []\n \n for i in range(len(text)-k+1):\n pattern = text[i:i+k]\n pattern_list.append(pattern)\n \n probable_sum = 1\n\n for j in range(k):\n base = pattern[j]\n base_nu = base_index.index(base)\n probable_sum = probable_sum*float(profile_matrix[base_nu][j])\n\n probable_list.append(probable_sum)\n\n max_probable = max(probable_list)\n max_probable_index = probable_list.index(max_probable)\n pattern = pattern_list[max_probable_index]\n\n return pattern\n\n###############################################################################\n\ndef matrix_score(motif_list):\n score = 0\n for i in range(k):\n motif_string = ''\n for j in motif_list:\n motif_string = motif_string + j[i]\n A_count = motif_string.count('A')\n C_count = motif_string.count('C')\n G_count = motif_string.count('G')\n T_count = motif_string.count('T')\n \n max_count = max(A_count, C_count, G_count, T_count)\n score = score + t - max_count\n\n return score\n\n###############################################################################\n\ndef greedy_motif_search(dna, k, t):\n best_motif = []\n for string in dna:\n first_motif = string[0:k]\n best_motif.append(first_motif)\n for i in range(len(dna[0])-k+1):\n motif = dna[0][i:i+k]\n motif_list = []\n motif_list.append(motif)\n for i in range(1,t):\n profile_matrix = motif_profile_forming(motif_list)\n motif = profile_most_probable(dna[i], k, profile_matrix)\n motif_list.append(motif)\n if matrix_score(motif_list) < matrix_score(best_motif):\n best_motif = motif_list\n\n return best_motif\n\n\n \nbest_motif = greedy_motif_search(dna, k, t)\nfor i in best_motif:\n print(i)\n \n","sub_path":"bioinfo_sec1/week3/No4_greedy_motif_search.py","file_name":"No4_greedy_motif_search.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"256807824","text":"\r\nimport pandas as pd \r\nimport numpy as np \r\nimport scipy.sparse as sparse\r\nimport math\r\ndef create_PCC_matrix():\r\n print(\"start constructing PCC movie matrix\")\r\n data = pd.read_csv(\"./data/train.csv\",names=[\"MovieID\",\"UserID\",\"Rating\",\"RatingDate\"])\r\n user_total = data[\"UserID\"].unique().max() + 1#including 0\r\n movie_total = data[\"MovieID\"].unique().max() + 1 #including 0\r\n \r\n row = np.array([])\r\n column = np.array([])\r\n cos_row = np.array([])\r\n cos_column = np.array([])\r\n \r\n pro_value = np.array([])\r\n cos_value = np.array([])\r\n for given_userid in data[\"UserID\"].unique():#0-10915\r\n #print(given_userid)\r\n \r\n given_user = data[data[\"UserID\"] == given_userid]\r\n \r\n given_user_user = np.array([given_userid for x in range(len(given_user))])\r\n given_user_movie = np.array(given_user[\"MovieID\"].tolist())\r\n given_user_rating = np.array(given_user[\"Rating\"].tolist())\r\n given_user_rating = given_user_rating -3\r\n average = given_user_rating.sum()/len(given_user_rating)\r\n \r\n given_user_rating = given_user_rating - average # Centering\r\n L2_norm = math.sqrt((given_user_rating*given_user_rating).sum())\r\n\r\n if L2_norm == 0:\r\n print(\"L2_norm == 0\")\r\n continue\r\n\r\n given_user_rating = given_user_rating/L2_norm\r\n row = np.concatenate((row,given_user_user))\r\n column = np.concatenate((column,given_user_movie))#column index strat from 0\r\n pro_value = np.concatenate((pro_value,given_user_rating))\r\n \r\n abs_user_row = math.sqrt((given_user_rating*given_user_rating).sum())\r\n if(abs_user_row>0):\r\n abs_given_user_rating = given_user_rating/abs_user_row\r\n cos_row = np.concatenate((cos_row,given_user_user))\r\n cos_column = np.concatenate((cos_column,given_user_movie))#column index strat from 0\r\n cos_value = np.concatenate((cos_value,abs_given_user_rating))\r\n \r\n #product similarity\r\n pro_user_movie_matrix = sparse.csc_matrix((pro_value, (row, column)), shape=(user_total, movie_total)) #row vector\r\n \r\n pro_movie_movie_matrix = pro_user_movie_matrix.transpose().dot(pro_user_movie_matrix) #none sparse\r\n pro_movie_movie_matrix = pro_movie_movie_matrix.toarray()\r\n \r\n \r\n cos_user_movie_matrix = sparse.csc_matrix((cos_value, (cos_row, cos_column)), shape=(user_total, movie_total)) #row vector\r\n \r\n \r\n cos_movie_movie_matrix = cos_user_movie_matrix.transpose().dot(cos_user_movie_matrix) #none sparse\r\n cos_movie_movie_matrix = cos_movie_movie_matrix.toarray()\r\n \r\n return(pro_movie_movie_matrix,cos_movie_movie_matrix)\r\n \r\n\r\npro_movie_movie_matrix,cos_movie_movie_matrix = create_PCC_matrix()","sub_path":"Collaborative Filtering/src/PCC_create_matrix.py","file_name":"PCC_create_matrix.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561175357","text":"from dictogram import Dictogram\nimport random\nimport re\n\n\nclass MarkovChain(dict):\n def __init__(self, corpus):\n if type(corpus) is str:\n corpus = self.open_file(corpus)\n super(MarkovChain, self).__init__()\n self.types = 0\n self.tokens = 0\n\n if corpus is not None:\n for index in range(len(corpus) - 1):\n if index != len(corpus) - 1:\n self.add_count(corpus[index], corpus[index + 1])\n\n def add_count(self, word_1, word_2):\n self.tokens += 1\n\n if len(self) == 0:\n self[word_1] = Dictogram([word_2])\n self.types += 1\n return\n\n if word_1 in self:\n self[word_1].add_count(word_2)\n # self[self.index(word_1)][1].add_count(word_2)\n return\n\n self[word_1] = Dictogram([word_2])\n self.types += 1\n\n def generate_random_sentence(self, length):\n randy = random.randint(0, len(self) - 1)\n sentence = ['the']\n for _ in range(length):\n sentence.append(self.get_next_word(sentence[-1]))\n return ' '.join(sentence)\n\n def get_next_word(self, word):\n if word in self.keys():\n dictogram = self.get(word)\n randy = random.randint(0, len(dictogram) - 1)\n iterator = 0\n for key, value in dictogram.items():\n if randy <= iterator:\n return key\n else:\n iterator += value\n\n @staticmethod\n def open_file(corpus):\n f = open(corpus, 'r', encoding='utf-8')\n words = f.read().lower().replace('\\n', ' ')\n words = re.sub('[^a-z]+', ' ', words)\n words = words.split(' ')\n return words\n\n\nif __name__ == '__main__':\n chain = MarkovChain('surgery.txt')\n for _ in range(10):\n for i in range(5, 10):\n print(chain.generate_random_sentence(i))","sub_path":"markov_chain.py","file_name":"markov_chain.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432747089","text":"\"\"\"\nThe demonstration of websocket server based on the BaseHTTPRequestHandler and ThreadingHTTPServer\nThe implementation notes as below\n+ The main thread is to listen and accept the client connection\n+ The thread is created for each connection\n\"\"\"\nimport base64\nimport hashlib\nimport http.server\n\nimport threading\n\nPORT = 8080\n\nclass WebsocketHandler(http.server.BaseHTTPRequestHandler):\n\n def __init__(self, *args, **kwargs):\n\n print(\"is called me!!!!\")\n\n super().__init__(*args, **kwargs)\n\n def ws_accept(self, key):\n if isinstance(key, str):\n key = key.encode('ascii')\n return base64.standard_b64encode(hashlib.sha1(\n key + b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n ).digest()).decode('ascii')\n\n\n def frame_make(msg):\n \"\"\"\n construct a websocket frame\n \"\"\"\n preamble = 1 << 7\n if isinstance(msg, str):\n preamble |= 1\n msg = msg.encode('utf-8')\n else:\n preamble |= 2\n frame = bytes([preamble])\n if len(msg) <= 125:\n frame += bytes([len(msg)])\n elif len(msg) < 2 ** 16:\n frame += bytes([126])\n frame += len(msg).to_bytes(2, 'big')\n else:\n frame += bytes([127])\n frame += len(msg).to_bytes(4, 'big')\n frame += msg\n return frame\n \n def frame_read(self) -> bytes:\n \"\"\"\n Read a complete ws frame\n \"\"\"\n\n # FIXME: handle reading when the connection is closed\n preamble = self.rfile.read(2)\n mask = preamble[1] >> 7\n length = preamble[1] & 0x7f\n if length == 126:\n length = int.from_bytes(self.rfile.read(2), 'big')\n elif length == 127:\n length = int.from_bytes(self.rfile.read(4), 'big')\n if mask:\n mask_key = self.rfile.read(4)\n data = self.rfile.read(length)\n if mask:\n data = bytes([data[i] ^ mask_key[i % 4] for i in range(len(data))])\n\n # if preamble[0] & 0xf == 1:\n # data = data.decode('utf-8')\n return data\n\n def do_handshake(self):\n \"\"\"\n Do websocket handshake\n \"\"\"\n self.send_response(101)\n self.send_header('Upgrade', 'websocket')\n self.send_header('Connection', 'upgrade')\n self.send_header('Sec-WebSocket-Accept',\n self.ws_accept(self.headers.get('Sec-WebSocket-Key')))\n self.end_headers()\n\n def do_GET(self):\n # Do websocket handshake\n self.do_handshake()\n while True:\n # Read a frame\n frame_msg = self.frame_read()\n print(\"frame_msg: \\n\", frame_msg.decode())\n\n # if self.on_read != None:\n # self.on_read(frame_msg)\n\n def send_msg(self, msg:str):\n \"\"\"\n \"\"\"\n self.wfile.write(self.frame_make(\"Echo msg: \" + msg))\n\n def close(self):\n \"\"\"\n Close both read & write connection\n \"\"\"\n self.finish()\n\ndef srv_accept_thread(): \n with http.server.ThreadingHTTPServer((\"\", PORT), WebsocketHandler) as ws:\n print(\"websocket is serving at port\", PORT)\n ws.serve_forever()\n\n\nif __name__ == \"__main__\":\n accept_thread = threading.Thread(target=srv_accept_thread, args = ())\n accept_thread.start()\n\n \n\n","sub_path":"02_ws_srv/ws_srv_echo.py","file_name":"ws_srv_echo.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337941296","text":"def data_grepper(file):\n try:\n with open(file) as data:\n return data.readline().strip().split(',')\n except IOError as err:\n print(\"File Error : \" + str(err))\n\n\ndef sanitize(time_string):\n \"\"\"\n :param time_string: Input time string, which may have mins and seconds separated by either ':', '-' or '.'\n :return: Uniformly formatted time string with mins and secs separated by '.'\n \"\"\"\n if \"-\" in time_string:\n splitter = \"-\"\n elif \":\" in time_string:\n splitter = \":\"\n else:\n return time_string\n (mins, secs) = time_string.split(splitter)\n return mins + \".\" + secs\n\n\"\"\"\nMain Code:\n==========\nThe code below does everything that athleteComprehension.py code does, but with far lesser effort.\n\"\"\"\njames = data_grepper('athleteTraining/james.txt')\njulie = data_grepper('athleteTraining/julie.txt')\nmikey = data_grepper('athleteTraining/mikey.txt')\nsarah = data_grepper('athleteTraining/sarah.txt')\n\n# Creating sets to store unique data:\nprint(\"\\nProcessed using a set: \")\nprint(\"James' top 3 times: \" + str(sorted(set([sanitize(time) for time in james]))[0:3])) # This is called function\n # chaining\nprint(\"Julie's top 3 times: \" + str(sorted(set([sanitize(time) for time in julie]))[0:3]))\nprint(\"Mikey's top 3 times: \" + str(sorted(set([sanitize(time) for time in mikey]))[0:3]))\nprint(\"Sarah's top 3 times: \" + str(sorted(set([sanitize(time) for time in sarah]))[0:3]))","sub_path":"HeadFirstPython/athleteSet.py","file_name":"athleteSet.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234026926","text":"#####################################################################\n# #\n# /figure_manager.py #\n# #\n# Copyright 2013, Monash University #\n# #\n# This file is part of the program lyse, in the labscript suite #\n# (see http://labscriptsuite.org), and is licensed under the #\n# Simplified BSD License. See the license.txt file in the root of #\n# the project for the full license. #\n# #\n#####################################################################\nimport lyse\nfrom collections import OrderedDict\nimport sys\n\nclass FigureManager(object):\n\n def __init__(self):\n self.figs = OrderedDict()\n self._figure = matplotlib.pyplot.figure\n self._close = matplotlib.pyplot.close\n self._show = matplotlib.pyplot.show\n self.__allocated_figures = []\n\n def get_first_empty_figure(self, identifier, *args, **kwargs):\n i = 1\n while True:\n # skip over protected figures that have been allocated to a specific identifier\n if i in self.__allocated_figures:\n i += 1\n continue\n fig = self._figure(i,*args,**kwargs)\n if not fig.axes:\n # only protect the figure if it has an explicit identifier\n # (this stops \"figure();figure();\"\" from generating multiple)\n # empty figures\n if identifier is not None:\n self.__allocated_figures.append(i)\n return i, fig\n i += 1\n \n def set_first_figure_current(self):\n # only do this if we have any figures at all\n # If we don't, we don't want to create one as that sets the size of the\n # window and then figures sizes are ignored by subsequent runs of the script\n if len(matplotlib.pyplot.get_fignums()) == 0:\n return \n \n identifier = 1\n fig = self._figure(identifier)\n if fig not in self.figs.values():\n self.figs[identifier] = fig\n elif identifier not in self.__allocated_figures:\n # handle case where we are swapping from all identified figures\n # to the first not being explicitly identified through a call to figure()\n # AND we already had a figure with the identifier of \"1\" which is what we use\n # for the default figure\n if identifier in self.figs and self.figs[identifier] != fig:\n j = identifier\n while j in self.figs:\n j += 1\n self.figs[j] = self.figs[identifier]\n msg = \"\"\"Warning: detected collision of matplotlib figure identifiers.\n Plot output may not be as expected. \n Re-run the analysis script to (hopefully) resolve the collision.\n To permanently fix this, please ensure you call figure() prior\n to other matplotlib plotting functions.\n \"\"\"\n sys.stderr.write(lyse.dedent(msg))\n self.figs[identifier] = fig\n self.__allocated_figures.append(identifier)\n self._remove_dead_references(identifier, fig)\n \n def __call__(self,identifier=None, *args, **kwargs):\n if identifier is None:\n number, fig = self.get_first_empty_figure(identifier, *args,**kwargs)\n self.figs[number] = fig\n self._remove_dead_references(number, fig)\n elif identifier in self.figs:\n fig = self.figs[identifier]\n self._figure(fig.number)\n if fig.number not in self.__allocated_figures:\n self.__allocated_figures.append(fig.number)\n else:\n number, fig = self.get_first_empty_figure(identifier, *args,**kwargs)\n self.figs[identifier] = fig\n self._remove_dead_references(identifier, fig)\n return fig\n\n def close(self,identifier=None):\n if identifier is None:\n thisfig = matplotlib.pyplot.gcf()\n for key, fig in list(self.figs.items()):\n if fig is thisfig:\n del self.figs[key]\n self._close()\n elif isinstance(identifier,matplotlib.figure.Figure):\n thisfig = identifier\n for key, fig in list(self.figs.items()):\n if fig is thisfig:\n del self.figs[key]\n self._close(thisfig)\n elif identifier == 'all':\n self.figs = OrderedDict()\n self._close('all')\n else:\n fig = self.figs[identifier]\n self._close(fig)\n del self.figs[identifier]\n \n def show(self):\n if lyse.spinning_top:\n pass # supress show()\n else:\n self._show()\n\n def reset(self):\n self.__allocated_figures = []\n\n def _remove_dead_references(self, current_identifier, current_fig):\n for key, fig in list(self.figs.items()):\n if fig == current_fig and key != current_identifier:\n del self.figs[key]\n\nfiguremanager = None\nmatplotlib = None\n\ndef install():\n if 'matplotlib.pyplot' in sys.modules:\n message = ('install() must be imported prior to importing pylab/pyplot ' +\n 'in order to correctly override the figure() function.')\n raise RuntimeError(message)\n\n global matplotlib\n global figuremanager\n import matplotlib.pyplot\n import matplotlib.figure\n\n figuremanager = FigureManager()\n matplotlib.pyplot.figure = figuremanager\n matplotlib.pyplot.close = figuremanager.close\n matplotlib.pyplot.show = figuremanager.show\n","sub_path":"lyse/figure_manager.py","file_name":"figure_manager.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"161924773","text":"\"\"\"Definitions for the review request detail view.\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom reviewboard.reviews.fields import get_review_request_fieldsets\nfrom reviewboard.reviews.models import BaseComment, ReviewRequest\n\n\nclass BaseReviewRequestPageEntry(object):\n \"\"\"An entry on the review detail page.\n\n This contains backend logic and frontend templates for one of the boxes\n that appears below the main review request box on the review request detail\n page.\n\n Attributes:\n timestamp (datetime.datetime):\n The timestamp of the entry.\n\n collasped (bool):\n Whether the entry should be initially collapsed.\n \"\"\"\n\n #: The template to render for the HTML.\n template_name = None\n\n #: The template to render for any JavaScript.\n js_template_name = None\n\n def __init__(self, timestamp, collapsed):\n \"\"\"Initialize the entry.\n\n Args:\n timestamp (datetime.datetime):\n The timestamp of the entry.\n\n collapsed (bool):\n Whether the entry is collapsed by default.\n \"\"\"\n self.timestamp = timestamp\n self.collapsed = collapsed\n\n\nclass ReviewEntry(BaseReviewRequestPageEntry):\n \"\"\"A review box.\n\n Attributes:\n review (reviewboard.reviews.models.Review):\n The review for this entry.\n\n issue_open_count (int):\n The count of open issues within this review.\n\n has_issues (bool):\n Whether there are any issues (open or not).\n\n comments (dict):\n A dictionary of comments. Each key in this represents a comment\n type, and the values are lists of comment objects.\n \"\"\"\n\n template_name = 'reviews/boxes/review.html'\n js_template_name = 'reviews/boxes/review.js'\n\n def __init__(self, request, review_request, review, collapsed):\n \"\"\"Initialize the entry.\n\n Args:\n request (django.http.HttpRequest):\n The request object.\n\n review_request (reviewboard.reviews.models.ReviewRequest):\n The review request that the change is for.\n\n review (reviewboard.reviews.models.Review):\n The review.\n\n collapsed (bool):\n Whether the entry is collapsed by default.\n \"\"\"\n super(ReviewEntry, self).__init__(review.timestamp, collapsed)\n\n self.request = request\n self.review_request = review_request\n self.review = review\n self.issue_open_count = 0\n self.has_issues = False\n self.comments = {\n 'diff_comments': [],\n 'screenshot_comments': [],\n 'file_attachment_comments': [],\n 'general_comments': [],\n }\n\n def add_comment(self, comment_type, comment):\n \"\"\"Add a comment to this entry.\n\n Args:\n comment_type (unicode):\n The type of comment (an index into the :py:attr:`comments`\n dictionary).\n\n comment (reviewboard.reviews.models.BaseComment):\n The comment to add.\n \"\"\"\n self.comments[comment_type].append(comment)\n\n if comment.issue_opened:\n self.has_issues = True\n\n if comment.issue_status == BaseComment.OPEN:\n self.issue_open_count += 1\n\n if self.review_request.submitter == self.request.user:\n self.collapsed = False\n\n\nclass ChangeEntry(BaseReviewRequestPageEntry):\n \"\"\"A change description box.\n\n Attributes:\n changedesc (reviewboard.changedescs.models.ChangeDescription):\n The change description for this entry.\n \"\"\"\n\n template_name = 'reviews/boxes/change.html'\n js_template_name = 'reviews/boxes/change.js'\n\n def __init__(self, request, review_request, changedesc, collapsed,\n locals_vars):\n \"\"\"Initialize the entry.\n\n Args:\n request (django.http.HttpRequest):\n The request object.\n\n review_request (reviewboard.reviews.models.ReviewRequest):\n The review request that the change is for.\n\n changedesc (reviewboard.changedescs.models.ChangeDescription):\n The change description for this entry.\n\n collapsed (bool):\n Whether the entry is collapsed by default.\n\n locals_vars (dict):\n A dictionary of the local variables inside the review detail\n view. This is done because some of the fields in the change\n description may make use of some of the maps maintained while\n building the page in order to avoid adding additional queries\n\n .. seealso::\n\n :py:data:`~reviewboard.reviews.fields.Field.locals_vars`\n \"\"\"\n super(ChangeEntry, self).__init__(changedesc.timestamp, collapsed)\n\n self.changedesc = changedesc\n self.fields_changed_groups = []\n cur_field_changed_group = None\n\n # See if there was a review request status change.\n status_change = changedesc.fields_changed.get('status')\n\n if status_change:\n assert 'new' in status_change\n self.new_status = ReviewRequest.status_to_string(\n status_change['new'][0])\n else:\n self.new_status = None\n\n # Process the list of fields, in order by fieldset. These will be\n # put into groups composed of inline vs. full-width field values,\n # for render into the box.\n fieldsets = get_review_request_fieldsets(\n include_main=True,\n include_change_entries_only=True)\n\n for fieldset in fieldsets:\n for field_cls in fieldset.field_classes:\n field_id = field_cls.field_id\n\n if field_id not in changedesc.fields_changed:\n continue\n\n inline = field_cls.change_entry_renders_inline\n\n if (not cur_field_changed_group or\n cur_field_changed_group['inline'] != inline):\n # Begin a new group of fields.\n cur_field_changed_group = {\n 'inline': inline,\n 'fields': [],\n }\n self.fields_changed_groups.append(cur_field_changed_group)\n\n if hasattr(field_cls, 'locals_vars'):\n field = field_cls(review_request, request=request,\n locals_vars=locals_vars)\n else:\n field = field_cls(review_request, request=request)\n\n cur_field_changed_group['fields'] += \\\n field.get_change_entry_sections_html(\n changedesc.fields_changed[field_id])\n","sub_path":"reviewboard/reviews/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":6817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157597332","text":"import sys\nfrom PyQt5.QtWidgets import *\n\n\nclass Form(QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n\n self.dial = QDial()\n self.dial.setNotchesVisible(True)\n\n self.spinBox = QSpinBox()\n\n layout = QHBoxLayout()\n layout.addWidget(self.dial)\n layout.addWidget(self.spinBox)\n\n self.setLayout(layout)\n self.setWindowTitle(\"Signals and Slots\")\n self.dial.valueChanged.connect(self.updateSpinner)\n self.spinBox.valueChanged.connect(self.updateDial)\n\n def updateSpinner(self):\n print(self.dial.value())\n self.spinBox.setValue(self.dial.value())\n\n def updateDial(self):\n print(self.spinBox.value())\n self.dial.setValue(self.spinBox.value())\n\n\napp = QApplication(sys.argv)\nform = Form()\nform.show()\napp.exec_()\n","sub_path":"gui/sample/signals_slots.py","file_name":"signals_slots.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259660852","text":"import torch.nn as nn\nimport torch\nfrom .token_performer import Token_performer\nfrom .Transformer import saliency_token_inference, contour_token_inference, token_TransformerEncoder\n\n\nclass token_trans(nn.Module):\n def __init__(self, in_dim=64, embed_dim=384, depth=14, num_heads=6, mlp_ratio=3.):\n super(token_trans, self).__init__()\n\n self.norm = nn.LayerNorm(in_dim)\n self.mlp = nn.Sequential(\n nn.Linear(in_dim, embed_dim),\n nn.GELU(),\n nn.Linear(embed_dim, embed_dim),\n )\n self.encoderlayer = token_TransformerEncoder(embed_dim=embed_dim, depth=depth, num_heads=num_heads, mlp_ratio=mlp_ratio)\n self.saliency_token_pre = saliency_token_inference(dim=embed_dim, num_heads=1)\n self.contour_token_pre = contour_token_inference(dim=embed_dim, num_heads=1)\n\n self.norm2 = nn.LayerNorm(embed_dim)\n self.mlp2 = nn.Sequential(\n nn.Linear(embed_dim, in_dim),\n nn.GELU(),\n nn.Linear(in_dim, in_dim),\n )\n\n self.norm2_c = nn.LayerNorm(embed_dim)\n self.mlp2_c = nn.Sequential(\n nn.Linear(embed_dim, in_dim),\n nn.GELU(),\n nn.Linear(in_dim, in_dim),\n )\n\n def forward(self, fea, saliency_tokens, contour_tokens):\n B, _, _ = fea.shape\n # fea [B, H*W, 64]\n # project to 384 dim\n fea = self.mlp(self.norm(fea))\n # fea [B, H*W, 384]\n\n fea = torch.cat((saliency_tokens, fea), dim=1)\n fea = torch.cat((fea, contour_tokens), dim=1)\n # [B, 1 + H*W + 1, 384]\n\n fea = self.encoderlayer(fea)\n # fea [B, 1 + H*W + 1, 384]\n saliency_tokens = fea[:, 0, :].unsqueeze(1)\n contour_tokens = fea[:, -1, :].unsqueeze(1)\n\n saliency_fea = self.saliency_token_pre(fea)\n # saliency_fea [B, H*W, 384]\n contour_fea = self.contour_token_pre(fea)\n # contour_fea [B, H*W, 384]\n\n # reproject back to 64 dim\n saliency_fea = self.mlp2(self.norm2(saliency_fea))\n contour_fea = self.mlp2_c(self.norm2_c(contour_fea))\n\n return saliency_fea, contour_fea, fea, saliency_tokens, contour_tokens\n\n\nclass decoder_module(nn.Module):\n def __init__(self, dim=384, token_dim=64, img_size=224, ratio=8, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), fuse=True):\n super(decoder_module, self).__init__()\n\n self.project = nn.Linear(token_dim, token_dim * kernel_size[0] * kernel_size[1])\n self.upsample = nn.Fold(output_size=(img_size // ratio, img_size // ratio), kernel_size=kernel_size, stride=stride, padding=padding)\n self.fuse = fuse\n if self.fuse:\n self.concatFuse = nn.Sequential(\n nn.Linear(token_dim*2, token_dim),\n nn.GELU(),\n nn.Linear(token_dim, token_dim),\n )\n self.att = Token_performer(dim=token_dim, in_dim=token_dim, kernel_ratio=0.5)\n\n # project input feature to 64 dim\n self.norm = nn.LayerNorm(dim)\n self.mlp = nn.Sequential(\n nn.Linear(dim, token_dim),\n nn.GELU(),\n nn.Linear(token_dim, token_dim),\n )\n\n def forward(self, dec_fea, enc_fea=None):\n\n if self.fuse:\n # from 384 to 64\n dec_fea = self.mlp(self.norm(dec_fea))\n\n # [1] token upsampling by the proposed reverse T2T module\n dec_fea = self.project(dec_fea)\n # [B, H*W, token_dim*kernel_size*kernel_size]\n dec_fea = self.upsample(dec_fea.transpose(1, 2))\n B, C, _, _ = dec_fea.shape\n dec_fea = dec_fea.view(B, C, -1).transpose(1, 2)\n # [B, HW, C]\n\n if self.fuse:\n # [2] fuse encoder fea and decoder fea\n dec_fea = self.concatFuse(torch.cat([dec_fea, enc_fea], dim=2))\n dec_fea = self.att(dec_fea)\n\n return dec_fea\n\n\nclass Decoder(nn.Module):\n def __init__(self, embed_dim=384, token_dim=64, depth=2, img_size=224):\n\n super(Decoder, self).__init__()\n\n self.norm = nn.LayerNorm(embed_dim)\n self.mlp = nn.Sequential(\n nn.Linear(embed_dim, embed_dim),\n nn.GELU(),\n nn.Linear(embed_dim, token_dim),\n )\n\n self.norm_c = nn.LayerNorm(embed_dim)\n self.mlp_c = nn.Sequential(\n nn.Linear(embed_dim, embed_dim),\n nn.GELU(),\n nn.Linear(embed_dim, token_dim),\n )\n self.img_size = img_size\n # token upsampling and multi-level token fusion\n self.decoder1 = decoder_module(dim=embed_dim, token_dim=token_dim, img_size=img_size, ratio=8, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), fuse=True)\n self.decoder2 = decoder_module(dim=embed_dim, token_dim=token_dim, img_size=img_size, ratio=4, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), fuse=True)\n self.decoder3 = decoder_module(dim=embed_dim, token_dim=token_dim, img_size=img_size, ratio=1, kernel_size=(7, 7), stride=(4, 4), padding=(2, 2), fuse=False)\n self.decoder3_c = decoder_module(dim=embed_dim, token_dim=token_dim, img_size=img_size, ratio=1, kernel_size=(7, 7), stride=(4, 4), padding=(2, 2), fuse=False)\n\n # token based multi-task predictions\n self.token_pre_1_8 = token_trans(in_dim=token_dim, embed_dim=embed_dim, depth=depth, num_heads=1)\n self.token_pre_1_4 = token_trans(in_dim=token_dim, embed_dim=embed_dim, depth=depth, num_heads=1)\n\n # predict saliency maps\n self.pre_1_16 = nn.Linear(token_dim, 1)\n self.pre_1_8 = nn.Linear(token_dim, 1)\n self.pre_1_4 = nn.Linear(token_dim, 1)\n self.pre_1_1 = nn.Linear(token_dim, 1)\n # predict contour maps\n self.pre_1_16_c = nn.Linear(token_dim, 1)\n self.pre_1_8_c = nn.Linear(token_dim, 1)\n self.pre_1_4_c = nn.Linear(token_dim, 1)\n self.pre_1_1_c = nn.Linear(token_dim, 1)\n\n for m in self.modules():\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.xavier_uniform_(m.weight),\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif classname.find('Linear') != -1:\n nn.init.xavier_uniform_(m.weight),\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif classname.find('BatchNorm') != -1:\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, saliency_fea_1_16, token_fea_1_16, saliency_tokens, contour_fea_1_16, contour_tokens, rgb_fea_1_8, rgb_fea_1_4):\n # saliency_fea_1_16 [B, 14*14, 384]\n # contour_fea_1_16 [B, 14*14, 384]\n # token_fea_1_16 [B, 1 + 14*14 + 1, 384] (contain saliency token and contour token)\n\n # saliency_tokens [B, 1, 384]\n # contour_tokens [B, 1, 384]\n\n # rgb_fea_1_8 [B, 28*28, 64]\n # rgb_fea_1_4 [B, 28*28, 64]\n\n B, _, _, = token_fea_1_16.size()\n\n saliency_fea_1_16 = self.mlp(self.norm(saliency_fea_1_16))\n # saliency_fea_1_16 [B, 14*14, 64]\n mask_1_16 = self.pre_1_16(saliency_fea_1_16)\n mask_1_16 = mask_1_16.transpose(1, 2).reshape(B, 1, self.img_size // 16, self.img_size // 16)\n\n contour_fea_1_16 = self.mlp_c(self.norm_c(contour_fea_1_16))\n # contour_fea_1_16 [B, 14*14, 64]\n contour_1_16 = self.pre_1_16_c(contour_fea_1_16)\n contour_1_16 = contour_1_16.transpose(1, 2).reshape(B, 1, self.img_size // 16, self.img_size // 16)\n\n # 1/16 -> 1/8\n # reverse T2T and fuse low-level feature\n fea_1_8 = self.decoder1(token_fea_1_16[:, 1:-1, :], rgb_fea_1_8)\n\n # token prediction\n saliency_fea_1_8, contour_fea_1_8, token_fea_1_8, saliency_tokens, contour_tokens = self.token_pre_1_8(fea_1_8, saliency_tokens, contour_tokens)\n\n # predict saliency and contour maps\n mask_1_8 = self.pre_1_8(saliency_fea_1_8)\n mask_1_8 = mask_1_8.transpose(1, 2).reshape(B, 1, self.img_size // 8, self.img_size // 8)\n\n contour_1_8 = self.pre_1_8_c(contour_fea_1_8)\n contour_1_8 = contour_1_8.transpose(1, 2).reshape(B, 1, self.img_size // 8, self.img_size // 8)\n\n # 1/8 -> 1/4\n fea_1_4 = self.decoder2(token_fea_1_8[:, 1:-1, :], rgb_fea_1_4)\n\n # token prediction\n saliency_fea_1_4, contour_fea_1_4, token_fea_1_4, saliency_tokens, contour_tokens = self.token_pre_1_4(fea_1_4, saliency_tokens, contour_tokens)\n\n # predict saliency maps and contour maps\n mask_1_4 = self.pre_1_4(saliency_fea_1_4)\n mask_1_4 = mask_1_4.transpose(1, 2).reshape(B, 1, self.img_size // 4, self.img_size // 4)\n\n contour_1_4 = self.pre_1_4_c(contour_fea_1_4)\n contour_1_4 = contour_1_4.transpose(1, 2).reshape(B, 1, self.img_size // 4, self.img_size // 4)\n\n # 1/4 -> 1\n saliency_fea_1_1 = self.decoder3(saliency_fea_1_4)\n contour_fea_1_1 = self.decoder3_c(contour_fea_1_4)\n\n mask_1_1 = self.pre_1_1(saliency_fea_1_1)\n mask_1_1 = mask_1_1.transpose(1, 2).reshape(B, 1, self.img_size // 1, self.img_size // 1)\n\n contour_1_1 = self.pre_1_1_c(contour_fea_1_1)\n contour_1_1 = contour_1_1.transpose(1, 2).reshape(B, 1, self.img_size // 1, self.img_size // 1)\n\n return [mask_1_16, mask_1_8, mask_1_4, mask_1_1], [contour_1_16, contour_1_8, contour_1_4, contour_1_1]\n\n","sub_path":"python/NCKU_LAB_Paper/VST/RGBD_VST/Models/Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":9436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537883283","text":"from __future__ import unicode_literals\nfrom django.db import models\n# from django.contrib.auth.models import User\n# from django.contrib.auth import get_user_model\n# User = get_user_model()\nfrom django.utils.timesince import timeuntil\nfrom django.core.urlresolvers import reverse\nfrom app.models import User, Organization, LoggedAction\n\nfrom sorl.thumbnail import get_thumbnail\nfrom teamedup.helpers import EmailNotification\nfrom django.conf import settings\n\nimport datetime\nimport json\n\n\nclass TeamQueryManager(models.Manager):\n def get_queryset(self):\n return super(TeamQueryManager, self).get_queryset().filter(is_archived=False)\n\nclass Team(models.Model):\n title = models.CharField(max_length=200)\n description = models.TextField(max_length=200)\n image = models.ImageField('img', upload_to='media/images/', default='img/dashboard_template_image.png')\n organization = models.ForeignKey(Organization, blank=True, null=True, default=None)\n everyone_can_invite = models.BooleanField(default=False)\n is_archived = models.BooleanField(default=False)\n\n objects = TeamQueryManager()\n\n @property\n def owners(self):\n return [member.user for member in self.member_set.filter(is_owner=True)]\n\n @property\n def members(self):\n return [member.user for member in self.member_set.all()]\n\n def __str__(self):\n return self.title\n\n def to_dict(self):\n try:\n image = get_thumbnail(self.image, '350x350', crop='center', quality=99).url\n except AttributeError:\n image = 'http://placehold.it/300x300&text=%s' % (self.title,)\n return {\n 'id': self.pk,\n 'title': self.title,\n 'description': self.description,\n 'image': image,\n 'members': [user.to_dict() for user in self.members],\n 'owners': [user.to_dict() for user in self.owners],\n 'everyone_can_invite': self.everyone_can_invite,\n 'is_archived': self.is_archived,\n 'type': 'team'\n #TODO: add organization field\n }\n\n @property\n def jsoned(self):\n return json.dumps(self.to_dict())\n\n def save(self, *args, **kwargs):\n if not self.organization:\n # TODO: remove this block before going live\n raise AttributeError\n created = False\n if self.pk is None:\n created = True\n super(Team, self).save(*args, **kwargs)\n if created:\n LoggedAction(content_object=self, text='%s team was created' % (self.title,), data=json.dumps({\n 'type': 'team_created',\n 'team': {\n 'id': self.pk,\n 'title': self.title\n }\n })).save()\n\n\n\n\nclass Role(models.Model):\n title = models.CharField(max_length=255, default='')\n description = models.TextField(default='')\n start_date = models.DateTimeField(default=None, blank=True, null=True)\n end_date = models.DateTimeField(default=None, blank=True, null=True)\n team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None, blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'title': self.title,\n 'description': self.description,\n 'start_date': self.start_date.strftime('%m-%d-%Y %H:%M'),\n 'end_date': self.end_date.strftime('%m-%d-%Y %H:%M'),\n 'duration': timeuntil(self.end_date, self.start_date),\n 'start_date_str': self.start_date.strftime('%d %b').lstrip(\"0\"),\n 'team': self.team.to_dict(),\n 'members': [ {\n 'id': member.user.pk,\n 'name': member.user.get_name(),\n 'userpic': member.user.get_userpic_url(),\n 'is_owner': member.is_owner,\n 'url': reverse('user-page', kwargs={'user_id': member.user.pk})\n } for member in self.member_set.all()]\n }\n\n @property\n def jsoned(self):\n return json.dumps(self.to_dict())\n\n def save(self, *args, **kwargs):\n created = False\n if self.pk is None:\n created = True\n super(Role, self).save(*args, **kwargs)\n if created:\n LoggedAction(content_object=self.team, text='%s role was created' % (self.title,), data=json.dumps({\n 'type': 'role_added',\n 'role': {\n 'id': self.pk,\n 'title': self.title\n },\n 'team': {\n 'id': self.team.pk,\n 'title': self.team.title\n }\n })).save()\n\n\nclass Member(models.Model):\n role = models.ManyToManyField(Role, default=None, blank=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)\n team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None)\n is_owner = models.BooleanField(default=False)\n created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n\n def get_roles_ids(self):\n return [item['id'] for item in self.role.values('id')]\n\n def save(self, *args, **kwargs):\n if self.pk is None:\n LoggedAction(content_object=self.team,\n text='%s has joined %s team' % (self.user.get_name(), self.team.pk), data=json.dumps({\n 'type': 'user_joined_team',\n 'user': {\n 'id': self.user.id,\n 'name': self.user.get_name(),\n },\n 'team': {\n 'id': self.team.pk,\n 'title': self.team.title\n }\n })).save()\n super(Member, self).save(*args, **kwargs)\n\n\n# class Request(models.Model): # TODO: refactor the invitation mechanism later\n# team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None) # related team\n# user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) # user related to the invitation\n# sender = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='sender') # who sent the invitation\n# created_at = models.DateTimeField(auto_now_add=True)\n\n# def to_dict(self):\n# return {\n# 'id': self.pk,\n# 'team': self.team.to_dict(),\n# 'user': self.user.to_dict(),\n# 'sender': self.sender.to_dict(),\n# 'created_at': self.created_at.strftime(\"%B %d, %Y at %I:%M%p\"),\n# }\n\n\n\nclass Invite(models.Model):\n team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None)\n inviter = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='invites')\n invitee = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='inviteds')\n created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n expired_at = models.DateTimeField(default=None, blank=True, null=True)\n status = models.CharField(max_length=20, default=None)\n read = models.BooleanField(default=False, blank=False, null=False)\n\n def save(self, *args, **kwargs):\n if not self.pk:\n link = '%s/app/notifications/' % (settings.BASE_URL,)\n EmailNotification.add(self.invitee.email, settings.INVITE_REQUEST_EMAIL,\n (self.invitee.get_name(), self.inviter.get_name(), self.team.title, link,))\n else:\n EmailNotification.add(self.inviter.email, settings.INVITE_REQUEST_ACCEPTED_EMAIL if self.status == 'accepted' else settings.INVITE_REQUEST_DECLINED_EMAIL,\n (self.inviter.get_name(), self.invitee.get_name(), self.team.title,))\n super(Invite, self).save(*args, **kwargs)\n\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'status': self.status,\n 'team': {\n 'id': self.team.pk,\n 'title': self.team.title\n },\n 'inviter': self.inviter.to_dict(),\n 'invitee': self.invitee.to_dict(),\n }\n\n\nclass JoinRequest(models.Model):\n team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None)\n requester = models.ForeignKey(User, on_delete=models.CASCADE, default=None, related_name='team_join_requests')\n created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n expired_at = models.DateTimeField(default=None, blank=True, null=True)\n status = models.CharField(max_length=20, default=None)\n read = models.BooleanField(default=False, blank=False, null=False)\n\n def save(self, *args, **kwargs):\n if not self.pk:\n link = '%s/app/notifications/' % (settings.BASE_URL,)\n for owner in self.team.owners:\n EmailNotification.add(owner.email, settings.JOIN_REQUEST_EMAIL,\n (owner.get_name(), self.requester.get_name(), self.team.title, link,))\n else:\n EmailNotification.add(self.requester.email, settings.JOIN_REQUEST_ACCEPTED_EMAIL if self.status == 'accepted' else settings.JOIN_REQUEST_DECLINED_EMAIL,\n (self.requester.get_name(), self.team.title,))\n super(JoinRequest, self).save(*args, **kwargs)\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'status': self.status,\n 'team': {\n 'id': self.team.pk,\n 'title': self.team.title\n },\n 'requester': self.requester.to_dict(),\n }\n\n\nclass TeamResource(models.Model):\n team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None, blank=True, null=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True)\n\n def to_dict(self):\n last_revision = self.get_last_revision()\n return {\n 'id': self.pk,\n 'file': None if not last_revision else last_revision.to_dict(),\n 'comments_count': TeamResourceComment.objects.filter(resource=self).count()\n }\n\n def get_revisions(self):\n return TeamResourceRevision.objects.filter(resource=self).order_by('-created_at')\n\n def add_revision(self, user, file):\n revision = TeamResourceRevision()\n revision.file = file\n revision.user = user\n revision.resource = self\n revision.save()\n\n def get_last_revision(self):\n try:\n return self.get_revisions()[0]\n except IndexError:\n return None\n\n\nclass TeamResourceRevision(models.Model):\n resource = models.ForeignKey(TeamResource, on_delete=models.CASCADE, default=None, blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True)\n file = models.FileField('uploaded', upload_to='media/resources/')\n\n def get_filename(self):\n return self.file.url.split('/')[-1]\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'url': self.file.url,\n 'filename': self.get_filename(),\n 'extension': self.get_filename().split('.')[-1],\n 'user': self.user.to_dict()\n }\n\n\nclass TeamResourceComment(models.Model):\n resource = models.ForeignKey(TeamResource, on_delete=models.CASCADE, default=None, blank=True, null=True)\n revision = models.ForeignKey(TeamResourceRevision, on_delete=models.CASCADE, default=None, blank=True, null=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True)\n body = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True)\n \n def save(self, *args, **kwargs):\n super(TeamResourceComment, self).save(*args, **kwargs)\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'user': self.user.to_dict(),\n 'body': self.body,\n 'revision': self.revision.to_dict(),\n 'created_at': self.created_at.strftime(\"%B %d, %Y at %I:%M%p\"),\n }\n\n\nclass RoleFeedback(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True)\n reviewer = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True, related_name='reviewer')\n role = models.ForeignKey(Role, on_delete=models.CASCADE, default=None, blank=True, null=True)\n score = models.IntegerField(default=0)\n comment = models.TextField(null=True, blank=True)\n created_at = models.DateTimeField(auto_now_add=True)\n\n @staticmethod\n def get_all_user_feedback(user):\n feedback_scores = RoleFeedback.objects.filter(user=user).order_by('-created_at')\n feedback = {}\n scores = []\n for fs in feedback_scores:\n scores.append(fs.score)\n if fs.role.pk not in feedback:\n feedback[fs.role.pk] = {\n 'role': fs.role,\n 'feedback': [fs,]\n }\n else:\n feedback[fs.role.pk]['feedback'].append(fs)\n medium_score = 0 if len(scores) == 0 else sum(scores) / len(scores)\n return feedback, medium_score\n\n def save(self, *args, **kwargs):\n if self.pk is None:\n LoggedAction(content_object=self.user,\n text='%s has left feedback for you' % (self.reviewer.pk, self.reviewer.get_name(), self.role.pk)).save()\n super(RoleFeedback, self).save(*args, **kwargs)\n\n def to_dict(self):\n return {\n 'id': self.pk,\n 'user': self.user.to_dict(),\n 'reviewer': self.reviewer.to_dict(),\n 'score': self.score,\n 'comment': self.comment,\n 'created_at': self.created_at.strftime(\"%B %d, %Y at %I:%M%p\"), \n }","sub_path":"teams/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"278641974","text":"\r\nfrom .construct_weather_stations_py3 import Construct_Weather_Stations\r\nfrom .construct_irrigation_scheduling_py3 import Construct_Irrigation_Scheduling_Control\r\nfrom .plc_measurements_py3 import Construct_Lacima_PLC_Measurements\r\nfrom .construct_plc_devices_py3 import Construct_Lacima_PLC_Devices\r\nfrom .wifi_devices_py3 import Construct_Lacima_WIFI_Devices\r\nfrom .main_web_site_definition_py3 import Generate_Main_Server_Web_Page_Definitions\r\n\r\nclass LACIMA_Site_Definitons(object):\r\n\r\n\r\n\r\n\r\n\r\n def __init__(self,bc,cd):\r\n self.bc = bc\r\n self.cd = cd\r\n \r\n \r\n properties = {}\r\n properties[\"port\"] = 8080\r\n properties[\"https\"]= False\r\n properties[\"debug\"]= True\r\n properties[\"modules\"] = [\"monitoring\",\"mqtt_client\",\"eto\",\"irrigation_scheduling\",\"irrigation_control\",\"modbus_control\"]\r\n properties[\"status_function\"] = \"irrigation\"\r\n \r\n \r\n bc.add_header_node(\"Web_Server_Definitions\")\r\n temp = Generate_Main_Server_Web_Page_Definitions()\r\n menu_definitions = temp.generate_menu_objects()\r\n properties[\"menu\"] = menu_definitions\r\n bc.add_info_node(\"WEB_SERVER\",\"MAIN_WEB_SERVER\",properties = properties)\r\n bc.end_header_node(\"Web_Server_Definitions\")\r\n \r\n \r\n \r\n bc.add_header_node(\"CLOUD_SERVICE_QUEUE\")\r\n cd.construct_package(\"CLOUD_SERVICE_QUEUE_DATA\")\r\n cd.add_job_queue(\"CLOUD_JOB_SERVER\",2048,forward=False)\r\n cd.add_hash(\"CLOUD_SUB_EVENTS\")\r\n cd.close_package_contruction()\r\n \r\n bc.add_header_node(\"CLOUD_SERVICE_HOST_INTERFACE\")\r\n bc.add_info_node( \"HOST_INFORMATION\",\"HOST_INFORMATION\",properties={\"host\":\"192.168.1.41\" ,\"port\": 6379, \"key_data_base\": 6, \"key\":\"_UPLOAD_QUEUE_\" ,\"depth\":1024} )\r\n bc.end_header_node(\"CLOUD_SERVICE_HOST_INTERFACE\")\r\n bc.end_header_node(\"CLOUD_SERVICE_QUEUE\") \r\n \r\n\r\n \r\n \r\n\r\n\r\n \r\n bc.add_header_node(\"MQTT_DEVICES\")\r\n cd.construct_package(\"MQTT_DEVICES_DATA\")\r\n cd.add_redis_stream(\"MQTT_INPUT_QUEUE\",50000)\r\n cd.add_redis_stream(\"MQTT_SENSOR_QUEUE\",10000)\r\n cd.add_redis_stream(\"MQTT_PAST_ACTION_QUEUE\",300)\r\n cd.add_hash(\"MQTT_SENSOR_STATUS\")\r\n cd.add_hash(\"MQTT_DEVICES\")\r\n cd.add_hash(\"MQTT_SUBSCRIPTIONS\")\r\n cd.add_hash(\"MQTT_CONTACT_LOG\")\r\n cd.add_hash(\"MQTT_UNKNOWN_DEVICES\")\r\n cd.add_hash(\"MQTT_UNKNOWN_SUBSCRIPTIONS\")\r\n cd.add_hash(\"MQTT_REBOOT_LOG\")\r\n cd.add_hash(\"MQTT_SERVER_STATE\")\r\n cd.add_job_queue(\"MQTT_PUBLISH_QUEUE\",depth= 50,forward = False)\r\n cd.close_package_contruction()\r\n properties = {}\r\n properties[\"HOST\"] = \"192.168.1.110\"\r\n properties[\"PORT\"] = 1883\r\n properties[\"BASE_TOPIC\"] = \"/\"\r\n bc.add_info_node( \"MQTT_SERVER\",\"MQTT_SERVER\",properties=properties )\r\n self.add_mqtt_monitor()\r\n bc.end_header_node(\"MQTT_DEVICES\") \r\n \r\n \r\n\r\n \r\n Construct_Weather_Stations(bc,cd) \r\n Construct_Irrigation_Scheduling_Control(bc,cd) \r\n Construct_Lacima_PLC_Measurements(bc,cd) \r\n Construct_Lacima_PLC_Devices(bc,cd)\r\n Construct_Lacima_WIFI_Devices(bc,cd)\r\n \r\n def add_mqtt_monitor(self):\r\n mqtt_tag = \"MQTT_SERVER_CHECK\"\r\n properties = {}\r\n properties[\"REBOOT_FLAG\"] = True\r\n properties[\"REBOOT_KEY\"] = \"REBOOT\"\r\n properties[\"type\"] = \"MQTT_MONITOR\"\r\n properties[\"HEART_BEAT\"] = \"HEART_BEAT\"\r\n properties[\"HEART_BEAT_TIME_OUT\"] = 120\r\n properties[\"topic\"] = mqtt_tag\r\n properties[\"null_commands\"] = {}\r\n properties[\"subscriptions\"] = {}\r\n properties[\"subscriptions\"][\"REBOOT\"] = True\r\n properties[\"subscriptions\"][\"HEART_BEAT\"] = True\r\n properties[\"subscriptions\"][\"SERVER_CHECK\"] = True\r\n self.bc.add_info_node( \"MQTT_DEVICE\",mqtt_tag,properties=properties )\r\n \r\n \r\n ","sub_path":"working/python_containers/lacima_system_configuration/construct_graph/graph_modules_py3/lacima/site_definitions_py3.py","file_name":"site_definitions_py3.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}