diff --git "a/4247.jsonl" "b/4247.jsonl" new file mode 100644--- /dev/null +++ "b/4247.jsonl" @@ -0,0 +1,704 @@ +{"seq_id":"90620660","text":"import numpy as np\r\nfrom scipy.stats import norm\r\n\r\n\r\nclass LGSS:\r\n \"\"\"Linear Gaussian State Space model. The observation is assumed to be one-dimensional.\"\"\"\r\n\r\n def __init__(self, T, R, Q, Z, H, a1, P1):\r\n self.d = T.shape[0] # State dimension\r\n self.deta = R.shape[1] # Second dimension is process noise dim\r\n self.T = T # Process model\r\n self.R = R # Process noise prefactor\r\n self.Q = Q # Process noise covariance\r\n self.Z = Z # Measurement model\r\n self.H = H # Measurement noise variance\r\n self.a1 = a1 # Initial state mean\r\n self.P1 = P1 # Initial state covariance\r\n\r\n def get_params(self):\r\n \"\"\"Return all model parameters.\r\n\r\n T, R, Q, Z, H, a1, P1 = model.get_params()\r\n \"\"\"\r\n return self.T, self.R, self.Q, self.Z, self.H, self.a1, self.P1\r\n\r\n\r\nclass kfs_res:\r\n \"\"\"Container class to store result of Kalman filter and smoother.\"\"\"\r\n\r\n def __init__(self, alpha_pred, P_pred, alpha_filt, P_filt, y_pred, F_pred):\r\n \"\"\"Initialize with KF results\"\"\"\r\n self.alpha_pred = alpha_pred\r\n self.P_pred = P_pred\r\n self.alpha_filt = alpha_filt\r\n self.P_filt = P_filt\r\n self.y_pred = y_pred\r\n self.F_pred = F_pred\r\n\r\n def set_ks_res(self, alpha_sm, V, eps_hat, eps_var, eta_hat, eta_cov):\r\n \"\"\"Update to contain also KS results\"\"\"\r\n self.alpha_sm = alpha_sm\r\n self.V = V\r\n self.eps_hat = eps_hat\r\n self.eps_var = eps_var\r\n self.eta_hat = eta_hat\r\n self.eta_cov = eta_cov\r\n\r\n\r\ndef kalman_smoother(y, model: LGSS, kf: kfs_res):\r\n \"\"\"Kalman (state and disturbance) smoother for LGSS model with one-dimensional observation.\r\n\r\n :param y: (n,) array of observations. May contain nan, which encodes missing observations.\r\n :param model: LGSS object with the model specification.\r\n :parma kf: kfs_res object with result from a Kalman filter foward pass.\r\n\r\n :return kfs_res: Container class. The original Kalman filter result is augmented with the following member variables,\r\n alpha_sm: (d,1,n) array of smoothed state means.\r\n V: (d,d,n) array of smoothed state covariances.\r\n eps_hat: (n,) array of smoothed means of observation disturbances.\r\n eps_var: (n,) array of smoothed variances of observation disturbances.\r\n eta_hat: (deta,1,n) array of smoothed means of state disturbances.\r\n eta_cov: (deta,deta,n) array of smoothed covariances of state disturbances.\r\n \"\"\"\r\n d = model.d # State dimension\r\n deta = model.deta # Number of state noise components\r\n n = len(y)\r\n\r\n # Allocate memory, see DK (4.44)\r\n r = np.zeros((d, 1, n))\r\n N = np.zeros((d, d, n))\r\n alpha_sm = np.zeros((d, 1, n))\r\n V = np.zeros((d, d, n))\r\n\r\n # Disturbances\r\n eps_hat = np.zeros(n) # Observation noise\r\n eps_var = np.zeros(n)\r\n eta_hat = np.zeros((deta, 1, n)) # State noise\r\n eta_cov = np.zeros((deta, deta, n)) # State noise covariance\r\n\r\n # Get all model parameters (for brevity)\r\n T, R, Q, Z, H, a1, P1 = model.get_params()\r\n\r\n # Get the innovations and their variances from forward pass\r\n v = y - kf.y_pred\r\n F = kf.F_pred.copy()\r\n\r\n # Simple way of handling missing observations; treat them as present but with infinite variance!\r\n ind = np.isnan(v)\r\n v[ind] = 0.\r\n F[ind] = np.inf\r\n\r\n # Compute the \"L-matrices\", DKp87\r\n L = np.zeros((d, d, n))\r\n K = np.zeros((d, 1, n))\r\n for t in range(n):\r\n K[:, :, t] = kf.P_pred[:, :, t] @ Z.T / F[t] # Kalman gain (without the leading T that DK use)\r\n L[:, :, t] = T @ (np.identity(d) - K[:, :, t] @ Z)\r\n\r\n # Initialize. r and N are defined for t=0,...,n-1 in DK, whereas other quantities are defined for t=1,...,n.\r\n # Hence, alpha_sm[:,t-1] = \\hat alpha_{t} but r[t-1] = r_{t-1}.\r\n r[:, :, -1] = (Z.T / F[-1]) * v[-1]\r\n N[:, :, -1] = (Z.T / F[-1]) @ Z\r\n # This is actually an unnecessary computation, since we simply compute the filter estimates again\r\n # (= to smoother at time step t=n), but we keep them to agree with the algorithm in DK\r\n alpha_sm[:, :, -1] = kf.alpha_pred[:, :, -1] + kf.P_pred[:, :, -1] @ r[:, :, -1]\r\n V[:, :, -1] = kf.P_pred[:, :, -1] - kf.P_pred[:, :, -1] @ N[:, :, -1] @ kf.P_pred[:, :, -1]\r\n\r\n # Disturbances\r\n eps_hat[-1] = (H / F[-1]) * v[-1]\r\n eps_var[-1] = H - (H / F[-1]) * H\r\n eta_cov[:, :, -1] = Q\r\n\r\n for t in np.flip(range(n - 1)):\r\n # State smoothing\r\n r[:, :, t] = (Z.T / F[t]) * v[t] + L[:, :, t].T @ r[:, :, t + 1]\r\n N[:, :, t] = (Z.T / F[t]) @ Z + L[:, :, t].T @ N[:, :, t + 1] @ L[:, :, t]\r\n alpha_sm[:, :, t] = kf.alpha_pred[:, :, t] + kf.P_pred[:, :, t] @ r[:, :, t]\r\n V[:, :, t] = kf.P_pred[:, :, t] - kf.P_pred[:, :, t] @ N[:, :, t] @ kf.P_pred[:, :, t]\r\n\r\n # Disturbance smoothing\r\n eps_hat[t] = H * (v[t] / F[t] - K[:, :, t].T @ T.T @ r[:, :, t + 1])\r\n eps_var[t] = H - (H / F[t]) * H - H * K[:, :, t].T @ T.T @ N[:, :, t + 1] @ T @ K[:, :, t] * H\r\n eta_hat[:, :, t] = Q @ R.T @ r[:, :, t + 1]\r\n eta_cov[:, :, t] = Q - Q @ R.T @ N[:, :, t + 1] @ R @ Q\r\n\r\n kf.set_ks_res(alpha_sm, V, eps_hat, eps_var, eta_hat, eta_cov)\r\n\r\n return kf","sub_path":"Task2/tssltools_lab2.py","file_name":"tssltools_lab2.py","file_ext":"py","file_size_in_byte":5290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"19024659","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport tarfile\nimport numpy as np\nimport six\nfrom six.moves import cPickle as pickle\n\nfrom paddle.io import Dataset\nfrom paddle.dataset.common import _check_exists_and_download\n\n__all__ = ['Cifar10', 'Cifar100']\n\nURL_PREFIX = 'https://dataset.bj.bcebos.com/cifar/'\nCIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz'\nCIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a'\nCIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz'\nCIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85'\n\nMODE_FLAG_MAP = {\n 'train10': 'data_batch',\n 'test10': 'test_batch',\n 'train100': 'train',\n 'test100': 'test'\n}\n\n\nclass Cifar10(Dataset):\n \"\"\"\n Implementation of `Cifar-10 `_\n dataset, which has 10 categories.\n\n Args:\n data_file(str): path to data file, can be set None if\n :attr:`download` is True. Default None\n mode(str): 'train', 'test' mode. Default 'train'.\n transform(callable): transform to perform on image, None for on transform.\n download(bool): whether to download dataset automatically if\n :attr:`data_file` is not set. Default True\n\n Returns:\n Dataset: instance of cifar-10 dataset\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import paddle.nn as nn\n from paddle.vision.datasets import Cifar10\n from paddle.vision.transforms import Normalize\n\n class SimpleNet(paddle.nn.Layer):\n def __init__(self):\n super(SimpleNet, self).__init__()\n self.fc = nn.Sequential(\n nn.Linear(3072, 10),\n nn.Softmax())\n\n def forward(self, image, label):\n image = paddle.reshape(image, (3, -1))\n return self.fc(image), label\n\n paddle.disable_static()\n\n normalize = Normalize(mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5])\n cifar10 = Cifar10(mode='train', transform=normalize)\n\n for i in range(10):\n image, label = cifar10[i]\n image = paddle.to_tensor(image)\n label = paddle.to_tensor(label)\n\n model = SimpleNet()\n image, label = model(image, label)\n print(image.numpy().shape, label.numpy().shape)\n\n \"\"\"\n\n def __init__(self,\n data_file=None,\n mode='train',\n transform=None,\n download=True):\n assert mode.lower() in ['train', 'test', 'train', 'test'], \\\n \"mode should be 'train10', 'test10', 'train100' or 'test100', but got {}\".format(mode)\n self.mode = mode.lower()\n\n self._init_url_md5_flag()\n\n self.data_file = data_file\n if self.data_file is None:\n assert download, \"data_file is not set and downloading automatically is disabled\"\n self.data_file = _check_exists_and_download(\n data_file, self.data_url, self.data_md5, 'cifar', download)\n\n self.transform = transform\n\n # read dataset into memory\n self._load_data()\n\n def _init_url_md5_flag(self):\n self.data_url = CIFAR10_URL\n self.data_md5 = CIFAR10_MD5\n self.flag = MODE_FLAG_MAP[self.mode + '10']\n\n def _load_data(self):\n self.data = []\n with tarfile.open(self.data_file, mode='r') as f:\n names = (each_item.name for each_item in f\n if self.flag in each_item.name)\n\n for name in names:\n if six.PY2:\n batch = pickle.load(f.extractfile(name))\n else:\n batch = pickle.load(f.extractfile(name), encoding='bytes')\n\n data = batch[six.b('data')]\n labels = batch.get(\n six.b('labels'), batch.get(six.b('fine_labels'), None))\n assert labels is not None\n for sample, label in six.moves.zip(data, labels):\n self.data.append((sample, label))\n\n def __getitem__(self, idx):\n image, label = self.data[idx]\n if self.transform is not None:\n image = self.transform(image)\n return image, label\n\n def __len__(self):\n return len(self.data)\n\n\nclass Cifar100(Cifar10):\n \"\"\"\n Implementation of `Cifar-100 `_\n dataset, which has 100 categories.\n\n Args:\n data_file(str): path to data file, can be set None if\n :attr:`download` is True. Default None\n mode(str): 'train', 'test' mode. Default 'train'.\n transform(callable): transform to perform on image, None for on transform.\n download(bool): whether to download dataset automatically if\n :attr:`data_file` is not set. Default True\n\n Returns:\n Dataset: instance of cifar-100 dataset\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import paddle.nn as nn\n from paddle.vision.datasets import Cifar100\n from paddle.vision.transforms import Normalize\n\n class SimpleNet(paddle.nn.Layer):\n def __init__(self):\n super(SimpleNet, self).__init__()\n self.fc = nn.Sequential(\n nn.Linear(3072, 10),\n nn.Softmax())\n\n def forward(self, image, label):\n image = paddle.reshape(image, (3, -1))\n return self.fc(image), label\n\n paddle.disable_static()\n\n normalize = Normalize(mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5])\n cifar100 = Cifar100(mode='train', transform=normalize)\n\n for i in range(10):\n image, label = cifar100[i]\n image = paddle.to_tensor(image)\n label = paddle.to_tensor(label)\n\n model = SimpleNet()\n image, label = model(image, label)\n print(image.numpy().shape, label.numpy().shape)\n\n \"\"\"\n\n def __init__(self,\n data_file=None,\n mode='train',\n transform=None,\n download=True):\n super(Cifar100, self).__init__(data_file, mode, transform, download)\n\n def _init_url_md5_flag(self):\n self.data_url = CIFAR100_URL\n self.data_md5 = CIFAR100_MD5\n self.flag = MODE_FLAG_MAP[self.mode + '100']\n","sub_path":"python/paddle/vision/datasets/cifar.py","file_name":"cifar.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"212871053","text":"import math\n\n\n# /**\n# * Recursively score connect 4 position using negamax variant of alpha-beta algorithm.\n# * @param: alpha < beta, a score window within which we are evaluating the position.\n# *\n# * @return the exact score, an upper or lower bound score depending of the case:\n# * - if actual score of position <= alpha then actual score <= return value <= alpha\n# * - if actual score of position >= beta then beta <= return value <= actual score\n# * - if alpha <= actual score <= beta then return value = actual score\n# */\n\n\ndef negamax(agent, board, alpha, beta, num_steps):\n if num_steps == agent.max_depth: # give up if no solution\n return 0\n\n assert (alpha < beta)\n all_successors = agent.get_successors(board)\n for boardstate in all_successors:\n if boardstate[0].get_outcome() == agent.player:\n return (1000 + num_steps) # our player\n\n beta_max = math.inf # set upper bound\n if beta > beta_max:\n beta = beta_max # there is no need to keep beta above our max possible score.\n if alpha >= beta:\n return beta # prune the exploration if the [alpha;beta] window is empty.\n\n num_steps += 1\n\n for boardstate in all_successors: # compute the score of all possible next move and keep the best one\n # It's opponent turn in P2 position after current player plays x column.\n score = -negamax(agent, boardstate[0], -beta, -alpha, num_steps)\n if score >= beta:\n return score # prune\n if score > alpha:\n alpha = score # set alpha\n return alpha\n\n\nclass ValueColPair(object):\n def __init__(self, value, column):\n self.value = value\n self.column = column\n\n\ndef simple_heuristic(board, col):\n y = get_token_row(board, col)\n value = 0\n value += is_partial_line_at(board, col, y, 1, 0)\n value += is_partial_line_at(board, col, y, 0, 1)\n value += is_partial_line_at(board, col, y, 1, 1)\n value += is_partial_line_at(board, col, y, 1, -1)\n return value\n\n\ndef is_partial_line_at(board, x, y, dx, dy):\n \"\"\"Return True if a line of identical tokens exists starting at (x,y) in direction (dx,dy)\"\"\"\n # Avoid out-of-bounds errors\n total = 0\n if ((x + (board.n - 1) * dx >= board.w) or\n (y + (board.n - 1) * dy < 0) or (y + (board.n - 1) * dy >= board.h)):\n return 0\n # Get token at (x,y)\n t = board.board[y][x] # t is our player\n\n my_count = 0\n other_count = 0\n my_in_a_row = True\n other_in_a_row = True\n if t == 1:\n other = 2\n else:\n other = 1\n\n # Go through elements\n for i in range(1, board.n):\n curr_token = board.board[y + i * dy][x + i * dx]\n if my_in_a_row is True and curr_token == t:\n my_count += 1\n else:\n my_in_a_row = False\n\n if other_in_a_row is True and curr_token == other:\n other_count += 1\n else:\n other_in_a_row = False\n\n total = my_count + other_count - 1\n\n if other_count == board.n - 1: # if blocking an opponent's gamewinning move\n total = 500 + other_count # give blocking a move priority over everything else if not guaranteed win\n\n return total\n\n\ndef get_token_row(boardstate, col): # gets the token at the top of the column\n y = 0\n while boardstate.board[y][col] != 0 and y < boardstate.h - 1:\n y = y + 1\n return y\n","sub_path":"ConnectN/heuristics.py","file_name":"heuristics.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"365582231","text":"import os\nimport unittest\nimport random\nimport logging\nimport collections\n\nimport pytest\nimport testfixtures\n\nfrom pyvivado import project, signal, config, test_utils\n\nfrom pyvivado.hdl.tree import tree, tree_minimum, tree_maximum\n\n\nlogger = logging.getLogger(__name__)\n\nclass TestTree(unittest.TestCase):\n\n def default_test(self):\n test_tree(tree_name='maximum', n_inputs=3, width=4)\n\ncompare_functions = (\n ('minimum', lambda x, y: x < y),\n ('maximum', lambda x, y: x > y)\n)\n\ncombinations = []\nmsg_width = 11\nfor tree_name, compare_function in compare_functions:\n for n_inputs in range(1, 17):\n combinations.append((tree_name, n_inputs, msg_width))\n\n@pytest.mark.parametrize('tree_name,n_inputs,width', combinations)\ndef test_tree(tree_name, n_inputs, width):\n\n directory = os.path.join(\n config.hdldir, 'tree', 'proj_tree_{}_{}_{}'.format(tree_name, n_inputs, width))\n\n n_data = 100\n data = []\n maxvalue = pow(2, width)-1\n for i in range(n_data):\n values = [random.randint(0, maxvalue) for j in range(n_inputs)]\n data.append(values)\n\n # Make wait data. Sent while initialising.\n n_wait_lines = 20\n wait_data = []\n for wait_index in range(n_wait_lines):\n wait_data.append({\n 'i_data': 0,\n })\n\n # Make input and expected data\n input_data = []\n expected_data = []\n expected_indices = []\n for values in data:\n input_data.append({\n 'i_data': signal.list_of_uints_to_uint(values, width=width),\n })\n minval = None\n for i, v in enumerate(values):\n compare_function = dict(compare_functions)[tree_name]\n if ((minval is None) or \n compare_function(v, minval)):\n minval = v\n minindex = i\n expected_data.append(minval)\n expected_indices.append(minindex)\n input_data.append({\n 'i_data': 0,\n })\n\n interface = tree.get_tree_interface({\n 'width': width,\n 'n_inputs': n_inputs,\n 'tree_name': tree_name,\n 'module_name': 'tree_{}'.format(tree_name),\n 'builder_name': 'tree_{}'.format(tree_name),\n })\n\n output_data = test_utils.simulate(\n interface=interface, directory=directory,\n data=wait_data+input_data\n )[n_wait_lines: n_wait_lines+n_data]\n assert(len(expected_data) == n_data)\n assert(len(expected_indices) == n_data)\n o_data = [d['o_data'] for d in output_data]\n o_address = [d['o_address'] for d in output_data]\n testfixtures.compare(expected_data, o_data)\n testfixtures.compare(expected_indices, o_address)\n \nif __name__ == '__main__':\n test_utils.run_test(TestTree)\n","sub_path":"hdl/tree/qa_tree.py","file_name":"qa_tree.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"620214143","text":"# You seem to be doing great at your first job. You have now successfully completed the first 2 of your tasks and your\n# boss decides to give you as your next task something more challenging. You have to accept all the new products\n# coming in the bakery and finally gather some statistics.\n# You will be receiving key-value pairs on separate lines separated by \": \" until you receive the command \"statistics\".\n# Sometimes you may receive a product more than once. In that case you have to add the new\n# quantity to the existing one. When you receive the \"statistics\" command, print the following:\n# Products in stock:\n# - {product1}: {quantity1}\n# - {product2}: {quantity2}\n# …\n# Total Products: {count_all_products}\n# Total Quantity: {sum_all_quantities}\nstore = {}\ncommand = input()\nwhile not command == \"statistics\":\n command = command.split(\": \")\n item = command[0]\n quantity = int(command[1])\n if item not in store:\n store[item] = quantity\n else:\n store[item] += quantity\n command = input()\nprint(\"Products in stock:\")\nfor item, quantity in store.items():\n print(f\"- {item}: {quantity}\")\nprint(f\"Total Products: {len(store)}\")\nprint(f\"Total Quantity: {sum(store.values())}\")\n\n# # INPUT\n# bread: 4\n# cheese: 2\n# ham: 1\n# bread: 1\n# statistics\n# # OUTPUT\n# Products in stock:\n# - bread: 5\n# - cheese: 2\n# - ham: 1\n# Total Products: 3\n# Total Quantity: 8\n","sub_path":"FirstStepsInPython/Fundamentals/Lab/Dictionaries/03 Statistics.py","file_name":"03 Statistics.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"369112529","text":"def main():\n text = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'\n words = text.replace('.', '').split()\n tmp = [0, 4, 5, 6, 7, 8, 14, 18]\n d = {}\n \n for i, word in enumerate(words):\n if i in tmp:\n d[word[0]] = i+1\n else: \n d[word[:2]] = i+1\n\n for key, value in sorted(d.items(), key=lambda x: x[1]):\n print(value, key)\n\n\nif __name__ == '__main__':\n main()\n \n \n","sub_path":"chapter1/_04.py","file_name":"_04.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"95684457","text":"import math\n\nnumbers = []\ncount = 0\ntotal = 0\nmedian_index = 0\n\nwhile True:\n line = input(\"Enter a number or just Enter/Return to finish: \")\n if line:\n try:\n number = int(line)\n except ValueError as error:\n print(error)\n continue\n numbers.append(number)\n count += 1\n total += number\n else:\n break\n\nif count:\n minimum = numbers[0]\n maximum = numbers[0]\n for value in numbers:\n if value < minimum:\n minimum = value\n elif value > maximum:\n maximum = value\n numbers.sort()\n median_index = math.ceil(len(numbers) / 2)\n if len(numbers) % 2 != 0:\n median = numbers[median_index]\n else:\n median = (numbers[median_index] + numbers[median_index + 1]) / 2\n print(\"numbers: \", numbers)\n print(\"Count = \", count, \"Sum = \", total, \"Lowest = \", minimum, \"Highest = \", maximum, \"Mean = \", total / count, \"Median = \", median)\n","sub_path":"Chapter1/exercise5.py","file_name":"exercise5.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"579020264","text":"from os import listdir\nfrom os.path import isfile, join\nfrom collections import OrderedDict\n\noutput_file = \"refined_results.txt\"\noutput_latex = \"latex_results.txt\"\nonlyfiles = [f for f in listdir() if isfile(join(f)) and not f.endswith(\".py\")]\naverage = {}\ncorrectly = {}\n\nwith open(output_file,\"w\") as f:\n f.write(\"Results from all tests refines \\n\\nOrder of files:\\n\")\n for file in onlyfiles:\n if file != output_file and file != output_latex:\n f.write(str(file) + \"\\n\")\n f.write(\"\\n\\n\")\n\nwith open(output_latex,\"w\") as f:\n f.write(\"Latex compatible Table Results from all tests refines \\n\\n\")\n\nfor file in onlyfiles:\n if file != output_file and file != output_latex:\n with open(file, \"r\") as input_data:\n for line in input_data:\n if line.strip() == '=== Summary ===': # Or whatever test is needed\n break\n with open(output_file, \"a\") as output:\n with open(output_latex, \"a\") as latex:\n output.write(\"\\n\\n\" + str(file) + \" Results\\n\\n\" + line)\n latex.write((\"\\n\\n\" + str(file) + \" Results\\n\\n\" + line))\n\n for line in input_data:\n if line.strip() == \"=== Detailed Accuracy By Class ===\":\n break\n if len(line.split()) > 0 and line.split()[0] in [\"Correctly\",\"Incorrectly\"]:\n output.write(line)\n if line.split()[0] == \"Correctly\":\n correctly.update({file:line.split()[4]})\n\n for line in input_data: # This keeps reading the file\n if line.strip() == 'End':\n break\n wordlist = line.split()\n\n if len(wordlist) > 0 and wordlist[0] == \"Weighted\":\n average.update({file:line})\n latexline = \" & \".join(wordlist)\n if len(latexline) > 0: latexline += \"\\\\\\\\ \\hline \\n\"\n latex.write(latexline)\n output.write(line)\n\nwith open(output_file, \"a\") as output:\n with open(output_latex, \"a\") as latex:\n output.write(\"\\n\\nAverage Result from all files:\\n\\n\\t\\t\")\n latex.write(\"\\n\\nAverage Result from all files:\\n\\n\")\n output.write(\" TP Rate FP Rate Precision Recall F-Measure MCC ROC Area PRC Area\\n\")\n for key, values in sorted(average.items()):\n output.write(values.strip(\"\\n\") + \"\\t\" + key +\"\\n\")\n row = values.strip(\"\\n\").split()\n latex.write(\" & \".join(row)+\" & \"+key+\"\\n\")\n\n output.write(\"\\n\\nOrder of Correctly Classified\\n\\nPercentage\\tFilename\\n\")\n for key in sorted(correctly.keys(), key=lambda file: correctly[file], reverse=True):\n if len(key) < 7:\n tabs = \"\\t\\t\\t\"\n else:\n tabs = \"\\t\\t\"\n output.write(correctly[key] + \":\" + tabs + key+\"\\n\")\n\n\nprint(\"Conversion Complete, Files Generated\")\n","sub_path":"PythonCode/getresults.py","file_name":"getresults.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"346242261","text":"#\n# Copyright 2017 Red Hat Inc.\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\" Proton reactive API python core client module \"\"\"\n\nfrom __future__ import absolute_import, print_function, division\n\nimport time\n\nimport proton\nimport proton.reactor\nimport proton.handlers\n\nfrom cli_proton_python import utils\n\n\nclass CoreClient(proton.handlers.MessagingHandler):\n \"\"\" Proton reactive API python core client\n\n implements various support methods for sender, recevier and connector\n \"\"\"\n\n def __init__(self, opts, reactor_opts=None):\n \"\"\"\n CoreClient constructor\n\n :param opts: core client options\n :type opts: optparse.Values instance\n :param reactor_opts: reactor options\n :type reactor_opts: dict\n \"\"\"\n reactor_opts = reactor_opts or {}\n super(CoreClient, self).__init__(**reactor_opts)\n self.url = proton.Url(opts.broker_url)\n self.msg_total_cnt = None\n self.start_tm = time.time()\n self.opts = opts\n if getattr(opts, 'sync_mode', None) or getattr(opts, 'capacity', None):\n raise NotImplementedError(\"Options not implemented yet: 'sync_mode', 'capacity'\")\n self.auto_settle = reactor_opts.get('auto_settle', True)\n self.timeout = None\n self.next_task = None\n self.tearing_down = False\n self.msgs = []\n\n def parse_connection_options(self):\n \"\"\"\n Prepare options passed to container connect\n\n :return: connection options\n :rtype: dict\n \"\"\"\n\n conn_opts = {}\n if self.opts.conn_urls is not None:\n if not isinstance(self.opts.conn_urls, (str, list)):\n raise ValueError('Invalid conn-urls value, expected string or list: %s'\n % self.opts.conn_urls)\n if isinstance(self.opts.conn_urls, str):\n conn_opts['urls'] = self.opts.conn_urls.split(',')\n else:\n conn_opts['urls'] = self.opts.conn_urls\n if self.opts.conn_reconnect == 'false':\n conn_opts['reconnect'] = False\n elif (self.opts.conn_reconnect_interval\n or self.opts.conn_reconnect_limit\n or self.opts.conn_reconnect_timeout):\n conn_opts['reconnect'] = CustomBackoff(self.opts.conn_reconnect_interval,\n self.opts.conn_reconnect_limit or 99,\n self.opts.conn_reconnect_timeout)\n if self.opts.conn_heartbeat is not None:\n if not isinstance(self.opts.conn_heartbeat, int):\n raise ValueError('Invalid conn-heartbeat value, expected number: %s'\n % self.opts.conn_heartbeat)\n conn_opts['heartbeat'] = self.opts.conn_heartbeat\n if self.opts.conn_handler is not None:\n raise NotImplementedError(\"Option not implemented yet: 'conn_handler'\")\n if self.opts.conn_max_frame_size is not None:\n conn_opts['max_frame_size'] = self.opts.conn_max_frame_size\n if self.opts.conn_sasl_enabled == 'false':\n conn_opts['sasl_enabled'] = False\n if self.opts.conn_allowed_mechs is not None:\n conn_opts['allowed_mechs'] = self.opts.conn_allowed_mechs\n return conn_opts\n\n def parse_link_options(self):\n \"\"\"\n Prepare link options passed\n\n :return: link options\n :rtype: list\n \"\"\"\n link_opts = []\n if self.opts.link_at_least_once:\n link_opts.append(proton.reactor.AtLeastOnce())\n if self.opts.link_at_most_once:\n link_opts.append(proton.reactor.AtMostOnce())\n return link_opts\n\n def set_up_ssl_server_auth(self, event):\n \"\"\" set-up SSLDomain for the server verification\n\n | VERIFY_PEER: Require peer to provide a valid identifying certificate\n | VERIFY_PEER_NAME: Require valid certificate and matching name\n\n :param event: reactor event\n :type event: proton.Event\n \"\"\"\n if not self.opts.conn_ssl_trust_store:\n raise ValueError('trust store path needs to be given: %s'\n % self.opts.conn_ssl_trust_store)\n event.container.ssl.client.set_trusted_ca_db(self.opts.conn_ssl_trust_store)\n if self.opts.conn_ssl_verify_peer_name:\n event.container.ssl.client.set_peer_authentication(proton.SSLDomain.VERIFY_PEER_NAME)\n elif self.opts.conn_ssl_verify_peer:\n event.container.ssl.client.set_peer_authentication(proton.SSLDomain.VERIFY_PEER)\n\n def set_up_ssl_client_auth(self, event):\n \"\"\"\n sets-up SSLDomain for the client authentication\n\n :param event: reactor event\n :type event: proton.Event\n \"\"\"\n if not self.opts.conn_ssl_private_key:\n raise ValueError('client private key path needs to be given: %s'\n % self.opts.conn_ssl_private_key)\n event.container.ssl.client.set_credentials(self.opts.conn_ssl_certificate,\n self.opts.conn_ssl_private_key,\n self.opts.conn_ssl_password)\n\n def set_up_ssl(self, event):\n \"\"\"\n sets-up SSLDomain\n\n :param event: reactor event\n :type event: proton.Event\n \"\"\"\n if (self.opts.conn_ssl_trust_store\n or self.opts.conn_ssl_verify_peer_name\n or self.opts.conn_ssl_verify_peer):\n self.set_up_ssl_server_auth(event)\n if self.opts.conn_ssl_certificate:\n self.set_up_ssl_client_auth(event)\n\n def tear_down(self, event, settled=False):\n \"\"\"\n tears down and closes the connection\n\n :param event: reactor event\n :type event: proton.Event\n :param settled: indicates whether all messages has been explicitly settled\n :type settled: bool\n \"\"\"\n if self.auto_settle or settled:\n if self.next_task is not None:\n self.next_task.cancel()\n if self.timeout is not None:\n self.timeout.cancel()\n if self.opts.log_stats == 'endpoints':\n utils.dump_event(event)\n self.tearing_down = True\n time.sleep(self.opts.close_sleep)\n if event.receiver:\n event.receiver.close()\n if event.sender:\n event.sender.close()\n if event.connection:\n event.connection.close()\n\n def print_message(self, message):\n '''\n prints or store a message\n\n utils.print_message wrapper\n\n :param msg: message\n :type msg: proton.Message\n :param msg_format: pre-defined message format\n :type msg_format: str\n '''\n if self.opts.log_msgs == 'store':\n self.msgs.append(message)\n else:\n utils.print_message(message, self.opts.log_msgs)\n\n def get_messages(self):\n ''' returns list of stored messages '''\n return self.msgs\n\n def clear_messages(self):\n ''' clears list of stored messages '''\n self.msgs = []\n\n def set_delay_before(self):\n \"\"\"\n returns delay duration before sending a message (in seconds)\n\n :return: time to wait before message is sent/received\n :rtype: float\n \"\"\"\n if self.opts.duration != 0 and self.opts.duration_mode == 'before-send':\n return self.calculate_delay(self.msg_total_cnt, self.opts.duration)\n return 0\n\n def set_delay_after(self):\n \"\"\"\n returns delay duration after sending a message (in seconds)\n\n :return: time to wait after message is sent/received\n :rtype: float\n \"\"\"\n if self.opts.duration != 0 and self.opts.duration_mode == 'after-send':\n return self.calculate_delay(self.msg_total_cnt, self.opts.duration)\n return 0\n\n @staticmethod\n def calculate_delay(in_count, in_duration):\n \"\"\"\n calculates delay between sending/receiving messages used by shecduler when requested\n by duration option (uses logic from deprecated utils.sleep4next)\n\n :param in_count: number of messages to be sent/received\n :type in_count: int\n :param in_duration: send/receive process total execution time\n :type in_duration: int\n :return: computed time to wait before or after message is sent/received\n :rtype: float\n \"\"\"\n delay = 0.0\n if (in_duration > 0) and (in_count > 0):\n delay = 1.0 * in_duration / in_count\n return delay\n\n def on_transport_error(self, event):\n \"\"\"\n handler called when any error related to transport occurs\n\n .. seealso:: MessagingHandler::on_transport_error\n\n :param event: reactor event\n :type event: proton.Event\n \"\"\"\n if self.timeout is not None:\n self.timeout.cancel()\n\n\nclass CustomBackoff(proton.reactor.Backoff):\n \"\"\"\n a reconnect strategy involving an increasing delay between\n retries, up to a maximum or 60 seconds. This is a modified version\n supporting limit to the number of reconnect attempts before giving up.\n \"\"\"\n\n def __init__(self, interval=None, limit=None, timeout=None):\n \"\"\" CustomBackoff constructor\n\n :param interval: time interval between re-connect attempts\n :type interval: float\n :param limit:\n :type limit: int\n :param timeout:\n :type timeout: int\n \"\"\"\n super(CustomBackoff, self).__init__()\n self.failed = 0\n self.cumulative = 0\n self.interval = interval\n self.limit = limit or 0\n self.timeout = timeout or 0\n\n def reset(self):\n ''' resets the reconnect attempts counters '''\n self.failed = 0\n self.cumulative = 0\n super(CustomBackoff, self).reset()\n\n def next(self):\n '''\n implements the reconnect attempt action\n\n :return: next reconnect attempt delay time\n :rtype: float\n '''\n current = self.delay\n if current == 0:\n self.delay = self.interval or 0.1\n else:\n if self.interval is None:\n self.delay = min(60, 2 * current)\n self.failed += 1\n if self.limit and self.failed > self.limit:\n raise Exception('Failed to reconnect within defined %i attempts limit' % self.limit)\n if self.timeout and self.cumulative >= self.timeout:\n raise Exception('Failed to reconnect within defined %.f seconds timeout' % self.timeout)\n print('Connection error: reconnect attempt %i of %i, next in attempt: %.1f seconds'\n % (self.failed, self.limit, current))\n self.cumulative += current\n return current\n\n\nclass DelayedNoop(object): # pylint: disable=too-few-public-methods\n \"\"\" callback object that does nothing. \"\"\"\n\n def on_timer_task(self, _):\n \"\"\" empty event handler method\"\"\"\n pass\n\n\nclass ClientException(Exception):\n \"\"\" custom client exception class (just to know source of exception) \"\"\"\n\n def __init__(self, message):\n \"\"\"\n ClientException constructor\n\n :param message: exception text to be printed out\n :type message: str\n \"\"\"\n super(ClientException, self).__init__(message)\n\n\nclass ErrorsHandler(object): # pylint: disable=too-few-public-methods\n \"\"\" class to be used as universal errors handler for clients \"\"\"\n\n def __init__(self, conn_reconnect):\n \"\"\"\n ErrorsHandler Constructor\n\n :param conn_reconnect: indicates whether re-connect is enabled ('true' or 'false')\n :type conn_reconnect: str\n \"\"\"\n self.conn_reconnect = conn_reconnect\n\n def on_unhandled(self, name, event):\n \"\"\"\n Universal handler which sees all events when added as global handler to reactor.\n\n .. seealso::\n node_data/clients/python/receiver.py\n and node_data/clients/python/sender.py\n\n :param name: event name\n :type name: str\n :param event: event object\n :type event: proton.Event\n \"\"\"\n\n dlv = event.delivery\n # trx_declare_failed\n if ((dlv is not None)\n and (hasattr(event, \"transaction\"))\n and (event.transaction is not None)\n and (dlv == event.transaction._declare) # pylint: disable=protected-access\n and (dlv.remote_state == proton.Delivery.REJECTED)):\n raise ClientException(\"Transaction error: %s ...\" % \"Transaction declare failed\")\n\n # trx_failed\n if ((dlv is not None)\n and (hasattr(event, \"transaction\"))\n and (event.transaction is not None)\n and (dlv == event.transaction._discharge) # pylint: disable=protected-access\n and (dlv.remote_state == proton.Delivery.REJECTED)\n and (not event.transaction.failed)):\n raise ClientException(\"Transaction error: %s ...\" % \"Transaction failed\")\n\n # connection_err\n if ((name == \"on_connection_remote_close\")\n and event.connection.remote_condition):\n err_message = \"Connection error: %s ...\" \\\n % self._evaluate_endpoint_error(event.connection, \"connection\")\n if (\"AMQ119031\" in err_message\n or self.conn_reconnect == \"false\"):\n raise ClientException(err_message)\n else:\n utils.dump_error(err_message)\n\n # link_err\n if ((name == \"on_link_remote_close\")\n and event.link.remote_condition):\n raise ClientException(\"Link error: %s ...\"\n % self._evaluate_endpoint_error(event.link, \"link\"))\n\n # session_err\n if ((name == \"on_session_remote_close\")\n and event.session.remote_condition):\n raise ClientException(\"Session error: %s ...\"\n % self._evaluate_endpoint_error(event.session, \"session\"))\n\n # transport_err\n if name == \"on_transport_error\":\n err_message = \"Transport error: %s - %s\" % (\n event.transport.condition.name, event.transport.condition.description)\n if (\"authentication\" in event.transport.condition.description.lower()\n or self.conn_reconnect == \"false\"):\n raise ClientException(err_message)\n else:\n utils.dump_error(err_message)\n\n # select_err\n if name == \"on_selectable_error\":\n raise ClientException(\"Selector error: %s ...\" % \"Selectable error ...\")\n\n # delivery rejected err\n if (name == \"on_delivery\"\n and ((dlv is not None)\n and dlv.remote_state == proton.Delivery.REJECTED)):\n raise ClientException(\"Message delivery error: %s ...\" % \"REJECTED\")\n\n @staticmethod\n def _evaluate_endpoint_error(endpoint, endpoint_type):\n \"\"\"\n Evaluate endpoint errors and returns detailed description.\n\n :param endpoint: endpoint\n :type endpoint: proton.Endpoint\n :param endpoint_type: type of the endpoint\n :type endpoint_type: str\n :return: error message\n :rtype: str\n \"\"\"\n message = \"Unknown endpoint error ...\"\n if endpoint.remote_condition:\n message = endpoint.remote_condition.description or endpoint.remote_condition.name\n elif (endpoint.state & proton.Endpoint.LOCAL_ACTIVE\n and endpoint.state & proton.Endpoint.REMOTE_CLOSED):\n message = \"%s closed by peer\" % endpoint_type\n return message\n","sub_path":"cli_proton_python/coreclient.py","file_name":"coreclient.py","file_ext":"py","file_size_in_byte":16534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"188627801","text":"import matplotlib.pyplot as plt\nfrom RandomWalk_Modified import RandomWalk\nwhile True:\n\trw = RandomWalk(50000)\n\trw.fill_walk()\n\tpoint_numbers = list(range(rw.num_points))\n\tplt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap = plt.cm.Blues, edgecolor='none', s = 5)\n\t#emphasize the first and last points\n\tplt.scatter(0,0,c='green', edgecolor='none',s=100)\n\tplt.scatter(rw.x_values[-1], rw.y_values[-1],c='red',edgecolor='none',s=100)\n\t#remove the axes\n\tplt.axes().get_xaxis().set_visible(False)\n\tplt.axes().get_yaxis().set_visible(False)\n\t#show the plot\n\tplt.show()\n\t#set the size of the plotting window\n\tplt.figure(dpi=128, figsize=(20,12))\n\t#save figure\n\tplt.savefig(\"random_walk_plot.png\", bbox_inches = \"tight\")\n\t#ask users whether we should keep it running\n\tkeep_running = input('Make another walk? (y/n): ')\n\tif(keep_running == 'n'):\n\t\tbreak","sub_path":"2.data_visualization/random_walk_modified_visual.py","file_name":"random_walk_modified_visual.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"216638310","text":"# coding:utf-8\nimport csv\nimport logging\nimport hashlib\n\n# 去掉csv文件中,重复的行\ndef quchong(file):\n ciku = open(r'full.csv', 'r') # 打开需要去重文件,可自行修改\n xieci = open(r'full_1.csv', 'w') # 打开处理后存放的文件\n cikus = ciku.readlines()\n list2 = {}.fromkeys(cikus).keys() # 列表去重方法,将列表数据当作字典的键写入字典,依据字典键不可重复的特性去重\n i = 1\n for line in list2:\n if line[0] != ',':\n # print line[0:-1].decode('utf-8').encode('gbk') # 数据量太多,会出现编码报错。蛋疼\n # print u\"写入第:\" + i + u\" 个\"\n print()\n i += 1\n xieci.writelines(line)\n xieci.close()\n\n\n# 把列表或是dic转换成csv文件存储到当前脚本目录,列表里存的是json对象\ndef transform_to_csv(data, path):\n csvfile = open(path + '.csv', 'wb')\n writer = csv.writer(csvfile)\n if not data:\n logging.error(\"transform_to_csv->data:None\")\n return\n if isinstance(data, list):\n writer.writerow(data[0].keys())\n for item in data:\n writer.writerow(item.values())\n elif isinstance(data, dict):\n writer.writerow(data.keys())\n writer.writerow(data.values())\n csvfile.close()\n\n\ndef get_application_id_list(path):\n csvFile = open(path, \"r\")\n reader = csv.reader(csvFile)\n\n # 建立空字典\n result = []\n i = 0\n for item in reader:\n # 忽略第一行\n if reader.line_num == 1:\n continue\n i = i + 1\n if len(result) == 100:\n break\n if item[1] == 'jpg' or item[3] == 'jpeg':\n result.append(item[2])\n csvFile.close()\n print(len(result))\n print(result)\n\n# 读取csv文件中时间 item[1] 第二列\ndef get_application_id_list(path):\n csvFile = open(path, \"r\")\n reader = csv.reader(csvFile)\n\n # 建立空字典\n result = []\n i = 0\n for item in reader:\n # 忽略第一行\n if reader.line_num == 1:\n continue\n i = i + 1\n if item[1] == 'jpg' or item[3] == 'jpeg':\n result.append(item[2])\n csvFile.close()\n print(len(result))\n print(result)\n\nif __name__ == '__main__':\n # path = '/Users/liwenfeng/work/csv/collect_resume_new.csv'\n # get_application_id_list(path)\n path = '/Users/liwenfeng/work/hunter_domian.csv'\n # get_hunter_domain_from_csv(path)\n import request","sub_path":"csv/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"439155781","text":"# -*- coding : utf-8 -*-\n# @time : 2019-05-15 18:51\n# @Author : Zhicong Hu\n# @Studid : 29489636\n\n\n#构造一个节点的类 学习单链表\n\nclass Node:\n def __init__(self,x):\n self.val=x\n #当前值\n self.next=None\n #下一个节点的地址\n'''\nnode0=NodeList(0)\nnode1=NodeList(1)\nnode0.nextval=node1\nprint(node0.nextval) #打印的是下一个节点的地址\n'''\n\n#构造一个单链表\nclass SingleLink:\n def __init__(self,node=None):\n self._head=node #初始化链表,创建头部节点,默认头节点为用户传入的node或者None\n\n\n #判断是否为空\n def if_empty(self):\n return self._head==None\n\n #返回链表长度\n def length(self):\n # 指针\n\n cursor = self._head\n\n # count记录数量\n count = 0\n '''指针一开始就指在头节点,头节点算一个'''\n\n '''如果头节点None,说明第一个节点的地址不存在,没有第一个节点'''\n while cursor != None:\n count += 1\n cursor = cursor.next\n return count\n\n #遍历\n def travel(self):\n cursor=self._head\n while cursor!=None:\n print(cursor.val)\n cursor=cursor.next\n\n\n #添加头部元素\n def add(self,item):\n item.next=self._head\n self._head=item\n\n\n #添加尾部元素\n def append(self,item):\n cursor = self._head\n if self._head==None:\n self._head=item\n else:\n while cursor.next!=None:\n cursor=cursor.next\n item.next=None\n cursor.next=item\n\n\n\n\n #指定位置添加\n def insert(self,p,item):\n cur=self._head\n count=0\n #只有头节点的情况\n if self._head==None:\n item.next=None\n self._head=item\n\n #在头节点和第一节点之间的情况\n if p==1:\n item.next=cur.next\n self._head=item\n\n\n\n if p>1:\n while cur.next!=None:\n count+=1\n if count==p-1:\n break\n cur=cur.next\n item.next=cur.next\n cur.next=item\n #删除节点\n\n def pop(self,item):\n cursor = self._head\n '''1.空表情况'''\n if self.if_empty():\n print('EMPTY LIST')\n return False\n '''第一位情况'''\n if item==self._head:\n\n self._head=cursor.next\n\n else:\n\n while cursor!=None:\n if cursor.next == None:\n print(\"Value doesn't exist\")\n return False\n elif cursor.next.val==item.val:\n if cursor.next.next:\n cursor.next=cursor.next.next\n else:\n cursor.next=None\n break\n\n cursor=cursor.next\n\n\n\na=SingleLink(Node(100))\n\na.append(Node(2000))\na.append(Node(2001))\na.append(Node(2002))\na.append(Node(2003))\na.append(Node(2004))\na.insert(6,Node(-1000))\na.pop(Node(2005))\n\n\n","sub_path":"leetcode/234_listnode.py","file_name":"234_listnode.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"622230459","text":"def d(x): #define-se a função como o enunciado do problema\n a=0\n for g in range(1,int(x/2)+1):\n if x%g==0:\n a=a+g\n return(a)\n\nprint('calculando')\n\nw=0\nfor y in range(1,10001):\n if d(d(y))==y and d(y)!=y:\n w=w+y #para cada dupla amigável encontrada, soma-se apenas um dos números porque um número é amigável do outro. Assim, o\n #que não foi adicionado na primeira vez será adicionado quando novamente essa dupla for achada, dessa vez por causa do\n print(y) #segundo número\nprint('********')\nprint('soma:',w)\n","sub_path":"Project Euler/Project Euler 21 (rods).py","file_name":"Project Euler 21 (rods).py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"172551988","text":"__all__ = [\"GoogleDriveFSOpener\"]\n\nfrom fs.opener import Opener\nfrom google.oauth2.credentials import Credentials # pylint: disable=wrong-import-order\n\nfrom .googledrivefs import GoogleDriveFS\n\nclass GoogleDriveFSOpener(Opener): # pylint: disable=too-few-public-methods\n\tprotocols = ['googledrive']\n\n\tdef open_fs(self, fs_url, parse_result, writeable, create, cwd): # pylint: disable=too-many-arguments\n\t\tdirectory = parse_result.resource\n\n\t\tcredentials = Credentials(parse_result.params.get(\"access_token\"),\n\t\t\trefresh_token=parse_result.params.get(\"refresh_token\", None),\n\t\t\ttoken_uri=\"https://www.googleapis.com/oauth2/v4/token\",\n\t\t\tclient_id=parse_result.params.get(\"client_id\", None),\n\t\t\tclient_secret=parse_result.params.get(\"client_secret\", None))\n\t\tfs = GoogleDriveFS(credentials)\n\n\t\tif directory:\n\t\t\treturn fs.opendir(directory)\n\t\treturn fs\n","sub_path":"fs/googledrivefs/opener.py","file_name":"opener.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"21404091","text":"\"\"\"empty message\n\nRevision ID: 1efe014ad2de\nRevises: abcbf0a73cb2\nCreate Date: 2021-02-24 15:04:06.295842\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1efe014ad2de'\ndown_revision = 'abcbf0a73cb2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('board_like', sa.Column('user_id', sa.Integer(), nullable=False))\n op.drop_constraint('board_like_board_id_fkey', 'board_like', type_='foreignkey')\n op.drop_constraint('board_like_users_id_fkey', 'board_like', type_='foreignkey')\n op.create_foreign_key(None, 'board_like', 'board', ['board_id'], ['id'], ondelete='CASCADE')\n op.create_foreign_key(None, 'board_like', 'users', ['user_id'], ['id'], ondelete='CASCADE')\n op.drop_column('board_like', 'users_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('board_like', sa.Column('users_id', sa.INTEGER(), autoincrement=False, nullable=False))\n op.drop_constraint(None, 'board_like', type_='foreignkey')\n op.drop_constraint(None, 'board_like', type_='foreignkey')\n op.create_foreign_key('board_like_users_id_fkey', 'board_like', 'users', ['users_id'], ['id'])\n op.create_foreign_key('board_like_board_id_fkey', 'board_like', 'board', ['board_id'], ['id'])\n op.drop_column('board_like', 'user_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/1efe014ad2de_.py","file_name":"1efe014ad2de_.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"589684080","text":"\"\"\"\n给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 \"\" 。\n注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。\n\n输入:s = \"ADOBECODEBANC\", t = \"ABC\"\n输出:\"BANC\"\n\"\"\"\n\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n # 初始化\n left = 0\n start_index = 0\n end_index = 0\n length = 0\n window_dict = {}\n t_dict = {}\n for char in t:\n t_dict[char] = t_dict.setdefault(char, 0) + 1\n # 窗口滑动\n for i in range(len(s)):\n if s[i] in t_dict:\n window_dict[s[i]] = window_dict.setdefault(s[i], 0) + 1\n while self.is_valid(window_dict, t_dict) is True:\n if i - left + 1 < length or length == 0:\n length = i - left + 1\n start_index = left\n end_index = i + 1\n if s[left] in t_dict:\n window_dict[s[left]] -= 1\n # if window_dict[s[left]] == 0:\n # del window_dict[s[left]]\n left += 1\n return s[start_index:end_index]\n\n def is_valid(self, window_dict, t_dict):\n for k, v in t_dict.items():\n if k in window_dict.keys():\n if v <= window_dict[k]:\n continue\n else:\n return False\n else:\n return False\n return True\n\nclass Solution2:\n def minWindow(self, s: str, t: str) -> str:\n # 滑动窗口\n need, window = {}, {}\n for c in t:\n need[c] = need.setdefault(c, 0) + 1 # need = {字符:出现次数}\n\n left, right = 0, 0\n valid = 0 # 验证window是否满足need条件,valid表示满足条件的字符个数\n start, length = 0, len(s) + 1\n while right < len(s):\n c = s[right]\n right += 1\n if c in need: # 更新窗口数据\n window[c] = window.setdefault(c, 0) + 1\n if window[c] == need[c]:\n valid += 1\n while valid == len(need):\n if right - left < length: # 优化结果\n start = left\n length = right - left\n d = s[left]\n left += 1\n if d in need: # 更新窗口数据\n if window[d] == need[d]:\n valid -= 1\n window[d] -= 1\n return s[start:start + length] if length != len(s) + 1 else ''\n\n\nif __name__ == '__main__':\n test1 = \"ADOBECODEBANC\"\n test2 = \"ABC\"\n test = Solution()\n print('rst is :', test.minWindow(test1, test2))\n","sub_path":"sliding window/76最小覆盖子串.py","file_name":"76最小覆盖子串.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"73835083","text":"from typing import List\n\n\nclass Solution26:\n def removeDuplicates(self, nums: List[int]) -> int:\n if nums is None or not nums:\n return 0\n prev = nums[0]\n u_index = 0\n\n for i in range(1, len(nums)):\n num = nums[i]\n if num != prev:\n u_index += 1\n nums[u_index] = num\n prev = num\n\n return u_index + 1\n","sub_path":"Python/prob26.py","file_name":"prob26.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"68798605","text":"import media\nimport fresh_tomatoes\n\n# Set often used url formats for poster art and youtube url\nwikipedia_image = \"https://upload.wikimedia.org/wikipedia/en{}.jpg\"\nyoutube_url = \"https://www.youtube.com/watch?v={}\"\n\n# Initialize first BTTF movie\nbtf = media.Movie(\"Back to the Future\",\n \"In this 1980s sci-fi classic, a small-town California teen is thrown back into\"\n \" the '50s when an experiment by his eccentric scientist friend goes awry.\",\n wikipedia_image.format(\"/d/d2/Back_to_the_Future\"),\n youtube_url.format(\"qvsgGtivCgs\"))\n\n# Initialize second BTTF movie\nbtf2 = media.Movie(\"Back to the Future Part II\",\n \"In this zany sequel, the time-traveling duo return from saving Marty's \"\n \"future son from disaster, only to discover their own time transformed.\",\n wikipedia_image.format(\"/c/c2/Back_to_the_Future_Part_II\"),\n youtube_url.format(\"MdENmefJRpw\"))\n\n# Initialize third BTTF movie\nbtf3 = media.Movie(\"Back to the Future Part III\",\n \"In this final chapter, Marty obtains a 70-year-old message from his\"\n \" time-traveling friend, in which he informs Marty that he has retired\"\n \" to a small town in the Old West.\",\n wikipedia_image.format(\"/4/4e/Back_to_the_Future_Part_III\"),\n youtube_url.format(\"3C8c3EoEfw4\"))\n\n# Create array of movies, display each twice for some height to webpage\nback_to_the_futures = [btf, btf2, btf3, btf, btf2, btf3]\n# Ouput movies to html page and open page in web browser\nfresh_tomatoes.open_movies_page(back_to_the_futures)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"281488344","text":"import os, sys\nimport argparse\nimport numpy as np\nimport time\nimport torch\nimport torch.optim as optim\nfrom loss import LogManager, calc_gaussprob, calc_kl_vae, nllloss, calc_entropy, calc_err, l1loss, calc_entropy_log\nimport pickle\nimport model\nfrom itertools import combinations\nimport data_manager as dm\nimport json\n\ndef load_pickle(path):\n with open(path, 'rb') as f:\n return pickle.load(f)\n\ndef load_sp(feat_dir, num_mcep=36):\n feat_path = os.path.join(feat_dir, 'feats.p')\n with open(feat_path, 'rb') as f:\n sp, _, _, _, _ = pickle.load(f)\n return sp\n\ndef load_ppg(feat_dir, num_mcep=36):\n ppg_path = os.path.join(feat_dir, 'ppg{}.p'.format(num_mcep))\n with open(ppg_path, 'rb') as f:\n ppg = pickle.load(f)\n return ppg\n\ndef calc_parm_num(model):\n total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n return total_params\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_type', type=str) # VAE3 MD\n\nparser.add_argument('--seed', type=int, default=0)\n\nparser.add_argument('--model_dir', default='pretrainSI')\nparser.add_argument('--lr', type=float, default=1)\nparser.add_argument('--c_lr', type=float, default=2.5*1e-5)\n\nparser.add_argument('--lr_sch',type=str, default='linear15')\nparser.add_argument('--epochs',type=int, default=1000)\n\nparser.add_argument('--baseline',type=str, default='')\nparser.add_argument('--disentanglement', type=str, default='')\n\nargs = parser.parse_args()\nassert args.model_type in [\"VAE1\", \"VAE2\", \"VAE3\", \"MD\"]\n\nis_MD=True if args.model_type==\"MD\" else False\n\ntorch.manual_seed(args.seed)\ntorch.backends.cudnn.deterministic=True\ntorch.backends.cudnn.benchmark=False\nnp.random.seed(args.seed)\n\n\n# Data load\nSPK_LIST = ['VCC2SF1','VCC2SF2','VCC2SM1','VCC2SM2'] \n# SPK_LIST = ['F1','M1','F2','M2']\nTOTAL_SPK_NUM = len(SPK_LIST)\n\nPPG_DICT_TRAIN = {\n spk_id:load_ppg(os.path.join(\"data\",\"train\", spk_id)) \n for spk_id in SPK_LIST\n}\n\nPPG_DICT_DEV = {\n spk_id:load_ppg(os.path.join(\"data\",\"dev\", spk_id)) \n for spk_id in SPK_LIST\n}\n\nSP_DICT_TRAIN = {\n spk_id:load_sp(os.path.join(\"data\",\"train\", spk_id)) \n for spk_id in SPK_LIST\n}\n\nSP_DICT_DEV = dict()\nfor spk_id in SPK_LIST:\n sps = []\n for _, _, file_list in os.walk(os.path.join(\"data\", \"dev\", spk_id)):\n for file_id in file_list:\n utt_id = file_id.split(\".\")[0]\n if utt_id == \"ppg36\":\n continue\n file_path = os.path.join(\"data\", \"dev\", spk_id, file_id)\n _, coded_sp, f0, ap = load_pickle(file_path)\n sps.append(coded_sp)\n SP_DICT_DEV[spk_id]=sps\n\n# Model initilaization\nmodel_dir = args.model_dir\nos.makedirs(model_dir,exist_ok=True)\n\nlatent_dim=8\n\nlr = 1\nc_lr = args.c_lr\n\nbatch_size = 8\n\nepochs = args.epochs\n\ntotal_time = 0\n\nmin_dev_loss = 9999999999999999\nmin_epoch = 0\nd_epoch = 1\n\npre_vae = model.VAE(style_dim=TOTAL_SPK_NUM, latent_dim=latent_dim, vae_type=args.model_type)\npre_vae.load_state_dict(torch.load(args.baseline))\npre_vae.cuda()\npre_vae.eval()\n\nspk_C = model.LatentClassifier(latent_dim=latent_dim, label_num=TOTAL_SPK_NUM)\nspk_C.cuda()\nspk_C_opt = optim.Adam(spk_C.parameters(), lr=c_lr)\n# spk_C_sch = optim.lr_scheduler.LambdaLR(optimizer=spk_C_opt, lr_lambda=lambda epoch: c_lr*(-(1e-2/(epochs+1))*epoch+1e-2))\nprint(calc_parm_num(spk_C))\nprint(spk_C)\n\ntorch.save(spk_C.state_dict(), os.path.join(model_dir,\"si_{}.pt\".format(epochs)))\n\nlm = LogManager()\nlm.alloc_stat_type_list([\"train_loss\", \"train_acc\", \"dev_loss\", \"dev_acc\"])\n\nfor epoch in range(epochs+1):\n print(\"SI Epoch: {} LearningRate: {}\".format(epoch, spk_C_opt.param_groups[0]['lr']))\n\n lm.init_stat() \n\n spk_C.train()\n train_loader = dm.feat_loader_multiple(SP_DICT_TRAIN, batch_size, shuffle=True, ppg_dict=PPG_DICT_TRAIN)\n for self_idx, (coded_mcep, _), _, _ in train_loader:\n \n one_hot_self = dm.make_spk_vector(self_idx, TOTAL_SPK_NUM, batch_size, is_MD)\n \n total_loss = 0.0\n z_mu, z_logvar, z, x_prime_mu, x_prime_logvar, x_prime = pre_vae(x=coded_mcep,one_hot_src=one_hot_self, one_hot_tar=one_hot_self)\n \n # Latent Classifier\n self_vec = dm.make_spk_target(self_idx, batch_size, is_MD=False)\n predicted_self = spk_C(z)\n si_loss = nllloss(predicted_self, self_vec)\n si_err = calc_err(predicted_self, self_vec)\n\n spk_C_opt.zero_grad()\n si_loss.backward()\n spk_C_opt.step()\n\n lm.add_torch_stat(\"train_loss\", si_loss)\n lm.add_torch_stat(\"train_acc\", 1-si_err)\n\n print(\"Train:\", end=' ')\n lm.print_stat()\n\n lm.init_stat()\n spk_C.eval()\n dev_loader = dm.feat_loader_single(SP_DICT_DEV, batch_size, shuffle=True) \n for self_idx, coded_mcep in dev_loader:\n \n one_hot_self = dm.make_spk_vector(self_idx, TOTAL_SPK_NUM, batch_size, is_MD)\n \n total_loss = 0.0\n z_mu, z_logvar, z, x_prime_mu, x_prime_logvar, x_prime = pre_vae(x=coded_mcep,one_hot_src=one_hot_self, one_hot_tar=one_hot_self)\n \n # Latent Classifier\n self_vec = dm.make_spk_target(self_idx, batch_size, is_MD=False)\n predicted_self = spk_C(z)\n si_loss = nllloss(predicted_self, self_vec)\n si_err = calc_err(predicted_self, self_vec)\n\n lm.add_torch_stat(\"dev_loss\", si_loss)\n lm.add_torch_stat(\"dev_acc\", 1-si_err)\n \n print(\"DEV:\", end=' ')\n lm.print_stat()\n print(\".....................\")\n # spk_C_sch.step()\n\ntorch.save(spk_C.state_dict(), os.path.join(model_dir,\"si_{}.pt\".format(epochs)))\n","sub_path":"exp/si/pretrain_si_multiple.py","file_name":"pretrain_si_multiple.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"62800149","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom shiyanlougithub.items import ShiyanlougithubItem\n\nclass CoursesSpider(scrapy.Spider):\n name = 'courses'\n @property\n def start_urls(self):\n url_tmpl = 'https://github.com/shiyanlou?page={}&tab=repositories'\n return (url_tmpl.format(i) for i in range(1,5))\n def parse(self, response):\n for cangku in response.xpath('//li[@class=\"col-12 d-block width-full py-4 border-bottom public source\"]'):\n item = ShiyanlougithubItem({\n 'name':cangku.xpath('.//a/text()').re_first(\"\\n\\s*(.*)\"),\n 'update_time':cangku.xpath('.//div[@class=\"f6 text-gray mt-2\"]/relative-time/@datetime').extract_first()\n })\n yield item\n","sub_path":"courses.py","file_name":"courses.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"640351890","text":"from __future__ import print_function\n\nfrom flask import Flask, render_template\nfrom flask.ext.socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'not so secret'\nsocketio = SocketIO(app)\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\nregistered_users = set()\n\n@socketio.on('register')\ndef register_user(username):\n if not username or username in registered_users:\n emit('registered', False)\n return\n\n registered_users.add(username)\n emit('registered', True)\n emit('user enter',\n {'username': username, 'userlist': list(registered_users)},\n broadcast=True)\n\n@socketio.on('unregister')\ndef unregister_user(username):\n try:\n registered_users.remove(username)\n except KeyError:\n return # Ignore if aleady unregistered\n\n emit('user leave',\n {'username': username, 'userlist': list(registered_users)},\n broadcast=True)\n\n@socketio.on('message')\ndef receive_message(data):\n try:\n from_ = data['from']\n message = data['message']\n except:\n print('Got invalid message: \"{}\"'.format(data))\n return # Ignore invalid data\n\n emit('message', {'from': from_, 'message': message}, broadcast=True)\n\n\nif __name__ == '__main__':\n socketio.run(app)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"67376092","text":"from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound,\\\n Http404\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\nfrom customer.models import Customer, CustomerForm, SendEmailForm, EmailSent, EmailReceived\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.core.mail import send_mass_mail\n\nfrom django.views.generic import list_detail\n\n\n@login_required\ndef create_customer(request):\n return save_customer(request)\n\n@login_required\ndef edit_customer(request, customer_id):\n return save_customer(request, customer_id)\n\n@login_required\ndef save_customer(request, customer_id=0):\n data = {\n 'customer_id': customer_id\n }\n \n if customer_id:\n try:\n customer = Customer.objects.get(pk=int(customer_id))\n except Customer.DoesNotExist:\n return HttpResponseNotFound(\"

That customer doesn't seem to exist

\")\n else:\n customer = None\n \n if request.method == 'POST':\n form = CustomerForm(request.POST, instance=customer)\n \n if form.is_valid():\n form.save()\n \n messages.add_message(request, messages.SUCCESS, 'Customer saved successfully')\n return HttpResponseRedirect(\"/\")\n elif customer_id:\n form = CustomerForm(instance=customer)\n else:\n form = CustomerForm()\n \n if not customer_id:\n data['title'] = \"Create customer\"\n data['button_label'] = \"Create customer\"\n else :\n data['title'] = \"Edit customer\"\n data['button_label'] = \"Edit customer\"\n\n data['form'] = form\n\n return render_to_response(\"customer/templates/create.html\", data)\n\n@login_required\ndef delete_customer(request, customer_id):\n try:\n customer = Customer.objects.get(pk=int(customer_id))\n customer.delete()\n \n messages.add_message(request, messages.SUCCESS, \"Customer deleted successfully\")\n except Customer.DoesNotExist:\n messages.add_message(request, messages.ERROR, \"That customer doesn't exist\")\n\n return HttpResponseRedirect(\"/\")\n\n@login_required\ndef email_customers(request):\n data = {}\n \n if request.method == 'POST':\n form = SendEmailForm(request.POST)\n \n if form.is_valid():\n email_details = form.cleaned_data\n \n # retrieve the list of customers\n customer_list = Customer.objects.all()\n \n email_addresses = []\n \n for customer in customer_list:\n\n email_to = customer.email\n \n email_sent = EmailSent(\n subject= email_details[\"subject\"],\n email_from= email_details[\"from_email\"],\n email_to= email_to,\n content= email_details[\"message\"]\n )\n \n email_sent.save()\n email_addresses.append(email_to)\n \n datatuple = (email_details[\"subject\"], email_details[\"message\"], email_details[\"from_email\"], email_addresses)\n \n send_mass_mail((datatuple, ))\n\n messages.add_message(request, messages.SUCCESS, 'E-mails sent successfully')\n return HttpResponseRedirect(\"/\")\n else :\n form = SendEmailForm()\n \n data[\"form\"] = form\n \n return render_to_response(\"customer/templates/email.html\", data)\n\n@login_required\ndef email_details(request, email_id): \n email = get_object_or_404(EmailSent, pk=email_id)\n\n # Show the detail page\n return list_detail.object_detail(\n request,\n queryset = EmailSent.objects.all(),\n object_id = email_id,\n template_name = \"customer/templates/email_sent_details.html\",\n template_object_name = \"email\"\n )\n\n@login_required\ndef received_email_details(request, email_id):\n email = get_object_or_404(EmailReceived, pk=email_id)\n\n # Show the detail page\n return list_detail.object_detail(\n request,\n queryset = EmailReceived.objects.all(),\n object_id = email_id,\n template_name = \"customer/templates/email_received_details.html\",\n template_object_name = \"email\"\n )\n\ndef receive_email(request):\n return_value = \"0\" \n \n if request.method == 'POST':\n email_received = EmailReceived(\n email_to = request.POST['to'],\n email_from = request.POST['from'],\n subject = request.POST['subject'],\n content = request.POST['text']\n )\n \n email_received.save()\n \n return_value = \"1\" \n \n return HttpResponse(return_value)","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"322347852","text":"import pytest\n\nfrom basil.industry import facility as f\nfrom basil.market import prospect as p\nfrom tests import *\n\n\ndef test_myrmidon(mocker, system, prices, names):\n mocker.patch('basil.market.PRICES_FUNC', new=prices)\n mocker.patch('basil.market.NAMES_FUNC', new=names)\n mocker.patch('basil.market.VALUES_FUNC', return_value=35250667)\n\n blueprint = myrmidon_bp()\n facilities = [f.NPCStation('test station', system),\n f.MediumShipAssemblyArray('test pos', system)]\n prospect = p.prospect(blueprint, facilities)\n\n assert_that(prospect, has_length(2))\n assert_that(prospect[0], has_property('facility', instance_of(\n f.MediumShipAssemblyArray)))\n assert_that(prospect[1], has_property('facility', instance_of(\n f.NPCStation)))\n assert_that(prospect[0], has_property('cost_per_unit', less_than(\n prospect[1].cost_per_unit)))\n\n\n@pytest.fixture(scope=\"module\")\ndef prices():\n data = {34: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 4.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 34},\n 35: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 8.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 35},\n 36: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 32.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 36},\n 37: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 64.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 37},\n 38: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 128.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 38},\n 39: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 512.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 39},\n 40: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 1024.0},\n \"buy\": {\"max\": 6.29, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 40},\n 24700: {\"sell\": {\"max\": 11.14, \"avg\": 6.68, \"median\": 6.53,\n \"stddev\": 0.58, \"min\": 1024.0},\n \"buy\": {\"max\": 58000000, \"avg\": 5.96, \"median\": 6.17,\n \"stddev\": 0.81, \"min\": 2.01},\n \"updated_at\": \"2006-01-19T07:37:25Z\",\n \"system_id\": 30000142,\n \"recorded_at\": \"2006-01-19T07:37:25Z\", \"id\": 24701},\n }\n\n def get_price(key, name):\n return data[key]\n\n return get_price\n\n\n@pytest.fixture(scope=\"module\")\ndef names():\n data = {34: \"Tritanium\", 35: \"Pyerite\", 36: \"Mexallon\", 38: \"Nocxium\",\n 39: \"Zydrine\", 40: \"Megacyte\", 24700: \"Myrmidon\"}\n\n def get_name(key):\n return data[key]\n\n return get_name\n\n\n@pytest.fixture(scope=\"module\")\ndef system():\n root_url = 'https://public-crest.eveonline.com'\n system = {\"systemCostIndices\":\n [{\"costIndex\": 0.001603724208963802, \"activityID\": 8,\n \"activityID_str\": \"8\", \"activityName\": \"Invention\"},\n {\"costIndex\": 0.028218277926758743, \"activityID\": 1,\n \"activityID_str\": \"1\", \"activityName\": \"Manufacturing\"},\n {\"costIndex\": 0.02078652725944311, \"activityID\": 3,\n \"activityID_str\": \"3\",\n \"activityName\": \"Researching Time Efficiency\"},\n {\"costIndex\": 0.00545216917033242, \"activityID\": 4,\n \"activityID_str\": \"4\",\n \"activityName\": \"Researching Material Efficiency\"},\n {\"costIndex\": 0.00580479643586028, \"activityID\": 5,\n \"activityID_str\": \"5\", \"activityName\": \"Copying\"}],\n \"solarSystem\": {\"id_str\": \"32112312\",\n \"href\": root_url + \"/solarsystems/30011392/\",\n \"id\": 32112312, \"name\": \"TestSystem\"}}\n return system\n\n\ndef myrmidon_bp():\n return {\"skills\": [{\"typeID\": 3380, \"level\": 1}],\n \"materials\": [{\"typeID\": 34, \"quantity\": 3166667},\n {\"typeID\": 35, \"quantity\": 711111},\n {\"typeID\": 36, \"quantity\": 233333},\n {\"typeID\": 38, \"quantity\": 14444},\n {\"typeID\": 39, \"quantity\": 5556},\n {\"typeID\": 40, \"quantity\": 2666}],\n \"products\": [{\"typeID\": 24700, \"quantity\": 1}],\n \"time\": 15000, \"itemID\": 317301623, \"typeID\": 24701, \"flagID\": 63,\n \"locationID\": 648230613, \"typeName\": \"Myrmidon Blueprint\",\n \"quantity\": -1, \"timeEfficiency\": 16, \"materialEfficiency\": 10,\n \"runs\": -1, \"me\": 10, \"te\": 16}\n","sub_path":"tests/functional/market/test_prospect.py","file_name":"test_prospect.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"53604394","text":"import cv2 as cv\nimport matplotlib.pyplot as plt\n\nimg = cv.imread('Photos/park.jpg')\ncv.imshow('Cats', img)\n\n# BGR to Grayscale\n\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\ncv.imshow('gray', gray)\n\n# BGR to HSV\n\nhsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)\ncv.imshow('hsv', hsv)\n\n# BGR to L*a*b\n\nlab = cv.cvtColor(img, cv.COLOR_BGR2LAB)\ncv.imshow('lab',lab) \n\nplt.imshow(img)\nplt.show()\n\n# Grayscale to BGR (cant convert from gs to hsv -> gotta pass trough BGR)\n\nhsv_bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)\ncv.imshow('hsv to BGR', hsv_bgr)\n\n\n\n\ncv.waitKey(0)","sub_path":"Python/spaces.py","file_name":"spaces.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"63796036","text":"from sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.tree import export_graphviz\r\n\r\niris = load_iris()\r\n#注意输入的格式问题,否则会报错\r\nX = iris.data[0:10, 0:1]\r\ny = iris.data[0:10, 1:2]\r\n\r\ntree_reg = DecisionTreeRegressor(max_depth = 2)\r\ntree_reg.fit(X, y)\r\n\r\nexport_graphviz(\r\n tree_reg,\r\n out_file = \"E://机器学习经典模型//决策树//iris_tree_reg.dot\",\r\n filled=True\r\n)\r\n\r\nprint(tree_reg.predict([[1]]))","sub_path":"python/decision-making tree/Decisiontree_regress.py","file_name":"Decisiontree_regress.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"630037468","text":"import cv2\r\n\r\ndef recognition():\r\n cap = cv2.VideoCapture('C:\\\\Users\\\\Egemen\\\\Desktop\\\\cars.mp4')\r\n car_cascade = cv2.CascadeClassifier('C:\\\\Users\\\\Egemen\\\\Desktop\\\\Car Detection\\\\cars.xml')\r\n backsub = cv2.createBackgroundSubtractorMOG2(history=2000, varThreshold=16, detectShadows=False) \r\n frames = 0\r\n b = 1\r\n while True:\r\n flag, frame = cap.read()\r\n if flag:\r\n ret, frame = cap.read()\r\n\r\n if ret:\r\n fgmask = backsub.apply(frame, None, 0.1)\r\n im,contours, hierarchy = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\r\n try:\r\n hierarchy = hierarchy[0]\r\n except:\r\n hierarchy = []\r\n for contour, hier in zip(contours, hierarchy):\r\n (x,y,w,h) = cv2.boundingRect(contour)\r\n if w > 20 and h > 20:\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\r\n if x>50 and x<70:\r\n with open(\"lol.txt\", \"a\") as myfile:\r\n frames+=1\r\n a = str(frames) + \"\\n\"\r\n myfile.write(a) \r\n b+=1\r\n print(frames)\r\n myfile.close()\r\n\r\n cv2.putText(frame,\"# Of Cars: \"+str(frames), (220, 20), cv2.FONT_HERSHEY_SIMPLEX,0.6, (0, 0, 0), 2)\r\n cv2.imshow(\"Car Recognition\", frame)\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n cars = car_cascade.detectMultiScale(gray, 1.1, 3)\r\n\r\n\r\n #press Q on keyboard to exit\r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n break\r\n else:\r\n # The next frame is not ready, so we try to read it again\r\n # It is better to wait for a while for the next frame to be ready\r\n cv2.waitKey(1000)\r\n if cv2.waitKey(10) == 27:\r\n break\r\nrecognition()\r\n\r\n","sub_path":"BusLight-master/Car_Detection_YGA.py","file_name":"Car_Detection_YGA.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"613557146","text":"### Precisa do SymPy e do MpMath\r\nfrom decimal import Decimal\r\nfrom sympy import *\r\nimport os\r\nimport math\r\n\r\nmetodo = 0 # Seleção do método de integração\r\nindice = 0 # Para quarda o valor de i nos for's para mostrar caso não seja continua em i\r\ncontinuar = 'S' # Continuar S ou N\r\nmenu = 'N'\r\nx = symbols('x') # Definição de x como um símbolo\r\n\r\ndef clear():\r\n os.system('cls' if os.name == 'nt' else 'clear')\r\n\r\n###### Método dos Retângulos #####\r\n\r\ndef mtdRetangulo(a, b, n): # a = limite inferior, b = limite superior e n = subintervalos\r\n integral = 0\r\n base = Decimal(str(abs(b-a)/n)) # Base do retângulo\r\n inicio = Decimal(a) \r\n\r\n for i in range(n):\r\n inicio += base\r\n integral += (funcao2.evalf(subs={x:(inicio)}))*base # Soma a área de cada retângulo ao valor da integral\r\n indice = i\r\n return integral \r\n\r\n###### Método dos Trapézios #####\r\n\r\ndef mtdTrapezio(a, b, n): # a = limite inferior, b = limite superior e n = subintervalos\r\n integral = 0 \r\n base = Decimal(str(abs(b-a)/n)) # Base do Trapézio\r\n inicio = Decimal(a)\r\n \r\n for i in range(n):\r\n integral += (((funcao2.evalf(subs={x:(inicio)})) + funcao2.evalf(subs={x:(inicio+base)})) * base)/2\r\n inicio += base\r\n indice = i\r\n \r\n return integral\r\n\r\n###### Método de Simpson ######\r\n\r\ndef mtdSimpson(a,b,n):\r\n integral = 0\r\n base = Decimal(str(abs(b-a)/n))\r\n inicio = Decimal(a)\r\n\r\n for i in range(n+1):\r\n\r\n #Integral = (1/3)*((b-a)/n)(f(a) + f(b) + 2*f(X(2n)) + 4*(f(X(2n+1))\r\n if(inicio != a and inicio != b):\r\n if(i % 2 == 0): # Se Xi, com i par então então f(Xi)*2\r\n #print(\"f(\",inicio,\") 1=\",funcao2.evalf(subs={x:(inicio)})) #teste\r\n integral += ((2*base)/3)*(funcao2.evalf(subs={x:(inicio)})) # Soma dos valores em índices pares\r\n else: # Se Xi, com i impar então f(Xi)*4\r\n #print(\"f(\",inicio,\") 2=\",funcao2.evalf(subs={x:(inicio)})) #teste\r\n integral += ((4*base)/3)*(funcao2.evalf(subs={x:(inicio)})) # Soma dos Valores em índices ímpares\r\n \r\n elif (inicio == a): # X1\r\n #print(\"f(\",limite1,\") 3=\",funcao2.evalf(subs={x:(a)})) #teste\r\n integral += (base/3)*(funcao2.evalf(subs={x:(a)})) # Soma do primeiro valor\r\n \r\n elif (inicio == b): # Xn\r\n #print(\"f(\",limite2,\") 4=\",funcao2.evalf(subs={x:(b)})) #teste\r\n integral += (base/3)*(funcao2.evalf(subs={x:(b)})) # Soma do ultimo valor\r\n \r\n inicio += base\r\n indice = i\r\n return integral\r\n\r\n###################################\r\n\r\n\r\n\r\nwhile(continuar == 'S' or continuar == 's'):\r\n try:\r\n if(menu == 'n' or menu == 'N'):\r\n funcao = input(\"Entre com uma função continua para ser integrada f(x)= \") # Função\r\n limite1 = float(input(\"Informe o limite inferior: \")) # Limite inferior de integração\r\n limite2 = float(input(\"Informe o limite superior: \")) # Limite superior de integração\r\n subintervalos = int(input(\"Informe a quantidade de subintervalos: \")) # Quantidade de subintervalos\r\n if(subintervalos >0):\r\n clear() # Limpar a tela\r\n \r\n # Menu \r\n print(\"Deseja cálcular a integral definida de f(x)=\", funcao,\"de\",limite1,\"até\",limite2,\"usando qual método?\")\r\n print(\"(1) - MÉTODO DOS RETÂNGULOS\")\r\n print(\"(2) - MÉTODO DOS TRAPÉZIOS\")\r\n print(\"(3) - MÉTODO DE SIMPSON\")\r\n print(\"(4) - TODOS OS MÉTODOS\")\r\n metodo = int(input(\"Digite o número relacionado ao método: \")) # Escolha do método\r\n \r\n funcao2 = sympify(funcao) # Conversão da string para uma expressão algébrica usando o SymPy\r\n\r\n clear() # Limpar a tela\r\n \r\n if(metodo == 1):\r\n valorIntegral = mtdRetangulo(limite1, limite2, subintervalos)\r\n if(math.isinf(valorIntegral)):\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"não converge\")\r\n else:\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"é aproximadamente %.3f\" % valorIntegral)\r\n \r\n elif(metodo == 2): \r\n valorIntegral = mtdTrapezio(limite1, limite2, subintervalos)\r\n if(math.isinf(valorIntegral)):\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"não converge\")\r\n else:\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"é aproximadamente %.3f\" % valorIntegral)\r\n \r\n elif(metodo == 3):\r\n valorIntegral = mtdSimpson(limite1, limite2, subintervalos)\r\n if(math.isinf(valorIntegral)):\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"não converge\")\r\n else:\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"é aproximadamente %.3f\" % valorIntegral)\r\n \r\n elif(metodo == 4):\r\n valorIntegral = mtdRetangulo(limite1, limite2, subintervalos)\r\n valorIntegral1 = mtdTrapezio(limite1, limite2, subintervalos)\r\n valorIntegral2 = mtdSimpson(limite1, limite2, subintervalos)\r\n \r\n print(\"A integral da função f(x) =\",funcao,\"de\",limite1,\"até\",limite2,\"é aproximadamente:\")\r\n \r\n if(math.isinf(valorIntegral) or math.isinf(valorIntegral1) or math.isinf(valorIntegral2)): #Se o valor das integrais forem números infinitos\r\n print(\"A integral da função: f(x) =\", funcao,\"de\",limite1,\"até\",limite2, \"não converge\")\r\n else:\r\n print(\"Usando o método dos Retângulos = %.5f\" % valorIntegral)\r\n print(\"Usando o método dos Trapézios = %.5f\" % valorIntegral1)\r\n print(\"Usando o método de Simpson = %.5f\" % valorIntegral2)\r\n \r\n else:\r\n clear() # Limpar a tela \r\n print(\"Subintervalo inválido\")\r\n if(metodo != 4):\r\n print(\"\\n\\nDeseja calcular a integral de f(x)=\",funcao,\"de\",limite1,\"até\",limite2,\"usando outro método? (S/N):\")\r\n menu = input() \r\n if(menu == 'n' or menu == 'N'):\r\n continuar = input(\"\\n\\nDeseja calcular mais uma integral? (S/N): \")\r\n \r\n clear() # Limpar a tela \r\n except ZeroDivisionError:\r\n print(\"A função não é continua no intervalo [\",limite1,\",\",limite2,\"] em x = \",indice)\r\n except (RuntimeError, TypeError, NameError):\r\n print(\"Entrada inválida! \\nf(x) = \",funcao)\r\n\r\n\r\n \r\n\r\n\r\n \r\n","sub_path":"Projeto(console).py","file_name":"Projeto(console).py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"413643532","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\n\nfrom pybb import defaults, views, feeds\n\n\napp_name = \"pybb\"\n\n\nurlpatterns = [\n # Syndication feeds\n url('^feeds/posts/$',\n feeds.LastPosts(),\n name='feed_posts'),\n\n url('^feeds/topics/$',\n feeds.LastTopics(),\n name='feed_topics'),\n\n url('^$',\n views.IndexView.as_view(),\n name='index'),\n\n url('^forums/(?:(?P\\d+)/)?forums/create/$',\n views.ForumCreateView.as_view(),\n name='forum_create'),\n\n url('^forums/(?P\\d+)/moderators/$',\n views.ModeratorListView.as_view(),\n name='moderator_list'),\n url('^forums/(?P\\d+)/moderators/(?P\\d+)$',\n views.ModeratorDetailView.as_view(),\n name='moderator_detail'),\n url('^forums/(?P\\d+)/moderators/(?P\\d+)/delete/$',\n views.ModeratorDeleteView.as_view(),\n name='moderator_delete'),\n url('^forums/(?P\\d+)/moderators/create/$',\n views.ModeratorCreateView.as_view(),\n name='moderator_create'),\n url('^forums/update/(?P\\d+)/$',\n views.ForumUpdateView.as_view(),\n name='forum_update'),\n\n url('^topics/(?P\\d+)/stick/$',\n views.TopicStickView.as_view(),\n name='topic_stick'),\n url('^topics/(?P\\d+)/unstick/$',\n views.TopicUnstickView.as_view(),\n name='topic_unstick'),\n url('^topics/(?P\\d+)/close/$',\n views.TopicCloseView.as_view(),\n name='topic_close'),\n url('^topics/(?P\\d+)/open/$',\n views.TopicOpenView.as_view(),\n name='topic_open'),\n url('^topics/merge/$',\n views.TopicMergeView.as_view(),\n name='topic_merge'),\n url('^topics/move/$',\n views.TopicMoveView.as_view(),\n name='topic_move'),\n url('^topics/(?P\\d+)/delete/$',\n views.TopicDeleteView.as_view(),\n name='topic_delete'),\n url('^topics/delete/$',\n views.TopicsDeleteView.as_view(),\n name='topics_delete'),\n url('^topics/(?P\\d+)/poll-vote/$',\n views.TopicPollVoteView.as_view(),\n name='topic_poll_vote'),\n\n # Add topic/post\n url('^forums/(?:(?P\\d+)/)?topic/add/$',\n views.PostCreateView.as_view(),\n name='topic_create'),\n url('^topics/post/add/$',\n views.PostsCreateView.as_view(),\n name='posts_create'),\n url('^topics/(?P\\d+)/post/add/$',\n views.PostCreateView.as_view(),\n name='post_create'),\n url('^topics/(?P\\d+)/tracker/$',\n views.TopicTrackerRedirectView.as_view(),\n name='topic_tracker_redirect'),\n url('^topics/latest/$',\n views.TopicsLatestView.as_view(),\n name='topics_latest'),\n\n # Post\n url('^posts/redirect/(?:(?P\\d+)/)?$',\n views.PostRedirectView.as_view(),\n name='post_redirect'),\n url('^posts/(?P\\d+)/edit/$',\n views.PostUpdateView.as_view(),\n name='post_update'),\n url('^posts/(?P\\d+)/delete/$',\n views.PostDeleteView.as_view(),\n name='post_delete'),\n url('^posts/(?P\\d+)/moderate/$',\n views.PostModerateView.as_view(),\n name='post_moderate'),\n url('^posts/move/$',\n views.PostsMoveView.as_view(),\n name='post_move'),\n\n # Subscription\n url('^subscriptions/$',\n views.SubscriptionListView.as_view(),\n name='subscription_list'),\n\n url('^subscription/topic/change/$',\n views.SubscriptionChangeView.as_view(),\n name='subscription_change'),\n\n url('^subscription/topic/delete/$',\n views.SubscriptionDeleteView.as_view(),\n name='subscription_delete'),\n\n url('^subscription/topic/add/$',\n views.create_subscription,\n name='subscription_create'),\n\n url('^post/preview/$',\n views.post_preview,\n name='post_preview'),\n\n # Commands\n url('^forums/mark-as-read/$',\n views.ForumMarkAsReadView.as_view(),\n name='forum_mark_as_read'),\n\n url('^moderation/logs/$',\n views.LogModerationListView.as_view(),\n name='logmoderation_list'),\n\n url('^(?P[\\w\\-\\_]+)/posts/$',\n views.UserPostsView.as_view(),\n name='user_posts'),\n\n url('^(?P[\\w\\-\\_]+)/posts/delete/$',\n views.UserPostsDeleteView.as_view(),\n name='user_posts_delete'),\n\n url(views.TopicDetailView.url,\n views.TopicDetailView.as_view(),\n name='topic_detail'),\n\n url(views.ForumDetailView.url,\n views.ForumDetailView.as_view(),\n name='forum_detail'),\n]\n\nif defaults.PYBB_ATTACHMENT_ENABLE:\n urlpatterns += [\n url('^post/attachment/list/$',\n views.AttachmentListView.as_view(),\n name='attachment_list'),\n\n url('^post/attachment/(?P\\d+)/delete/$',\n views.AttachmentDeleteView.as_view(),\n name='attachment_delete'),\n ]\n","sub_path":"pybb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"595345262","text":"# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `combine.py`.\"\"\"\n\nfrom absl.testing import absltest\n\nimport chex\nimport jax.numpy as jnp\n\nfrom optax._src import combine\nfrom optax._src import transform\nfrom optax._src import update\n\n\nSTEPS = 50\nLR = 1e-2\n\n\nclass ComposeTest(chex.TestCase):\n\n def setUp(self):\n super().setUp()\n self.init_params = (jnp.array([1., 2.]), jnp.array([3., 4.]))\n self.per_step_updates = (jnp.array([500., 5.]), jnp.array([300., 3.]))\n\n @chex.all_variants()\n def test_chain(self):\n transformations = [\n transform.scale_by_adam(),\n transform.trace(decay=0, nesterov=False),\n transform.scale(-LR)]\n\n # Apply updates with chain.\n chain_params = self.init_params\n chained_transforms = combine.chain(*transformations)\n state = chained_transforms.init(chain_params)\n\n @self.variant\n def update_fn(updates, state):\n return chained_transforms.update(updates, state)\n\n for _ in range(STEPS):\n updates, state = update_fn(self.per_step_updates, state)\n chain_params = update.apply_updates(chain_params, updates)\n\n # Manually apply sequence of transformations.\n manual_params = self.init_params\n states = [t.init(manual_params) for t in transformations]\n for _ in range(STEPS):\n updates = self.per_step_updates\n new_states = []\n for t, s in zip(transformations, states):\n updates, state = t.update(updates, s)\n new_states.append(state)\n manual_params = update.apply_updates(manual_params, updates)\n states = new_states\n\n # Check equivalence.\n chex.assert_tree_all_close(manual_params, chain_params, rtol=1e-4)\n\n\nif __name__ == '__main__':\n absltest.main()\n","sub_path":"optax/_src/combine_test.py","file_name":"combine_test.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"304949452","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : Joshua\n@Time : 2018/9/5 15:51\n@File : proxy_crawler.py\n@Desc : 代理下载调度\n\"\"\"\n\nfrom gevent import monkey\nmonkey.patch_all()\n\nimport sys\nimport time\nimport gevent\n\nfrom gevent.pool import Pool\nfrom multiprocessing import Queue, Process, Value\n\nimport setting\nfrom spider.tools.utils import md5\n\nfrom proxy_htmldownloader import HtmlDownloader\nfrom proxy_htmlparser import HtmlParser\nfrom proxy_validator import Validator\nfrom proxy_sqlitedb import ProxySqliteDB\nfrom proxy_pipeline import SqlitePipeline\n\n\ndef start_proxycrawl(proxy_queue, db_proxy_num, myip):\n crawl = ProxyCrawl(proxy_queue, db_proxy_num, myip)\n crawl.run()\n\n\nclass ProxyCrawl(object):\n proxies = set()\n\n def __init__(self, proxy_queue, db_proxy_num, myip):\n self.crawl_pool = Pool(setting.THREADNUM)\n self.queue = proxy_queue\n self.db_proxy_num = db_proxy_num\n self.myip = myip\n\n def run(self):\n while True:\n self.proxies.clear()\n str_ = 'Starting crawl proxy!'\n sys.stdout.write(str_ + \"\\r\\n\")\n sys.stdout.flush()\n proxylist = ProxySqliteDB.get_all()\n\n spawns = []\n for proxy in proxylist:\n spawns.append(gevent.spawn(Validator.detect_from_db, self.myip, proxy, self.proxies))\n if len(spawns) >= setting.MAX_CHECK_CONCURRENT_PER_PROCESS:\n gevent.joinall(spawns)\n spawns= []\n gevent.joinall(spawns)\n self.db_proxy_num.value = len(self.proxies)\n str_ = 'IPProxyPool----->>>>>>>>db exists ip:%d' % len(self.proxies)\n\n if len(self.proxies) < setting.MINNUM:\n str_ += '\\r\\nIPProxyPool----->>>>>>>>now ip num < MINNUM, start crawling...'\n sys.stdout.write(str_ + \"\\r\\n\")\n sys.stdout.flush()\n spawns = []\n for p in setting.parserList:\n spawns.append(gevent.spawn(self.crawl, p))\n if len(spawns) >= setting.MAX_DOWNLOAD_CONCURRENT:\n gevent.joinall(spawns)\n spawns= []\n gevent.joinall(spawns)\n else:\n str_ += '\\r\\nIPProxyPool----->>>>>>>>now ip num meet the requirement,wait UPDATE_TIME...'\n sys.stdout.write(str_ + \"\\r\\n\")\n sys.stdout.flush()\n\n time.sleep(setting.UPDATE_TIME)\n\n def crawl(self, parser):\n html_parser = HtmlParser()\n for url in parser['urls']:\n response = HtmlDownloader.download(url)\n if response is not None:\n proxylist = html_parser.parse(response, parser)\n if proxylist is not None:\n for proxy in proxylist:\n proxy_str = '%s:%s' % (proxy['ip'], proxy['port'])\n proxy['proxy_id'] = md5(proxy_str)\n if proxy_str not in self.proxies:\n self.proxies.add(proxy_str)\n while True:\n if self.queue.full():\n time.sleep(0.1)\n else:\n self.queue.put(proxy)\n break\n\nif __name__ == \"__main__\":\n DB_PROXY_NUM = Value('i', 0)\n q1 = Queue()\n q2 = Queue()\n p0 = Process(target=start_api_server)\n p1 = Process(target=start_proxycrawl, args=(q1, DB_PROXY_NUM))\n p2 = Process(target=Validator.validator, args=(q1, q2))\n p3 = Process(target=SqlitePipeline.save_data, args=(q2, DB_PROXY_NUM))\n\n p0.start()\n p1.start()\n p2.start()\n p3.start()","sub_path":"spider/strong_spider/spider/antispider/proxypool/proxy_crawler.py","file_name":"proxy_crawler.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"465636378","text":"from model import A2C\nfrom agent import Agent\nfrom wrappers import GymEnvVec\nfrom experience import ExperienceSourceFirstLast, unpack_batch\nfrom common import RewardTracker\n\nimport numpy as np \nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch as T\nimport ptan\nimport gym\n\nfrom itertools import count\nfrom torch.utils.tensorboard import SummaryWriter\nfrom collections import namedtuple\n\n\n\nTotalReward = namedtuple(\"TotalReward\", field_names=\"reward\")\n\ndef data_func(net, device, train_queue, batch_size, entropy_beta, \n env_name, n_envs, gamma, reward_steps, **kwargs):\n\n env = GymEnvVec(env_name, n_envs)\n agent = Agent(net, batch_size, entropy_beta)\n exp_source = ExperienceSourceFirstLast(env, agent, gamma, reward_steps)\n\n for exp in exp_source:\n new_rewards = exp_source.pop_total_reward()\n if new_rewards:\n train_queue.put(TotalReward(reward=np.mean(new_rewards)))\n train_queue.put(exp)\n\ndef main():\n \"\"\"\n A3C - Data Parallelism : Agent_0 interacts with Agent_i, for i > 0. Agent_0\n doesn't choose actions or interact with the environments. He will just learn.\n Agent_i will interact with the environments and choose actions. Some information\n are exchange between Agent_0 and Agent_i. \n \"\"\"\n import ipdb; ipdb.set_trace()\n mp.set_start_method(\"spawn\")\n\n #ctx = mp.get_context(\"spawn\")\n \n HYPERPARAMS = {\n \"breakout\": {\n #\"env_name\": \"BreakoutNoFrameskip-v4\",\n \"env_name\": \"PongNoFrameskip-v4\",\n \"gamma\": 0.99, \n \"learning_rate\": 0.003,\n \"entropy_beta\": 0.03,\n \"batch_size\": 32,\n \"n_envs\": 10,\n \"process_count\": 4,\n \"reward_steps\": 4,\n \"stop_reward\": 500,\n \"adam_eps\": 1e-3,\n }\n }\n\n params = HYPERPARAMS[\"breakout\"]\n\n device = T.device(\"cuda\" if T.cuda.is_available() else \"cpu\")\n writer = SummaryWriter(\"run\")\n\n make_env = lambda: ptan.common.wrappers.wrap_dqn(gym.make(params[\"env_name\"]))\n\n env = make_env()\n net = A2C(env.observation_space.shape, env.action_space.n)\n net.share_memory()\n\n agent = Agent(net, params[\"batch_size\"], params[\"entropy_beta\"])\n \n optimizer = optim.Adam(net.parameters(), lr=params[\"learning_rate\"], eps=params[\"adam_eps\"])\n\n train_queue = mp.Queue(maxsize=params[\"process_count\"])\n data_proc_list = []\n \n for _ in range(params[\"process_count\"]):\n data_proc = mp.Process(target=data_func, \n args=(net, device, train_queue), \n kwargs={**params})\n data_proc.start()\n data_proc_list.append(data_proc)\n \n batch = []\n step = 0\n \n try:\n with RewardTracker(writer, params[\"stop_reward\"]) as tracker:\n while True:\n train_entry = train_queue.get()\n if isinstance(train_entry, TotalReward):\n if tracker.reward(train_entry.reward, step):\n break\n continue\n \n step += 1\n batch.append(train_entry)\n if len(batch) < params[\"batch_size\"]:\n continue\n \n batch_args = unpack_batch(batch, net, params[\"gamma\"], params[\"reward_steps\"], device)\n batch.clear()\n \n optimizer.zero_grad()\n agent.learn(step, *batch_args, optimizer)\n \n finally:\n for p in data_proc_list:\n p.terminate()\n p.join()\n \nif __name__ == \"__main__\":\n mp.set_start_method(\"spawn\")\n main()","sub_path":"Discrete_Actor_Critic/Breakout_A3C/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"301275943","text":"from matplotlib import pyplot as plt\nimport os\n\nfrom bounding_box import BoundingBox\nfrom map_handler import get_tomtom_map_raster_image\n\n\ndef get_bounding_box(X):\n min_lat = min(X[:, 0])\n max_lat = max(X[:, 0])\n min_lon = min(X[:, 1])\n max_lon = max(X[:, 1])\n\n bbox = BoundingBox(min_lon=min_lon - 0.05*(max_lon-min_lon),\n min_lat=min_lat - 0.05*(max_lat-min_lat),\n max_lon=max_lon + 0.05*(max_lon-min_lon),\n max_lat=max_lat + 0.05*(max_lat-min_lat))\n\n return bbox\n\n\ndef get_latlon_aspect_ratio(bbox):\n return (bbox.max_lat - bbox.min_lat) / (bbox.max_lon - bbox.min_lon)\n\n\ndef get_image_aspect_ratio(image):\n return image.shape[0] / image.shape[1]\n\n\ndef get_background_map_image_and_bounding_box(X):\n try:\n # Fetch map using TomTom Maps API\n bbox = get_bounding_box(X)\n background_image = get_tomtom_map_raster_image(bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat)\n except OSError as e:\n # Alternatively, use the offline version\n print('Error: \"{}\"; using pre-fetched image...'.format(e))\n bbox = BoundingBox(20.39, 44.78, 20.52, 44.84)\n background_image = plt.imread('staticimage.png')\n\n return background_image, bbox\n\n\ndef draw_background_map(X, ax):\n background_image, bbox = get_background_map_image_and_bounding_box(X)\n latlon_aspect = get_latlon_aspect_ratio(bbox)\n im_aspect = get_image_aspect_ratio(background_image)\n ax.imshow(background_image, extent=[bbox.min_lon, bbox.max_lon, bbox.min_lat, bbox.max_lat], zorder=0,\n aspect=1 / latlon_aspect * im_aspect, alpha=0.5)\n\n\ndef draw_clusters(X, labels, ax):\n # show clusters\n marker = ['x', 'o', 'v', '^', '+']\n color = ['k', 'r', 'g', 'b', 'y', 'm', 'c']\n\n min_cluster = min(labels)\n max_cluster = max(labels)\n for label in range(min_cluster, max_cluster+1):\n msk = (labels == label)\n cluster_points = [X[i] for i in range(len(msk)) if msk[i] == 1]\n lats = [x[0] for x in cluster_points]\n lons = [x[1] for x in cluster_points]\n ax.scatter(lons, lats, c=color[label % len(color)], marker=marker[label // len(color) % len(marker)], zorder=1,\n label='noise' if label<0 else None)\n if min_cluster < 0:\n ax.legend()\n\n\ndef save_figure(fig, ax):\n fig.set_size_inches(13.5, 9.75, forward=True)\n template_filename = 'clusters_plot_{}.png'\n i = 0\n while os.path.exists(template_filename.format(i)):\n i += 1\n for item in ax.get_xticklabels() + ax.get_yticklabels():\n item.set_fontsize(8)\n plt.savefig(template_filename.format(i), dpi=400, bbox_inches='tight')\n\n\ndef draw_map_with_clusters(X, labels):\n fig, ax = plt.subplots()\n draw_background_map(X, ax)\n draw_clusters(X, labels, ax)\n\n # save_figure(fig, ax)\n\n plt.show()\n","sub_path":"drawing_functions.py","file_name":"drawing_functions.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"502166153","text":"from django.shortcuts import get_object_or_404, render\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.http import HttpResponse\nfrom . models import *\n\ndef index(request):\n rents = RentPlace.objects.order_by('-date_published').filter(is_published=True)\n paginator = Paginator(rents, 3)\n page = request.GET.get('page')\n paged_rents = paginator.get_page(page)\n\n district_choices = District.objects.all()\n payment_choice = PaymentMode.objects.all()\n\n context = {\n 'rents': paged_rents,\n }\n \n return render(request, 'pages/renting.html', context)\n\ndef rent(request, rent_id):\n rent = get_object_or_404(RentPlace, pk=rent_id)\n context = {\n 'rent': rent\n }\n return render(request, 'pages/renting_place.html', context)\n","sub_path":"renting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"454191188","text":"import re\nimport os\nimport hashlib\nimport time\n\nfrom simplecacher.streamer import Streamer\nfrom simplecacher.sclogger import SCLogger\nfrom simplecacher.config import Config\n\n\nclass Cacher(object):\n\n CACHE_OBJECT_ID_MODE_PATH = 0\n CACHE_OBJECT_ID_MODE_FILENAME = 1\n\n CACHE_OBJECT_ID_MODES = {\n 'path': CACHE_OBJECT_ID_MODE_PATH,\n 'filename': CACHE_OBJECT_ID_MODE_FILENAME\n }\n\n def __init__(self, *args, **kwargs):\n super(Cacher, self).__init__(*args, **kwargs)\n\n self.re_allowed_exts = []\n self.re_allowed_urls = []\n\n self.cache_enable = int(Config.cache.enable)\n\n if not self.cache_enable:\n self.cache_data = self.cache_data_disable\n SCLogger.cache.info('Cache is disabled')\n else:\n self.compile_allowed_exts()\n self.compile_allowed_urls()\n\n if not os.path.isdir(Config.cache.object_path):\n os.makedirs(Config.cache.object_path)\n\n self.cache_compute_mode = self.CACHE_OBJECT_ID_MODES[\n Config.cachecompute.mode]\n\n self.validity_seconds = int(Config.cache.validity_seconds)\n\n def cache_data_disable(self, host, path, response, **kwargs):\n return self.cache_bypass(response)\n\n def cache_data(self, host, path, response, filesize=-1):\n \"\"\"\n Cache prepare data caching.\n\n Based on the mode, a sha256 sum is used to store data on disk.\n\n FIXME: incomplete download will be sent if the same file is asked.\n \"\"\"\n cache_allowed = self.check_cache_allowed(host, path)\n if not cache_allowed:\n SCLogger.cache.debug('Not allowed: {0}{1}'.format(host, path))\n return self.cache_bypass(response)\n else:\n cached_file_path = self.get_cache_filepath(host, path)\n cache_file_path_tmp = self.get_cache_filepath(host, path) + '.tmp'\n cached = self.check_cached_data(\n cached_file_path, filesize=filesize)\n\n if cached:\n cache_hit = True\n SCLogger.cache.info('Hit: {0}{1}'.format(host, path))\n streamer = Streamer.data_cached_streamer(cached_file_path)\n else:\n cache_hit = False\n SCLogger.cache.info('Miss: {0}{1}'.format(host, path))\n streamer = Streamer.data_cacher_streamer(\n response, cache_file_path_tmp)\n\n return cache_hit, cached_file_path, streamer\n\n def complete_cache_data(self, cached_file_path, filesize):\n if self.check_cached_data(cached_file_path + '.tmp', filesize):\n os.rename(cached_file_path + '.tmp', cached_file_path)\n return True\n return False\n\n def cache_bypass(self, response):\n cache_hit = False\n cached_file_path = None\n streamer = Streamer.data_direct_streamer(response)\n return cache_hit, cached_file_path, streamer\n\n def get_cache_filepath(self, host, path):\n if self.cache_compute_mode == Cacher.CACHE_OBJECT_ID_MODE_FILENAME:\n opath = os.path.basename(path)\n else:\n opath = path\n\n if os.path.isabs(opath):\n opath = os.path.curdir + opath\n\n if int(Config.cachecompute.with_host):\n opath = os.path.join(host, opath)\n\n opath = os.path.normpath(opath)\n\n if int(Config.cachecompute.hash_filename):\n opath = hashlib.sha256(\n opath.encode('utf-8')).hexdigest() + '.cache'\n else:\n fpath = os.path.dirname(opath)\n fname = os.path.basename(opath)\n cfpath = os.path.join(Config.cache.object_path, fpath)\n if not os.path.exists(cfpath):\n os.makedirs(cfpath)\n opath = os.path.join(fpath, fname)\n\n opath = os.path.normpath(opath)\n\n SCLogger.cache.debug('Relative object path: {0}'.format(opath))\n\n cached_file_path = os.path.abspath(\n os.path.join(Config.cache.object_path, opath)) + '.cache'\n\n SCLogger.cache.debug('Final object path: {0}'.format(cached_file_path))\n\n return cached_file_path\n\n def check_cache_allowed(self, host, path):\n \"\"\"\n Check if resource is eligible for caching.\n \"\"\"\n if self.check_cache_exts(host, path):\n return True\n elif self.check_cache_urls(host, path):\n return True\n\n return False\n\n def check_cache_exts(self, host, path):\n for allowed_re in self.re_allowed_exts:\n m = allowed_re.match(path)\n if m:\n return True\n return False\n\n def compile_allowed_exts(self):\n allowed_exts = Config.cache.allowed_ext.split(' ')\n for allowed_ext in allowed_exts:\n rer = r'^.*\\.{0}$'.format(allowed_ext)\n r = re.compile(rer)\n self.re_allowed_exts.append(r)\n SCLogger.cache.debug('Added allowed ext re: {0}'.format(rer))\n\n def compile_allowed_urls(self):\n if os.path.isfile(Config.cache.allowed_urls):\n lists = [Config.cache.allowed_urls]\n else:\n lists = os.listdir(Config.cache.allowed_urls)\n\n for urllist in lists:\n with open(urllist, 'r') as furllist:\n for url in furllist:\n url = url.replace('\\n', '').replace('\\r', '')\n self.re_allowed_urls.append(re.compile(url))\n SCLogger.cache.debug(\n 'Added allowed url re: {0}'.format(url))\n\n def check_cache_urls(self, host, path):\n for allowed_re in self.re_allowed_urls:\n m = allowed_re.match('{0}{1}'.format(host, path))\n if m:\n return True\n return False\n\n def remove_cached_data(self, cached_file_path, reason=None):\n if reason:\n SCLogger.cache.debug(\n 'Remove: {0}: {1}'.format(reason, cached_file_path))\n else:\n SCLogger.cache.debug('Remove: {0}'.format(cached_file_path))\n os.remove(cached_file_path)\n\n def check_cached_data(self, cached_file_path, filesize=-1):\n # if file isn't present\n if not os.path.isfile(cached_file_path):\n return False\n\n # if file is present but we dont have validity time\n if self.validity_seconds == 0:\n return True\n\n # if file is present and we have validity time\n stat = os.stat(cached_file_path)\n if time.time() - stat.st_mtime > self.validity_seconds:\n self.remove_cached_data(cached_file_path, reason='outdated')\n return False\n\n # check if the file size is ok\n if filesize > -1:\n cached_size = os.stat(cached_file_path).st_size\n if cached_size == filesize:\n return True\n else:\n self.remove_cached_data(\n cached_file_path, reason='wanted {0} but got {1} bytes'.format(filesize, cached_size))\n return False\n\n return True\n","sub_path":"simplecacher/cacher.py","file_name":"cacher.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"441488998","text":"# 引入库\nimport wave\nimport pyaudio\nchunk = 1024\nf = wave.open(\"蜂鸟+-+吴青峰.wav\", \"rb\")\np = pyaudio.PyAudio()\nrate = f.getframerate()\nstream = p.open(format=p.get_format_from_width(f.getsampwidth()),\n channels=f.getnchannels(), rate=rate, output=True)\nRATE / CHUNK * RECORD_SECONDS\n# 读取数据\ndata = f.readframes(chunk)\n\n# 播放\nwhile data != \"\":\n stream.write(data)\n data = f.readframes(chunk)\n\n# 停止数据流\nstream.stop_stream()\nstream.close()\n# 关闭 PyAudio\np.terminate()\n","sub_path":"人工智能程序设计/music_classification/播放.py","file_name":"播放.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"379497600","text":"\"\"\" invader.py - Copyright 2016 Kenichiro Tanaka \"\"\"\r\nimport sys\r\nfrom random import randint\r\nimport pygame\r\nfrom pygame.locals import Rect, QUIT, KEYDOWN, \\\r\n K_LEFT, K_RIGHT, K_SPACE\r\n\r\npygame.init()\r\npygame.key.set_repeat(5, 5)\r\nSURFACE = pygame.display.set_mode((600, 600))\r\nFPSCLOCK = pygame.time.Clock()\r\n\r\nclass Drawable:\r\n \"\"\" 全ての描画オブジェクトのスーパークラス \"\"\"\r\n def __init__(self, rect, offset0, offset1):\r\n strip = pygame.image.load(\"strip.png\")\r\n self.images = (pygame.Surface((24, 24), pygame.SRCALPHA),\r\n pygame.Surface((24, 24), pygame.SRCALPHA))\r\n self.rect = rect\r\n self.count = 0\r\n self.images[0].blit(strip, (0, 0),\r\n Rect(offset0, 0, 24, 24))\r\n self.images[1].blit(strip, (0, 0),\r\n Rect(offset1, 0, 24, 24))\r\n\r\n def move(self, diff_x, diff_y):\r\n \"\"\" オブジェクトを移動 \"\"\"\r\n self.count += 1\r\n self.rect.move_ip(diff_x, diff_y)\r\n\r\n def draw(self):\r\n \"\"\" オブジェクトを描画 \"\"\"\r\n image = self.images[0] if self.count % 2 == 0 \\\r\n else self.images[1]\r\n SURFACE.blit(image, self.rect.topleft)\r\n\r\nclass Ship(Drawable):\r\n \"\"\" 自機オブジェクト \"\"\"\r\n def __init__(self):\r\n super().__init__(Rect(300, 550, 24, 24), 192, 192)\r\n\r\nclass Beam(Drawable):\r\n \"\"\" ビームオブジェクト \"\"\"\r\n def __init__(self):\r\n super().__init__(Rect(300, 0, 24, 24), 0, 24)\r\n\r\nclass Bomb(Drawable):\r\n \"\"\" 爆弾オブジェクト \"\"\"\r\n def __init__(self):\r\n super().__init__(Rect(300, -50, 24, 24), 48, 72)\r\n self.time = randint(5, 220)\r\n\r\nclass Alien(Drawable):\r\n \"\"\" エイリアンオブジェクト \"\"\"\r\n def __init__(self, rect, offset, score):\r\n super().__init__(rect, offset, offset+24)\r\n self.score = score\r\n\r\ndef main():\r\n \"\"\" メインルーチン \"\"\"\r\n sysfont = pygame.font.SysFont(None, 72)\r\n scorefont = pygame.font.SysFont(None, 36)\r\n message_clear = sysfont.render(\"!!CLEARED!!\",\r\n True, (0, 255, 225))\r\n message_over = sysfont.render(\"GAME OVER!!\",\r\n True, (0, 255, 225))\r\n message_rect = message_clear.get_rect()\r\n message_rect.center = (300, 300)\r\n game_over = False\r\n moving_left = True\r\n moving_down = False\r\n move_interval = 20\r\n counter = 0\r\n score = 0\r\n aliens = []\r\n bombs = []\r\n ship = Ship()\r\n beam = Beam()\r\n\r\n # エイリアンの並びを初期化\r\n for ypos in range(4):\r\n offset = 96 if ypos < 2 else 144\r\n for xpos in range(10):\r\n rect = Rect(100+xpos*50, ypos*50 + 50, 24, 24)\r\n alien = Alien(rect, offset, (4-ypos)*10)\r\n aliens.append(alien)\r\n\r\n # 爆弾を設定\r\n for _ in range(4):\r\n bombs.append(Bomb())\r\n\r\n while True:\r\n ship_move_x = 0\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_LEFT:\r\n ship_move_x = -5\r\n elif event.key == K_RIGHT:\r\n ship_move_x = +5\r\n elif event.key == K_SPACE and beam.rect.bottom < 0:\r\n beam.rect.center = ship.rect.center\r\n\r\n if not game_over:\r\n counter += 1\r\n # 自機を移動\r\n ship.move(ship_move_x, 0)\r\n\r\n # ビームを移動\r\n beam.move(0, -15)\r\n\r\n # エイリアンを移動\r\n area = aliens[0].rect.copy()\r\n for alien in aliens:\r\n area.union_ip(alien.rect)\r\n\r\n if counter % move_interval == 0:\r\n move_x = -5 if moving_left else 5\r\n move_y = 0\r\n\r\n if (area.left < 10 or area.right > 590) and \\\r\n not moving_down:\r\n moving_left = not moving_left\r\n move_x, move_y = 0, 24\r\n move_interval = max(1, move_interval - 2)\r\n moving_down = True\r\n else:\r\n moving_down = False\r\n\r\n for alien in aliens:\r\n alien.move(move_x, move_y)\r\n\r\n if area.bottom > 550:\r\n game_over = True\r\n\r\n # 爆弾を移動\r\n for bomb in bombs:\r\n if bomb.time < counter and bomb.rect.top < 0:\r\n enemy = aliens[randint(0, len(aliens) - 1)]\r\n bomb.rect.center = enemy.rect.center\r\n\r\n if bomb.rect.top > 0:\r\n bomb.move(0, 10)\r\n\r\n if bomb.rect.top > 600:\r\n bomb.time += randint(50, 250)\r\n bomb.rect.top = -50\r\n\r\n if bomb.rect.colliderect(ship.rect):\r\n game_over = True\r\n\r\n # ビームがエイリアンと衝突?\r\n tmp = []\r\n for alien in aliens:\r\n if alien.rect.collidepoint(beam.rect.center):\r\n beam.rect.top = -50\r\n score += alien.score\r\n else:\r\n tmp.append(alien)\r\n aliens = tmp\r\n if len(aliens) == 0:\r\n game_over = True\r\n\r\n # 描画\r\n SURFACE.fill((0, 0, 0))\r\n for alien in aliens:\r\n alien.draw()\r\n ship.draw()\r\n beam.draw()\r\n for bomb in bombs:\r\n bomb.draw()\r\n\r\n score_str = str(score).zfill(5)\r\n score_image = scorefont.render(score_str,\r\n True, (0, 255, 0))\r\n SURFACE.blit(score_image, (500, 10))\r\n\r\n if game_over:\r\n if len(aliens) == 0:\r\n SURFACE.blit(message_clear, message_rect.topleft)\r\n else:\r\n SURFACE.blit(message_over, message_rect.topleft)\r\n\r\n pygame.display.update()\r\n FPSCLOCK.tick(20)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"invader/invader.py","file_name":"invader.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"269098293","text":"import socket\r\nimport threading\r\nimport sys\r\nimport argparse\r\nimport queue\r\nimport struct\r\nimport time\r\nimport datetime\r\n\r\n\r\nTIME_DIFFERENCE = (datetime.date(1970, 1, 1) - datetime.date(1900, 1, 1)).days * 24 * 3600\r\n\r\n\r\ndef format_time(time_):\r\n return int(time_ * (2 ** 32))\r\n\r\n\r\nclass SNTP:\r\n _FORMAT = '!BBBb3I4Q'\r\n\r\n def __init__(self, version: int = 3, mode: int = 3, transmit: int = 0, raw: bytes = b'',\r\n time_offset: int = 0, **kwargs):\r\n self.raw = raw\r\n self.time_offset = time_offset\r\n self.leap_indicator = 0\r\n self.version = version\r\n self.mode = mode\r\n self.stratum = 0\r\n self.poll = 0\r\n self.precision = 0\r\n self.root_delay = 0\r\n self.root_dispersion = 0\r\n self.ref_id = 0\r\n self.ref_time = 0\r\n self.originate_time = 0\r\n self.receive_time = 0\r\n self.transmit_time = transmit\r\n\r\n for key, value in kwargs.items():\r\n setattr(self, key, value)\r\n\r\n @classmethod\r\n def request_from_bytes(cls, data: bytes):\r\n if len(data) < 48:\r\n print('incorrect')\r\n return SNTP(correct=False)\r\n version = (data[0] & 56) >> 3\r\n mode = data[0] & 7\r\n transmit = int.from_bytes(data[40:48], 'big')\r\n if mode != 3:\r\n return None\r\n return SNTP(version, 4, originate_time=transmit, receive_time=time.time() + TIME_DIFFERENCE)\r\n\r\n def __bytes__(self):\r\n first = (self.leap_indicator << 6) | (self.version << 3) | self.mode\r\n receive_time = format_time(self.receive_time + self.time_offset)\r\n transmit_time = format_time(time.time() + TIME_DIFFERENCE + self.time_offset)\r\n return struct.pack('>3Bb5I3Q', first, self.stratum, self.poll, self.precision, 0, 0, 0, 0, 0,\r\n self.originate_time, receive_time, transmit_time)\r\n\r\n def __str__(self):\r\n return repr(self)\r\n\r\n def __repr__(self):\r\n result = ['SNTP(', \", \".join(map(lambda x: f'{x[0]}={x[1]}', self.__dict__.items())), ')']\r\n return ''.join(result)\r\n\r\n def offset_answer(self, time_offset):\r\n pass\r\n\r\n\r\nclass UdpServer:\r\n def __init__(self, server_port: int = 123, time_offset: int = 0, workers: int = 5, timeout: int = 2):\r\n self.isWorking = True\r\n self.server_port = server_port\r\n self.time_offset = time_offset\r\n\r\n self.to_send = queue.Queue()\r\n self.received = queue.Queue()\r\n\r\n socket.setdefaulttimeout(timeout)\r\n self.server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n self.server.bind(('', server_port))\r\n\r\n self.receiver = threading.Thread(target=self.receive)\r\n self.workers = [threading.Thread(target=self.handle_received) for _ in range(workers)]\r\n\r\n def start(self):\r\n print('Server is starting...')\r\n for w in self.workers:\r\n w.setDaemon(True)\r\n w.start()\r\n self.receiver.setDaemon(True)\r\n self.receiver.start()\r\n print(f'Server has started. Listen on port {self.server_port}.\\nTime offset: {self.time_offset}s\\n')\r\n\r\n while self.isWorking:\r\n pass\r\n\r\n def handle_received(self):\r\n while self.isWorking:\r\n try:\r\n sntp, addr = self.received.get(block=False)\r\n except queue.Empty:\r\n time.sleep(0.5)\r\n else:\r\n if sntp:\r\n sntp.time_offset = self.time_offset\r\n self.server.sendto(bytes(sntp), addr)\r\n\r\n def receive(self):\r\n while self.isWorking:\r\n try:\r\n data, addr = self.server.recvfrom(1024)\r\n self.received.put((SNTP.request_from_bytes(data), addr))\r\n print(f'Request:\\nIP: {addr[0]}\\nPort: {addr[1]}\\n')\r\n except socket.error:\r\n pass\r\n\r\n def stop(self):\r\n print('Server is stopping...')\r\n self.isWorking = False\r\n self.receiver.join()\r\n for w in self.workers:\r\n w.join()\r\n self.server.close()\r\n print('Server has stopped')\r\n\r\n\r\ndef parse_args(args):\r\n parser = argparse.ArgumentParser(description=\"SNTP server, that allows to send time with offset.\")\r\n parser.add_argument('-d', action='store', dest='time', type=int, default=0,\r\n help='Time offset to right time in seconds. '\r\n 'Can be position or negative number')\r\n parser.add_argument('-p', '--port', action='store', type=int, default=123, help='Server port. If port before 1024 '\r\n 'requires root user')\r\n args = parser.parse_args(args)\r\n\r\n if args.port < 1 or args.port > 65535:\r\n print('Enter correct port', file=sys.stderr)\r\n exit(2)\r\n\r\n return args\r\n\r\n\r\ndef main(argv):\r\n args = parse_args(argv[1:])\r\n server = UdpServer(args.port, args.time, workers=10)\r\n try:\r\n server.start()\r\n except KeyboardInterrupt:\r\n pass\r\n finally:\r\n server.stop()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)\r\n","sub_path":"tasks/SNTP/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"85500782","text":"import unittest\nimport unit\n\nclass TestUnitBasic(unit.TestUnitControl):\n\n def setUpClass():\n unit.TestUnit().check_modules('python')\n\n conf_app = \"\"\"\n {\n \"app\": {\n \"type\": \"python\",\n \"workers\": 1,\n \"path\": \"/app\",\n \"module\": \"wsgi\"\n }\n }\n \"\"\"\n\n conf_basic = \"\"\"\n {\n \"listeners\": {\n \"*:7080\": {\n \"application\": \"app\"\n }\n },\n \"applications\": %s\n }\n \"\"\" % (conf_app)\n\n def test_python_get_empty(self):\n self.assertEqual(self.get(), {'listeners': {}, 'applications': {}},\n 'empty')\n\n def test_python_get_prefix_listeners(self):\n self.assertEqual(self.get('/listeners'), {}, 'listeners prefix')\n\n def test_python_get_prefix_applications(self):\n self.assertEqual(self.get('/applications'), {}, 'applications prefix')\n\n def test_python_get_applications(self):\n self.put('/applications', self.conf_app)\n\n resp = self.get()\n\n self.assertEqual(resp['listeners'], {}, 'listeners')\n self.assertEqual(resp['applications'],\n {\n \"app\": {\n \"type\": \"python\",\n \"workers\": 1,\n \"path\": \"/app\",\n \"module\": \"wsgi\"\n }\n },\n 'applications')\n\n def test_python_get_applications_prefix(self):\n self.put('/applications', self.conf_app)\n\n self.assertEqual(self.get('/applications'),\n {\n \"app\": {\n \"type\": \"python\",\n \"workers\": 1,\n \"path\": \"/app\",\n \"module\":\"wsgi\"\n }\n },\n 'applications prefix')\n\n def test_python_get_applications_prefix_2(self):\n self.put('/applications', self.conf_app)\n\n self.assertEqual(self.get('/applications/app'),\n {\n \"type\": \"python\",\n \"workers\": 1,\n \"path\": \"/app\",\n \"module\": \"wsgi\"\n },\n 'applications prefix 2')\n\n def test_python_get_applications_prefix_3(self):\n self.put('/applications', self.conf_app)\n\n self.assertEqual(self.get('/applications/app/type'), 'python', 'type')\n self.assertEqual(self.get('/applications/app/workers'), 1, 'workers')\n\n def test_python_get_listeners(self):\n self.put('/', self.conf_basic)\n\n self.assertEqual(self.get()['listeners'],\n {\"*:7080\":{\"application\":\"app\"}}, 'listeners')\n\n def test_python_get_listeners_prefix(self):\n self.put('/', self.conf_basic)\n\n self.assertEqual(self.get('/listeners'),\n {\"*:7080\":{\"application\":\"app\"}}, 'listeners prefix')\n\n def test_python_get_listeners_prefix_2(self):\n self.put('/', self.conf_basic)\n\n self.assertEqual(self.get('/listeners/*:7080'),\n {\"application\":\"app\"}, 'listeners prefix 2')\n\n def test_python_change_listener(self):\n self.put('/', self.conf_basic)\n self.put('/listeners', '{\"*:7081\":{\"application\":\"app\"}}')\n\n self.assertEqual(self.get('/listeners'),\n {\"*:7081\": {\"application\":\"app\"}}, 'change listener')\n\n def test_python_add_listener(self):\n self.put('/', self.conf_basic)\n self.put('/listeners/*:7082', '{\"application\":\"app\"}')\n\n self.assertEqual(self.get('/listeners'),\n {\n \"*:7080\": {\n \"application\": \"app\"\n },\n \"*:7082\": {\n \"application\": \"app\"\n }\n },\n 'add listener')\n\n def test_python_change_application(self):\n self.put('/', self.conf_basic)\n\n self.put('/applications/app/workers', '30')\n self.assertEqual(self.get('/applications/app/workers'), 30,\n 'change application workers')\n\n self.put('/applications/app/path', '\"/www\"')\n self.assertEqual(self.get('/applications/app/path'), '/www',\n 'change application path')\n\n def test_python_delete(self):\n self.put('/', self.conf_basic)\n\n self.assertIn('error', self.delete('/applications/app'),\n 'delete app before listener')\n self.assertIn('success', self.delete('/listeners/*:7080'),\n 'delete listener')\n self.assertIn('success', self.delete('/applications/app'),\n 'delete app after listener')\n self.assertIn('error', self.delete('/applications/app'),\n 'delete app again')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_python_basic.py","file_name":"test_python_basic.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"525572362","text":"import numpy as np\nimport xobjects as xo\nfrom xobjects.context import available\n\n\ndef test_ref_to_static_type():\n for CTX in xo.ContextCupy, xo.ContextPyopencl, xo.ContextCpu:\n if CTX not in available:\n continue\n\n context = CTX()\n print(context)\n buff = context._make_buffer(capacity=1024)\n\n Float64_3 = xo.Float64[3]\n\n arr1 = Float64_3([1, 2, 3], _buffer=buff)\n arr2 = Float64_3([4, 5, 6], _buffer=buff)\n\n class MyStructRef(xo.Struct):\n a = xo.Ref[Float64_3]\n # a = xo.Field(xo.Ref(Float64_3)) # More explicit\n\n assert MyStructRef._size == 8\n\n mystructref = MyStructRef(a=arr2, _buffer=buff)\n\n assert mystructref._size == 8\n assert (\n mystructref.a._offset == arr2._offset\n ) # Points to the same object\n for ii in range(3):\n assert mystructref.a[ii] == arr2[ii]\n\n mystructref.a = arr1\n assert (\n mystructref.a._offset == arr1._offset\n ) # Points to the same object\n for ii in range(3):\n assert mystructref.a[ii] == arr1[ii]\n\n mystructref.a = [7, 8, 9]\n for ii in range(3):\n assert mystructref.a[ii] == [7, 8, 9][ii]\n\n\ndef test_ref_to_dynamic_type():\n for CTX in xo.ContextCupy, xo.ContextPyopencl, xo.ContextCpu:\n if CTX not in available:\n continue\n\n context = CTX()\n print(context)\n buff = context._make_buffer(capacity=1024)\n\n arr1 = xo.Float64[:]([1, 2, 3], _buffer=buff)\n arr2 = xo.Float64[:]([4, 5, 6, 7], _buffer=buff)\n\n class MyStructRef(xo.Struct):\n a = xo.Ref[xo.Float64[:]]\n\n assert MyStructRef._size == 8\n\n mystructref = MyStructRef(a=arr2, _buffer=buff)\n assert (\n mystructref.a._offset == arr2._offset\n ) # Points to the same object\n assert mystructref._size == 8\n for ii in range(4):\n assert mystructref.a[ii] == arr2[ii]\n\n mystructref.a = arr1\n assert (\n mystructref.a._offset == arr1._offset\n ) # Points to the same object\n for ii in range(3):\n assert mystructref.a[ii] == arr1[ii]\n\n mystructref.a = [\n 7,\n 8,\n ]\n for ii in range(2):\n assert mystructref.a[ii] == [7, 8, 9][ii]\n\n\ndef no_test_unionref():\n\n for CTX in xo.ContextCupy, xo.ContextPyopencl, xo.ContextCpu:\n if CTX not in available:\n continue\n\n context = CTX()\n print(context)\n\n arr = xo.Float64[:]([1, 2, 3], _context=context)\n buf = arr._buffer\n string = xo.String(\"Test\", _buffer=buf)\n\n class MyStructRef(xo.Struct):\n a = xo.Ref(xo.Float64[:], xo.String)\n\n assert MyStructRef._size == 16\n\n mystructref = MyStructRef(_buffer=buf)\n\n mystructref.a = arr\n assert (\n mystructref.a._offset == arr._offset\n ) # Points to the same object\n assert mystructref.a[1] == 2\n\n mystructref.a = string\n assert mystructref.a == \"Test\"\n\n\ndef no_test_array_of_unionrefs():\n class MyStructA(xo.Struct):\n a = xo.Float64\n\n class MyStructB(xo.Struct):\n a = xo.Int32\n\n Element = xo.Ref[MyStructA, MyStructB]\n ArrOfUnionRefs = Element[:]\n\n for CTX in xo.ContextCupy, xo.ContextPyopencl, xo.ContextCpu:\n if CTX not in available:\n continue\n\n context = CTX()\n print(context)\n\n aoref = ArrOfUnionRefs(10, _context=context)\n\n for ii in range(10):\n if np.mod(ii, 2) == 0:\n # Even elements\n temp = MyStructA()\n else:\n # Odd elements\n temp = MyStructB(a=10, _buffer=aoref._buffer)\n aoref[ii] = temp\n\n for ii in range(10):\n aoref[ii].a = 10 * ii\n\n for ii in range(10):\n print(f\"aoref[{ii}]=\", aoref[ii])\n assert aoref[ii].a == 10 * ii\n","sub_path":"tests/test_ref.py","file_name":"test_ref.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"406229438","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport telebot\n\nbot = telebot.TeleBot(os.environ['ABC:1234'])\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n bot.reply_to(message, u\"Hi, whats your meme!?\")\n\nbot.polling()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"40840036","text":"# https://programmers.co.kr/learn/courses/30/lessons/42586\nimport math\n\n\ndef solution(progresses, speeds):\n n = len(progresses)\n answer = []\n time = [0] * n\n for i in range(n):\n time[i] = math.ceil((100 - progresses[i]) / speeds[i])\n while time:\n t = time.pop(0)\n count = 1\n while time:\n if time[0] <= t:\n time.pop(0)\n count += 1\n else:\n break\n answer.append(count)\n return answer\n","sub_path":"programmers/laern/stack&queue4.py","file_name":"stack&queue4.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"333018928","text":"import unittest\nfrom Domain.entities import Book\nfrom Validator.validators import ValidateBook\nfrom Infrastructure.repo import Repo\nfrom Business.service import*\nfrom Errors.exceptions import*\n\n\n\nclass MyTestCase(unittest.TestCase):\n def test_repo(self):\n repoBooks = Repo()\n repoBooks.add(Book('0000', 'title', 'author'))\n repoBooks.add(Book('0001', 'title', 'author'))\n\n self.assertEqual(len(repoBooks), 2)\n\n l = []\n for i in repoBooks:\n l.append(i)\n self.assertEqual(len(l), 2)\n\n self.assertEqual(repoBooks[0], Book('0000', 'title', 'author'))\n repoBooks[0] = Book('0001', 'title', 'author')\n self.assertEqual(repoBooks[0], Book('0001', 'title', 'author'))\n\n def test_service(self):\n repoBooks = Repo()\n repoBooks.add(Book('0', 't', 'a'))\n repoBooks.add(Book('0001', 'title', 'author'))\n serviceBooks = ServiceBooks(repoBooks, None, None, None)\n\n serviceBooks.sort()\n self.assertEqual(repoBooks[0].id, '0001')\n\n serviceBooks.filter()\n self.assertEqual(len(repoBooks), 1)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Library/Tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"73898078","text":"# 获取全部歌曲的详细信息\n\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nimport csv\nimport pandas as pd\nimport numpy as np\nimport traceback\nimport time\n\n\nfrom selenium.common.exceptions import WebDriverException\n\n\n# 爬取歌曲链接中首页的评论信息\ndef get_comment_under_song(url, driver):\n driver.get(url)\n # 切换到内容的iframe\n driver.switch_to.frame(\"contentFrame\")\n\n # time.sleep(0.05)\n\n # ele_comments = driver.find_element_by_css_selector(\"div.cmmts.j-flag\")\n # 找到全部评论元素\n # eles = driver.find_elements_by_css_selector(\"div.cmmts.j-flag>*\")\n\n list = []\n eles = driver.find_elements_by_xpath(\"//div[@class='cmmts j-flag']/*\")\n count_try = 0\n\n while len(eles) <= 1 and count_try < 100: # 只重试100次\n print(\"页面未完全加载\")\n if len(eles) == 0 and count_try >= 10:\n print(\"超过10次无法加载, 可能评论信息不存在\")\n break # 不再尝试\n time.sleep(0.1) # 等待0.1秒\n eles = driver.find_elements_by_xpath(\"//div[@class='cmmts j-flag']/*\")\n count_try = count_try + 1\n\n\n if len(eles) <= 1:\n print(\"页面无法加载或没有评论\")\n\n # 完整的第一条评论的点赞数路径\n # \"//div[@class='cmmts j-flag']/*[2]//div[@class='rp']/a[1]\"\n\n popular = 0\n # count = 1 # xpath从1开始计数...\n\n comment = \"\"\n print(\" \", len(eles))\n for i in range(len(eles)):\n if eles[i].tag_name == \"div\": # 评论元素\n\n # 获取评论内容\n comment = driver.find_element_by_xpath(\"//div[@class='cmmts j-flag']/*[%d]//div[@class='cnt f-brk']\" % (i+1)).text\n comment = comment.replace(',', ' ')\n comment = comment.replace('\\n', ' ')\n # 获取点赞数\n num_likes = driver.find_element_by_xpath(\"//div[@class='cmmts j-flag']/*[%d]//div[@class='rp']/a[1]\" % (i+1)).text[1:-1:1]\n\n # count = count + 1\n # 转换为int\n if len(num_likes) != 0:\n if num_likes.endswith(\"万\"):\n num_likes = int(float(num_likes[0:-1:1]) * 10000) # 切片去除汉字, 转为float并乘以10000\n else:\n num_likes = int(num_likes)\n else:\n num_likes = 0 # 无点赞\n\n list.append((num_likes, popular, comment)) # 添加到列表\n\n elif eles[i].tag_name == \"h3\": # 边界元素\n if eles[i].text.startswith(\"精彩\"):\n popular = 1 # 激活热评标记\n elif eles[i].text.startswith(\"最新\"):\n popular = 0\n else: # 是br元素(换行), 不管它\n pass\n\n return list\n\n\ndef main():\n # 网址\n # url = \"https://music.163.com/playlist?id=3077285212\"\n\n # url = \"https://music.163.com/#/song?id=411214279\" # 雅俗共赏 OK\n # url = \"https://music.163.com/#/song?id=1345865324\" # 不知名的歌 OK\n url = \"https://music.163.com/#/song?id=1357704311\" # 炸了\n\n # 选项\n options = Options() # 调用sele库进行设置\n options.add_argument(\"--headless\")\n # options.headless = True\n\n # 传入设置, 创建一个driver\n driver = webdriver.Firefox(options=options,\n executable_path=r\"D:\\Files\\Library_development\\geckodriver-v0.26.0-win64\\geckodriver.exe\")\n print(\" driver created\")\n\n # 存储歌单的csv文件(追加模式,'\\n'换行避免空行)\n # file_csv = open(\"test.csv\", \"w\", encoding='utf-8')\n # writer = csv.writer(file_csv, lineterminator='\\n')\n\n # writer.writerow([\"标题\", \"\"])\n try:\n comment_list = get_comment_under_song(url, driver)\n print(comment_list)\n except WebDriverException as wde:\n print(\" \", wde.args)\n print(\"=====\")\n print(traceback.format_exc()) # 打印详细信息\n\n\n\n # 关闭驱动, 这点很重要, 不然火狐的进程是不会死的\n driver.close()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","sub_path":"NetEaseCloudMusicCrawler_TEST/CRAWLER/crawler_commentsUnderSong.py","file_name":"crawler_commentsUnderSong.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"2158351","text":"from math import sqrt\n\ndef calcula_tempo(aceleracoes):\n \n tempos = dict()\n \n for atleta in aceleracoes.keys():\n aceleracao = aceleracoes[atleta]\n tempo = sqrt(200/aceleracao)\n tempos[atleta] = tempo\n \n return tempos\n\naceleracoes = dict()\n\nwhile True:\n \n atleta = input()\n if atleta == 'sair': break\n aceleracao = float(input())\n \n aceleracoes[atleta] = aceleracao\n\ntempos = calcula_tempo(aceleracoes)\n\ntempos = list(tempos.values())\natletas = list(tempos.keys())\n\ntempo_minimo = min(tempos)\nindice = tempos.index(tempo_minimo)\natleta_rapido = atletas[indice]\n\nprint('O vencedor é %s com tempo de conclusão de %d s' % (atleta_rapido, tempo_minimo))\n\n\n\n","sub_path":"backup/user_233/ch78_2020_03_23_13_45_04_019076.py","file_name":"ch78_2020_03_23_13_45_04_019076.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"563073404","text":"\n'''\n\n urllib,他只能进行同步请求,不能进行异步请求。\n\n 1、获得静态数据\n https://www.nasdaq.com/symbol/aapl/historical#.UWdnJBDMhHK\n https://www.nasdaq.com/market-activity/stocks/aapl/historical#.UWdnJBDMhHK\n\n 2、获得动态数据\n http://q.stock.sohu.com/cn/600519/lshq.shtml\n http://q.stock.sohu.com/hisHq?code=cn_600519&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp&0.9161459029494989\n\n 3、伪装成浏览器\n urllib的请求头中添加User-Agent字段\n 模拟iPhone浏览器:User-Agent设置用户代理字段,\n Mozilla/5.0(iPhone:CPU iPhone OS 10_2_1 like Mac OS X)\n AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1\n 示例:http://www.ctrip.com\n'''\n\nimport urllib.request\n\n# url = 'https://www.nasdaq.com/symbol/aapl/historical#.UWdnJBDMhHK'\n# url = 'http://q.stock.sohu.com/hisHq?code=cn_600519&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp&0.9161459029494989'\nurl = 'http://www.ctrip.com'\nreq = urllib.request.Request(url)\nreq.add_header('User-Agent',\n 'Mozilla/5.0 (iPhone: CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) '\n 'Version/10.0 Mobile/14D27 Safari/602.1')\n\n\nwith urllib.request.urlopen(req) as response:\n data = response.read()\n json_data = data.decode()\n print(json_data)\n","sub_path":"项目实战1:网络爬虫与抓取股票数据/part02 爬取数据/2-2 使用urllib爬取数据/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"394480749","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nif __name__ == '__main__':\n arr = []\n\n for _ in range(6):\n arr.append(list(map(int, input().rstrip().split())))\n \n i = 0\n maximum = 0\n while i < (len(arr) - 2):\n j = 0\n while j < (len(arr) - 2):\n total = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]\n if total > maximum or (i == 0 and j == 0):\n maximum = total\n j = j + 1\n i = i + 1\n\n print(maximum)","sub_path":"Interview Preparation Kit/Arrays/Python/2D Array - DS.py","file_name":"2D Array - DS.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"379801003","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\turl(r'^$', 'bruno.views.index'),\n\turl(r'^about/', 'bruno.views.about'),\n\turl(r'^contact/', 'bruno.views.contact'),\n\turl(r'^bhaskara/', include('bhaskara.urls')),\n\turl(r'^texto/', include('texto.urls')),\n\turl(r'^templates/', 'templates'),\n\turl(r'^static/', 'static'),\n\turl(r'^media/', 'media'),\n)","sub_path":"bruno/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"110109373","text":"import cv2\nfrom CV import PreProcessor, FaceDetector\nimport matplotlib.image as mpimg\n\n# import numpy as np\nfrom matplotlib import pyplot as plt\n\n# rgb image picked up in bgr format\nimgrgb = cv2.imread('Images/manFace.jpeg')\n#rgb image colour is off as it reads bgr\nplt.subplot(122), plt.imshow(imgrgb), plt.title('original image')\nplt.xticks([]), plt.yticks([])\nplt.show()\n\npreProcessor = PreProcessor()\n# convert to BGR\nimgbgr = preProcessor.convert_to_bgr(imgrgb)\n\nplt.subplot(122), plt.imshow(imgbgr), plt.title('after convert to bgr image')\nplt.xticks([]), plt.yticks([])\nplt.show()\n\n\n# gray scale returns blue/green...\ngreyScaleImg = preProcessor.applygreyscale(imgrgb)\nplt.subplot(122), plt.imshow(greyScaleImg), plt.title('after Applying Grey Scale')\nplt.xticks([]), plt.yticks([])\nplt.show()\n\n# Smooth image\nbFilter = preProcessor.applybilateralfilter(imgbgr)\n\n# Detect Faces\nfaceDetector = FaceDetector()\nfaces = faceDetector.detectfaces(bFilter)\n\nprint(\"run ran\")\n\n\n# display image\nfor face in faces:\n plt.subplot(122), plt.imshow(face), plt.title('Faces')\n plt.xticks([]), plt.yticks([])\n plt.show()\n","sub_path":"Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"588442220","text":"import random\nrandom.seed(10)\n\n__author__ = 'Trevor Martin'\n\n\nclass Ecosystem:\n\n __slots__ = ['_initial_bears', '_initial_fish', '_len_river', '_river']\n\n def __init__(self, initial_bears, initial_fish, len_river):\n\n if type(initial_bears) != int or type(initial_fish) != int or type(len_river) != int:\n raise TypeError('The initial bears and fish as well as the river length must be integers')\n\n assert len_river >= (initial_bears+initial_fish), 'The length of the river must exceed the starting total of bears and fish combined' \n \n self._initial_bears = initial_bears\n self._initial_fish = initial_fish\n self._len_river = len_river\n self._river = self.fill_river()\n \n def fill_river(self):\n river = [None]*self._len_river\n indices = list(range(self._len_river))\n random.shuffle(indices)\n for index in indices:\n if self._initial_bears == 0 and self._initial_fish != 0:\n choice = 0\n \n if self._initial_bears != 0 and self._initial_fish == 0:\n choice = 1\n \n if self._initial_bears == 0 and self._initial_fish == 0:\n break\n \n if self._initial_bears !=0 and self._initial_fish: \n choice = random.randrange(0, 1)\n \n if choice == 1:\n river[index] = 'bear'\n self._initial_bears -= 1\n\n if choice == 0:\n river[index] = 'fish'\n self._initial_fish -= 1\n \n return river\n\n \n def course(self, time_steps):\n\n if type(time_steps) != int:\n raise TypeError('The time steps must be an integer value')\n\n print(f'INITIAL ECOSYSTEM: {self._river}')\n\n for life in range(time_steps):\n for index, val in enumerate(self._river):\n \n none_indices = [i for i, elt in enumerate(self._river) if elt == None]\n \n move = random.randrange(0,1)\n if move == 1:\n position = index+1\n if move == 0:\n position = index-1\n \n if val == 'fish' and self._river[position] == 'fish':\n if len(none_indices) > 0:\n choice = random.randint(0, len(none_indices)-1)\n self._river[none_indices[choice]] = 'fish'\n if val == 'bear' and self._river[position] == 'bear':\n if len(none_indices) > 0:\n choice = random.randint(0, len(none_indices)-1)\n self._river[none_indices[choice]] = 'bear'\n if val == 'bear' and self._river[position] == 'fish':\n self._river[position] = None\n if val == 'fish' and self._river[position] == 'bear':\n self._river[index] = None\n print(f'LIFETIME {life}: {self._river}')\n\nif __name__ == '__main__':\n ecosystem = Ecosystem(5,18,23)\n ecosystem.course(3)\n \n","sub_path":"DSAP/Ch02/p_2_36.py","file_name":"p_2_36.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"63274837","text":"# -*- encoding: utf-8 -*-\nimport sys\nr_input = sys.stdin.readline\n\n# 도시의 수\nN = int(r_input())\ncost = [list(map(int, r_input().split())) for _ in range(N)]\nresult = sys.maxsize\nvisit = [0] * N\n\n\ndef dfs(node, total, cnt, start, p):\n global result\n visit[node] = 1\n\n if cnt == N:\n if cost[node][start]:\n total += cost[node][start]\n\n if total < result:\n result = total\n\n visit[node] = 0\n\n return\n\n for j in range(N):\n if j != start and not visit[j] and cost[node][j]:\n dfs(j, total + cost[node][j], cnt + 1, start, p + [j])\n\n visit[node] = 0\n\n\ndfs(0, 0, 1, 0, [0])\n\nprint(result)\n","sub_path":"Algorithm/Baekjoon/10971 외판원 순회 2/10971.py","file_name":"10971.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"613077367","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import reverse\nfrom pokedex.models import Pokemon, Type, PokemonAbility, Ability\nfrom django.db.models import Q\n\ndef redirect_to_pokedex(request):\n\treturn HttpResponseRedirect(reverse('index'))\n\ndef index(request):\n\tcontext = {}\n\n\ttypes = Type.objects.order_by('name')\n\tcontext['types'] = types\n\n\tquery = request.GET\n\tfilter_name = query.get('name')\n\tfilter_type = query.get('type')\n\tif len(query) > 0 and (filter_name != '' or filter_type != 'any'):\n\t\tif filter_type != 'any':\n\t\t\tfilter_type = Type.objects.filter(name=filter_type.upper())[0]\n\t\t\tpokemon_searched = Pokemon.objects.filter(\n\t\t\t\tQ(eng_name__icontains=filter_name), \n\t\t\t\tQ(type_1=filter_type.id) | Q(type_2=filter_type.id)\n\t\t\t)\n\t\telse:\n\t\t\tpokemon_searched = Pokemon.objects.filter(eng_name__icontains=filter_name)\n\telse:\n\t\tpokemon_searched = Pokemon.objects.all()\n\n\tfor pokemon in pokemon_searched:\n\t\tpokemon.national_number = '0' * (3 - len(str(pokemon.national_number))) + str(pokemon.national_number)\n\t\tpokemon.type_1 = Type.objects.filter(id=pokemon.type_1)[0]\t\t# the types are initially integers\n\t\tif pokemon.type_2 != 18:\n\t\t\tpokemon.type_2 = Type.objects.filter(id=pokemon.type_2)[0]\n\n\tcontext['results'] = pokemon_searched\n\n\treturn render(request, 'search.html', context)\n\ndef pokemon_info(request, pokemon):\n\tcontext = {}\n\n\tpokemon = Pokemon.objects.get(eng_name=pokemon)\n\tpokemon.national_number = '0' * (3 - len(str(pokemon.national_number))) + str(pokemon.national_number)\n\tpokemon.type_1 = Type.objects.filter(id=pokemon.type_1)[0]\t\t# the types are initially integers\n\tif pokemon.type_2 != None:\n\t\tpokemon.type_2 = Type.objects.filter(id=pokemon.type_2)[0]\n\tpokemon.ability = PokemonAbility.objects.filter(pokemon=pokemon.national_number)\n\tcontext['pokemon'] = pokemon\n\n\treturn render(request, 'pokemon_info.html', context)\n\ndef ability_search(request):\n\tcontext = {}\n\n\tquery = request.GET\n\tfilter_name = query.get('name')\n\n\tif len(query) > 0 and filter_name != '':\n\t\tabilities = Ability.objects.filter(name__icontains=filter_name)\n\telse:\n\t\tabilities = Ability.objects.all()\n\n\tcontext['abilities'] = abilities\n\n\treturn render(request, 'ability_search.html', context)\n\ndef ability_info(request, ability):\n\tcontext = {}\n\n\tability = Ability.objects.get(name=ability.upper().replace('_', ' '))\n\tcontext['ability'] = ability\n\n\tpokemon = PokemonAbility.objects.filter(ability=ability.name.upper().replace('_', ' '))\n\tpokemon_with_ability = []\n\n\tfor p in pokemon:\n\t\tpokemon_with_ability.append(Pokemon.objects.get(national_number=p.pokemon))\n\n\tcontext['pokemon'] = pokemon_with_ability\n\n\treturn render(request, 'ability_info.html', context)","sub_path":"pokedex/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"159163790","text":"import torch\nimport numpy as np\n\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n# how many samples per batch to load\nbatch_size = 20\n\n# convert data to torch.FloatTensor\nnormalize = transforms.Normalize((0.1307,), (0.3081,)) # MNIST\ntransform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n])\n\n# choose the training and test datasets\ntrain_data = datasets.MNIST(root='./data', train=True, download=False, transform=transform)\ntest_data = datasets.MNIST(root='./data', train=False, download=False, transform=transform)\n\n# prepare data loaders\nnum_train = len(train_data)\nindices = list(range(num_train))\nsplit = int(np.floor(0.2 * num_train))\n\ntrain_idx, valid_idx = indices[split:], indices[:split]\n\ntrain_sampler = SubsetRandomSampler(train_idx)\nvalid_sampler = SubsetRandomSampler(valid_idx)\n\ntrain_loader = torch.utils.data.DataLoader(train_data,\n batch_size=batch_size, sampler=train_sampler)\n\nvalid_loader = torch.utils.data.DataLoader(train_data,\n batch_size=batch_size, sampler=valid_sampler)\n\nimport matplotlib.pyplot as plt\n\n# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy()\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20 / 2, idx + 1, xticks=[], yticks=[])\n ax.imshow(np.squeeze(images[idx]), cmap='gray')\n # print out the correct label for each image\n # .item() gets the value contained in a Tensor\n ax.set_title(str(labels[idx].item()))\nplt.show()\n","sub_path":"py_codes/1_Two_Layer_MLP/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"134178194","text":"class Solution:\n def validMountainArray(self, arr: list[int]) -> bool:\n descending = False\n\n if len(arr) <= 1:\n return False\n\n if arr[0] >= arr[1]:\n return False\n\n prev_num = arr[0]\n for num in arr[1:]:\n if num == prev_num:\n return False\n\n if not descending and num < prev_num:\n descending = True\n\n elif descending and num > prev_num:\n return False\n\n prev_num = num\n\n return descending\n\n\ntests = [\n (\n ([2, 1],),\n False,\n ),\n (\n ([3, 5, 5],),\n False,\n ),\n (\n ([0, 3, 2, 1],),\n True,\n ),\n]\n","sub_path":"valid_mountain_array.py","file_name":"valid_mountain_array.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"237929223","text":"# Definition for singly-linked list.\nimport heapq\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeKLists(self, lists):\n hp = list()\n heapq.heapify(hp)\n d = dict()\n root = None\n cur = None\n for node in lists:\n if node:\n heapq.heappush(hp, node.val)\n if node.val in d:\n d[node.val].append(node)\n else:\n d[node.val] = [node]\n\n while hp:\n val = heapq.heappop(hp)\n t = d[val].pop()\n if t.next:\n heapq.heappush(hp, t.next.val)\n if t.next.val in d:\n d[t.next.val].append(t.next)\n else:\n d[t.next.val] = [t.next]\n t.next = None\n if not root:\n root = t\n cur = root\n else:\n cur.next = t\n cur = cur.next\n return root\n\n\n\n","sub_path":"lt0023/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"67686030","text":"import sys\nimport pygame\nimport os\n\nname = 'star.png'\npygame.init()\n\n\ndef create_simple_sprite(name, y, x, transform=False, size=(1, 1), colorkey=None):\n sprite = pygame.sprite.Sprite()\n sprite.image = pygame.transform.scale(load_image(name, colorkey), size) if transform else load_image(name)\n sprite.rect = sprite.image.get_rect()\n sprite.rect.y = x\n sprite.rect.x = y\n return sprite\n\n\ndef load_text(text):\n return open('data/text/' + text).readlines()\n\n\ndef load_image(name, color_key=None):\n fullname = os.path.join('data', name)\n\n try:\n image2 = pygame.image.load(fullname).convert_alpha()\n except pygame.error as message:\n print('Cannot load image:', name)\n raise SystemExit(message)\n\n image = pygame.Surface(image2.get_rect().size, pygame.SRCALPHA, 32).convert_alpha()\n image.blit(image2, (0, 0), image.get_rect())\n if color_key is not None:\n if color_key == -1:\n color_key = image.get_at((0, 0))\n image.set_colorkey(color_key)\n else:\n pass # image = image.convert_alpha()\n return image\n\n\ndef text_format(mes, text_font, text_size, text_color):\n return pygame.font.Font(text_font, text_size).render(mes, 0, text_color)\n\n\ndef load_level(filename):\n filename = \"data/text/\" + filename\n\n with open(filename, 'r') as mapFile:\n level_map = [line.strip() for line in mapFile]\n\n max_width = max(map(len, level_map))\n\n return list(map(lambda x: x.ljust(max_width, '.'), level_map))\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\nclass Tile(pygame.sprite.Sprite):\n def __init__(self, tile_type, pos_x, pos_y, *group):\n super().__init__(*group)\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.name_image = load_image(tile_type)\n self.image = pygame.transform.scale(load_image(tile_type), (180, 180))\n self.rect = self.image.get_rect().move(\n 180 * pos_x, 180 * pos_y)\n\n\nclass Sprite(pygame.sprite.Sprite):\n def __init__(self, pos_x, pos_y, image, *group):\n super().__init__(*group)\n self.image = pygame.transform.scale(load_image(image), (180, 180))\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.name_image = load_image(image)\n self.rect = self.image.get_rect().move(pos_x, pos_y)\n\n\nclass AnimatedSprite(pygame.sprite.Sprite):\n def __init__(self, sheet, columns, rows, x, y, sound, *group):\n super().__init__(*group)\n self.frames = []\n self.columns = columns\n self.rows = rows\n self.sound = sound\n self.cut_sheet(sheet[0], columns, rows)\n self.cut_sheet(sheet[1], columns, rows)\n self.cut_sheet(sheet[2], columns, rows)\n self.cur_frame = 0\n self.pos_x = x\n self.pos_y = y\n self.scale = 180\n self.vy = 0\n self.vx = 0\n self.frames_normal = self.frames[:]\n self.image_normal = self.frames[self.cur_frame]\n for i in range(len(self.frames)):\n self.frames[i] = pygame.transform.scale(self.frames[i], (180, 180))\n self.image = self.frames[self.cur_frame]\n self.rect = self.rect.move(x * 180, y * 180)\n\n def cut_sheet(self, sheet, columns, rows):\n self.rect = pygame.Rect(0, 0, sheet.get_width() // columns,\n sheet.get_height() // rows)\n for j in range(rows):\n for i in range(columns):\n frame_location = (self.rect.w * i, self.rect.h * j)\n self.frames.append(sheet.subsurface(pygame.Rect(\n frame_location, self.rect.size)))\n\n def update(self, cub=None):\n if self.vx != 0:\n self.rect = self.rect.move(self.vx, 0)\n self.pos_x += self.vx / self.scale\n self.cur_frame = (self.cur_frame + 1) % len(self.frames)\n self.image = self.frames[0:4][self.cur_frame % 4] if self.vx < 0 else \\\n pygame.transform.flip(self.frames[0:4][self.cur_frame % 4], True,\n False)\n self.image_normal = self.frames_normal[0:4][self.cur_frame % 4] if self.vx < 0 else \\\n pygame.transform.flip(self.frames[0:4][self.cur_frame % 4], True,\n False)\n elif self.vy != 0:\n self.pos_y += self.vy / self.scale\n self.cur_frame = (self.cur_frame + 1) % len(self.frames)\n self.image = self.frames[4:8][self.cur_frame % 4] if self.vy < 0 else \\\n pygame.transform.flip(self.frames[8:][self.cur_frame % 4], True,\n False)\n self.image_normal = self.frames_normal[0:4][self.cur_frame % 4] if self.vx < 0 else \\\n pygame.transform.flip(self.frames[0:4][self.cur_frame % 4], True,\n False)\n self.rect = self.rect.move(0, self.vy)\n\n if pygame.sprite.spritecollideany(self, cub):\n self.rect = self.rect.move(0, -self.vy)\n self.rect = self.rect.move(-self.vx, 0)\n self.pos_x += -self.vx / self.scale\n self.pos_y += -self.vy / self.scale\n\n def get_event(self, event):\n if self.rect.collidepoint(event.pos):\n pygame.mixer.Sound(self.sound).play()\n\n\nclass Player:\n def __init__(self, sprite, health, lucky, protect, money):\n self.sprite = sprite\n self.health = health\n self.lucky = lucky\n self.protect = protect\n self.money = money\n\n def set_health(self, count):\n self.health += count\n\n def set_money(self, count):\n self.money += count\n\n\nclass Menu:\n def __init__(self, y, h, items, screen, music, tittle):\n self.items = items\n self.y = y\n self.h = h\n self.title = tittle\n self.music = music\n fon = create_simple_sprite(\"image/space.png\", 0, 0, True, (1300, 700))\n self.select_item = 0\n self.screen = screen\n self.all_sprites = pygame.sprite.Group()\n self.all_sprites.add(fon)\n\n def draw_menu(self):\n menu = True\n clock = pygame.time.Clock()\n pygame.mixer.music.load(self.music)\n pygame.mixer.music.play(-1, 0.0)\n while menu:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n self.select_item = min(self.select_item + 1, len(self.items) - 1)\n if event.key == pygame.K_UP:\n self.select_item = max(0, self.select_item - 1)\n if event.key == pygame.K_RETURN:\n menu = False\n\n self.all_sprites.draw(self.screen)\n\n if self.title:\n title = text_format(\"RICK AND MORTY\", \"data/font/font3.ttf\", 100, pygame.Color(\"orange\"))\n self.screen.blit(title, (130, 100))\n\n punkts = [text_format(i, \"data/font/font3.ttf\", 75, pygame.Color(\"yellow\")) for i in self.items.keys()]\n\n max_size = max(punkts, key=lambda x: x.get_rect()[2]).get_rect()[2]\n\n pygame.draw.rect(self.screen, (147, 112, 219),\n (620 - (max_size / 2), self.y + self.select_item * self.h - 25,\n max_size + 50,\n punkts[0].get_rect()[3] + 40))\n\n for i in range(len(punkts)):\n self.screen.blit(punkts[i], (650 - (punkts[i].get_rect()[2] / 2),\n self.y + i * self.h))\n\n pygame.display.flip()\n clock.tick(60)\n\n return self.items[list(self.items.keys())[self.select_item]]\n\n\nclass Camera:\n def __init__(self):\n self.dx = 0\n self.dy = 0\n\n def apply(self, obj):\n obj.rect.x += self.dx\n obj.rect.y += self.dy\n\n def update(self, target):\n self.dx = -(target.rect.x + target.rect.w // 2 - 1300 // 2)\n self.dy = -(target.rect.y + target.rect.h // 2 - 700 // 2)\n\n\ndef cat_scen(fon_name, text, screen, rick, morty, music):\n select = 0\n fon = create_simple_sprite(fon_name, 0, 0, True, (1300, 750))\n rick = create_simple_sprite(rick, -60, 20)\n morty = create_simple_sprite(morty, 1000, 100)\n all_sprites = pygame.sprite.Group()\n all_sprites.add(fon)\n all_sprites.add(rick)\n all_sprites.add(morty)\n\n pygame.mixer.music.load(music)\n pygame.mixer.music.play(-1, 0.0)\n\n running = True\n while running:\n screen.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n if event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:\n select += 1\n if select == len(text):\n running = False\n\n all_sprites.draw(screen)\n screen.blit(text_format(text[min(select, len(text) - 1)].rstrip(), \"data/font/font1.ttf\",\n 35, (0, 0, 0)), (300, 550))\n pygame.display.flip()\n\n\ndef choice(fon_name, variants, screen, music, x, y):\n class ChoiceItem(pygame.sprite.Sprite):\n def __init__(self, pos_x, pos_y, image):\n super().__init__(all_sprites)\n self.image = image\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.rect = self.image.get_rect()\n self.rect.x = (pos_x - self.rect[2]) // 2\n self.rect.y = pos_y\n\n def update(self, image):\n self.image = image\n self.rect = self.image.get_rect()\n self.rect.x = (self.pos_x - self.rect[2]) // 2\n self.rect.y = self.pos_y\n\n select = 0\n fon = create_simple_sprite(fon_name, 0, 0, True, (1300, 700))\n all_sprites = pygame.sprite.Group()\n all_sprites.add(fon)\n ChoiceItem(x, y, load_image(variants[0][0]))\n\n pygame.mixer.music.load(music)\n pygame.mixer.music.play(-1, 0.0)\n text = load_text(variants[select][1])\n\n running = True\n while running:\n screen.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n select = min(select + 1, len(variants) - 1)\n text = load_text(variants[select][1])\n\n if event.key == pygame.K_LEFT:\n select = max(0, select - 1)\n text = load_text(variants[select][1])\n\n if event.key == pygame.K_RETURN:\n running = False\n\n all_sprites.update(load_image(variants[select][0]))\n all_sprites.draw(screen)\n screen.blit(text_format(text[0].rstrip(), \"data/font/font1.ttf\", 75, (0, 0, 0)), (750, 90))\n for i in range(1, len(text)):\n screen.blit(text_format(text[i].rstrip(), \"data/font/font1.ttf\", 35, (0, 0, 0)), (790, 140 + i * 90))\n pygame.display.flip()\n\n return select\n","sub_path":"classes_function.py","file_name":"classes_function.py","file_ext":"py","file_size_in_byte":11086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"9854266","text":"\"\"\"\nClass to implement a Predictor for applying a model on new images\n- takes a folder with images and a model as input\n- additionally requires pre-processing specification and class list\n\"\"\"\nimport os\nfrom keras.models import load_model\nfrom keras.preprocessing.image import ImageDataGenerator, list_pictures\nfrom keras.utils.data_utils import Sequence\nfrom keras.preprocessing.image import load_img\n# from tools.double_iterator import DoubleIterator\nfrom collections import OrderedDict\nimport numpy as np\nimport pandas as pd\nimport json\n\n\nclass DataSet(Sequence):\n def __init__(self, image_paths, batch_size, image_classes=None,\n imagegenerator=None,\n target_size=None,\n color_mode=None,\n class_mode=None):\n self.image_paths = image_paths\n self.image_classes = image_classes\n self.batch_size = batch_size\n self.target_size = target_size\n self.color_mode = color_mode\n self.class_mode = class_mode\n\n if self.image_classes is None:\n self.image_classes = ['unknown' for x in\n range(0, len(self.image_paths))]\n\n def __len__(self):\n return len(self.image_paths) // self.batch_size\n\n def __getitem__(self, idx):\n batch_x = self.self.image_paths[idx*self.batch_size:\n (idx+1)*self.batch_size]\n batch_y = self.self.image_classes[idx*self.batch_size:\n (idx+1)*self.batch_size]\n\n img_array = np.arry([load_img(fname) for fname in batch_x])\n if self.imagegenerator is not None:\n gen = self.imagegenerator.flow(\n img_array, y=batch_y,\n batch_size=self.batch_size,\n shuffle=False,\n seed=None,\n target_size=self.target_size,\n color_mode=self.color_mode,\n class_mode=self.class_mode)\n x, y = gen.next()\n else:\n raise NotImplementedError\n return x, y\n\n\nclass PredictorExternalTest(object):\n \"\"\" class to implement a predictor, completely independent of the specific\n project infrastructure - to be used for researches who want to apply\n one of the models\n \"\"\"\n def __init__(self,\n path_to_model=None,\n model_cfg_json=None,\n keras_datagen=None,\n class_list=None):\n\n self.path_to_model = path_to_model\n self.keras_datagen = keras_datagen\n self.class_list = class_list\n self.model_cfg_json = model_cfg_json\n self.model = None\n self.preds = None\n self.pre_processing = None\n self.color_mode = \"rgb\"\n\n if path_to_model is None:\n raise IOError(\"Path to model has to be specified\")\n\n if model_cfg_json is None:\n if keras_datagen is None:\n raise IOError(\"Specify keras ImageDataGenerator\")\n\n if class_list is None:\n raise IOError(\"Specify class list to map predictions\\\n to classes\")\n\n if model_cfg_json is not None:\n if (keras_datagen is not None) or (class_list is not None):\n raise IOError(\"Specify only one of model_cfg_json or\\\n (keras_datagen and class_list)\")\n\n if not os.path.isfile(self.path_to_model):\n raise FileNotFoundError(\"Model File %s not found\" %\n self.path_to_model)\n\n # Load model from disk\n print(\"Loading model from disk: %s\" % self.path_to_model)\n self.model = load_model(self.path_to_model)\n\n # handle color mode\n if self.model.input_shape[3] == 1:\n self.color_mode = 'grayscale'\n else:\n self.color_mode = 'rgb'\n\n # Load cfg from json file\n if model_cfg_json is not None:\n cfg_file = open(model_cfg_json, 'r')\n model_cfg = json.load(cfg_file)\n # check model_cfg\n assert 'class_mapper' in model_cfg.keys()\n assert 'pre_processing' in model_cfg.keys()\n\n # extract class mapping and order\n class_list = list()\n for i in range(0, len(model_cfg['class_mapper'].keys())):\n class_list.append(model_cfg['class_mapper'][str(i)])\n self.class_list = class_list\n\n # add pre_processing\n self.pre_processing = model_cfg['pre_processing']\n\n def predict_path(self, path, output_path,\n output_file_name='predictions.csv'):\n \"\"\" Predict class for images in a directory with subdirectories that\n contain the images \"\"\"\n\n # check input\n if any([x is None for x in [path, output_path]]):\n raise IOError(\"Path and output_path have to be specified\")\n\n # check output_path\n if not output_path[-1] in ('/', '\\\\'):\n output_path = output_path + os.path.sep\n\n # prediction batch sizes\n batch_size = 256\n\n # fit data generator on input data\n if self.pre_processing is None:\n\n print(\"Initializing generator\")\n generator = self.keras_datagen.flow_from_directory(\n path,\n target_size=self.model.input_shape[1:3],\n color_mode=self.color_mode,\n batch_size=batch_size,\n class_mode='sparse',\n seed=123,\n shuffle=False)\n\n # Fit data generator if required\n if any([self.keras_datagen.featurewise_std_normalization,\n self.keras_datagen.samplewise_std_normalization,\n self.keras_datagen.zca_whitening]):\n\n print(\"Fitting data generator\")\n # create a generator to randomly select images to calculate\n # image statistics for data pre-processing\n generator_fit = self.keras_datagen.flow_from_directory(\n path,\n target_size=self.model.input_shape[1:3],\n color_mode=self.color_mode,\n batch_size=2000,\n class_mode='sparse',\n seed=123,\n shuffle=True)\n\n # fit the generator with a batch of sampled data\n generator.fit(generator_fit.next())\n\n # use pre-defined pre_processing options and add to generator\n else:\n print(\"Initializing generator\")\n gen = ImageDataGenerator(rescale=1./255)\n for k, v in self.pre_processing.items():\n setattr(gen, k, v)\n\n image_paths = list_pictures(path)\n self.generator = DataSet(image_paths, batch_size=batch_size,\n imagegenerator=gen,\n target_size=self.model.input_shape[1:3],\n color_mode=self.color_mode,\n class_mode='sparse')\n\n # predict whole set\n print(\"Starting to predict images in path\")\n\n # calculate number of iterations to make\n steps_remainder = len(image_paths) % batch_size\n if steps_remainder > 0:\n extra_step = 1\n else:\n extra_step = 0\n\n # use double iterator to speed up training\n # gen_double = DoubleIterator(generator, batch_size=batch_size,\n # inner_shuffle=False)\n\n preds = self.model.predict_generator(\n self.generator,\n steps=self.generator.__len__() + extra_step,\n workers=1,\n use_multiprocessing=False,\n verbose=1)\n\n # preds = self.model.predict_generator(\n # generator,\n # steps=(generator.n // batch_size) + extra_step,\n # workers=1,\n # use_multiprocessing=False,\n # verbose=1)\n\n print(\"Finished predicting %s of %s images\" %\n (preds.shape[0], len(image_paths)))\n # check size and log critical\n if preds.shape[0] != len(image_paths):\n print(\"Number of Preds %s don't match\" +\n \"number of images %s\" % (preds.shape[0], len(image_paths)))\n\n # save predictions\n self.preds = preds\n\n # Create a data frame with all predictions\n print(\"Creating Result DF\")\n res = self._create_result_df(path)\n\n # write DF to disk\n res.to_csv(output_path + output_file_name, index=False)\n\n def _create_result_df(self, filenames,\n image_directory=\"\"):\n \"\"\" Create Data Frame with Predictions \"\"\"\n\n # get max predictions & class ids\n id_max = np.argmax(self.preds, axis=1)\n max_pred = np.amax(self.preds, axis=1)\n\n # map class names and indices\n n_classes = len(self.class_list)\n\n # create result data frame via dictionary\n res = OrderedDict()\n\n # loop over all files / predictions\n for i in range(0, len(filenames)):\n fname = filenames[i].split(os.path.sep)[1]\n class_dir = filenames[i].split(os.path.sep)[0]\n\n p = max_pred[i]\n y_pred = self.class_list[id_max[i]]\n\n # store predictions for all classes\n p_all = self.preds[i, :]\n preds_all = {self.class_list[j]: p_all[j] for j in\n range(0, n_classes)}\n\n if image_directory == '':\n image_path = ''\n else:\n image_path = image_directory + os.path.sep + class_dir +\\\n os.path.sep + fname\n\n res[i] = OrderedDict([('file_name', fname),\n ('predicted_class', y_pred),\n ('predicted_probability', p),\n ('predictions_all', preds_all),\n ('image_path', image_path)])\n\n res_df = pd.DataFrame.from_dict(res, orient=\"index\")\n\n return res_df\n\n\nif __name__ == '__main__':\n pass\n\n model_file = \"D:/Studium_GD/Zooniverse/Data/transfer_learning_project/models/3663/mnist_testing_201708141308_model_best.hdf5\"\n pre_processing = ImageDataGenerator(rescale=1./255)\n pred_path = \"D:/Studium_GD/Zooniverse/Data/transfer_learning_project/images/3663/unknown\"\n output_path = \"D:/Studium_GD/Zooniverse/Data/transfer_learning_project/save/3663/\"\n class_list = [str(i) for i in range(0,10)]\n from config.config import cfg_path\n model_cfg_json = cfg_path['save'] + 'mnist_testing_201708141308_cfg.json'\n\n predictor = PredictorExternalTest(\n path_to_model=model_file,\n model_cfg_json=model_cfg_json)\n\n predictor.predict_path(path=pred_path, output_path=output_path)\n\n from config.config import cfg_path\n model_cfg_json = cfg_path['save'] + 'mnist_testing_201708141308_cfg.json'\n model_cfg_json\n cfg_file = open(model_cfg_json, 'r')\n model_cfg = json.load(cfg_file)\n model_cfg.keys()\n model_cfg['pre_processing']\n\n # preds.shape\n # preds.shape\n # generator.directory\n # generator.class_indices\n # generator.filenames\n # model.summary()\n\n\n\n # model_file = cfg_path['models'] +\\\n # 'cat_vs_dog_testing_201707111307_model_best' + '.hdf5'\n #\n # model_file\n # model = load_model(model_file)\n # model.get_config()\n # model\n\n\n\n\n\n # datagen = ImageDataGenerator(\n # rescale=1./255)\n #\n # generator = datagen.flow_from_directory(\n # cfg_path['images'] + 'val',\n # target_size=model.input_shape[1:3],\n # color_mode='rgb',\n # batch_size=256,\n # class_mode='sparse',\n # seed=123,\n # shuffle=False)\n # preds = model.predict_generator(\n # generator,\n # steps=(generator.n // 256)+1,\n # workers=2)\n # preds.shape\n # preds[0:5,:]\n # generator.\n\n\n # predictor = Predictor(mod_file='cat_vs_dog_testing_201707111307_model_best',\n # cfg_model=cfg_model,\n # cfg_path=cfg_path)\n #\n # res = predictor.predict_path(cfg_path['images'] + 'val')\n #\n # res.head\n\n\n # model_file\n # model = load_model(model_file)\n # model.get_config()\n # predictor = Predictor(mod_file='mnist_testing_201707231307_model_best',\n # cfg_model=cfg_model,\n # cfg_path=cfg_path)\n #\n # res = predictor.predict_dir(cfg_path['images'] + 'val')\n #\n # res.head\n\n # preds, nams, cl, cl_i = predictor.predict_dir(cfg_path['images'] + 'val')\n #\n # import numpy as np\n # import pandas as pd\n # id_max = np.argmax(preds, axis=1)\n # max_pred = np.amax(preds, axis=1)\n # y_true = cl\n # class_mapper = {v: k for k, v in cl_i.items()}\n #\n # # create result dictionary\n # res = pd.DataFrame(columns=('subject_id', 'image_id', 'y_true',\n # 'y_pred', 'p'))\n # i=0\n # for i in range(0, len(nams)):\n # subject_id = nams[i].split('\\\\')[1].split('_')[0]\n # image_id = nams[i].split('_')[1].split('.')[0]\n # p = max_pred[i]\n # y_true = cl[i]\n # y_pred = class_mapper[id_max[i]]\n # res.loc[i] = [subject_id, image_id, y_true, y_pred, p]\n #\n # res.head\n #\n #\n #\n #\n #\n #\n # tt = np.amax(preds, axis=1)\n # tt.shape\n # tt[0:10]\n #\n # preds.shape\n # preds[0:5,:]\n # nams[0:5]\n # nams[0]\n # class_mapper\n # cl_i\n","sub_path":"transfer_learning/tools/predictor_external_test.py","file_name":"predictor_external_test.py","file_ext":"py","file_size_in_byte":13757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"372495807","text":"import WAV\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport wave\nimport sys\nimport librosa\nfrom pydub import AudioSegment\nimport pandas as pd\nfrom datetime import datetime\nimport os \n\n# result[0] = 무호흡 환자 진단 카운팅 (수면 중 무호흡이라고 판단 된 횟수)\n# result[1] = 가장 큰 소음 dB\n# result[2] = 평균 소음 dB\n# result[3] = 수면중 무호흡 횟수\n\ndef Manage(file_name): #c => count, c_a = count_apnea\n\tcount = 0\n\tcount_apnea = 0\n\t#file = 'out_tests.wav'\n\tfile = file_name\n\tprint(file)\n\t#result = WAV.DeTect(n,str)\n\ttemp = WAV.DeTect(2,file)\n\tresult = [0,0,0,0]\n\tresult[0] = temp[0] # 무호흡 환자 진단 카운트\n\tresult[1] = temp[3] # 무호흡 횟수 카운트\n\tresult[2] = temp[1] #가장 큰 소음 dB\n\tresult[3] = temp[2] #평균 소음 dB\n\treturn result\n\t\ndef Max_period(file_name, Max_dB, email):\n\t'''\n\tspf = wave.open(file_name,'r')\n\tsignal = spf.readframes(-1)\n\tsignal = np.frombuffer(signal, dtype=np.int16)\n\tframerate = spf.getframerate()\n\n\ttemp_signal = signal.copy()\n\ttemp_signal = np.abs(temp_signal)\n\ttemp_Time = []\n\ttemp = 0\n\ttime = int(len(signal)/framerate) #음성 input 파일의 총 시간 구함\n\t\n\tfor i in range(0,time): #44100으로 sampling된 파일 1초 단위로 만들기\n\t\tfor j in range(0,framerate):\n\t\t\ttemp = temp + temp_signal[i*framerate + j]\n\t\ttemp_Time.append(temp/44100)\n\t\ttemp = 0\n\t'''\n\ty, sr = librosa.load(file_name)\n\tframerate = 22050\n\n\tabs_y = abs(y)\n\ttemp_Time = []\n\ttemp = 0\n\ttime = int(len(abs_y)/framerate) #음성 input 파일의 총 시간 구함\n\t\n\tfor i in range(0,time): #44100으로 sampling된 파일 1초 단위로 만들기\n\t\tfor j in range(0,framerate):\n\t\t\ttemp = temp + abs_y[i*framerate + j]\n\t\ttemp_Time.append(temp/framerate)\n\t\ttemp = 0\n\n\tmag = librosa.amplitude_to_db(np.array(temp_Time), ref=0.00002) #진폭 값 데시벨로 만들어 줌\n\tmag = np.around(mag)\n\t\n\t\n\tmax = np.where(mag==Max_dB)\n\tmax_term = max[0][0]\n\n\t###### 여기 부분은 수정이 필요함 #####\n\t\n\t# 지금은 현재 시간만으로 갖고 오는데 시간을 input 받아 갖고 올 수 있게 해야함\n\tnow = datetime.now()\n\tdate = str(now.year)+'-'+str(now.month)+'-'+str(now.day)\n\n\t################################\n\n\tif max_term-60 < 0 and max_term+60 > len(mag):\n\t\tdata = [range(0,len(mag)), mag]\n\telif max_term-60 < 0 and max_term+60 < len(mag):\n\t\tdata = [range(0,max_term+60), mag[0:max_term+60]]\n\telif max_term+60>len(mag) and max_term-60 > 0:\n\t\tdata = [range(max_term-60,len(mag)),mag[max_term-60:]]\n\telse:\n\t\tdata = [range(max_term-60,max_term+60),mag[max_term-60:max_term+60]]\n\t\n\tdataframe = pd.DataFrame(data)\n\n\t######### Max_dB가 있는 구간의 파형 csv 파일 이름 ##########\n\t# {user_id}/{date}.csv\n\t\n\tcsv_file_name = email+'/'+date+'.csv'\n\n\t#####################################################\n\n\ttry:\n\t\tif not(os.path.isdir(email)):\n\t\t\tos.makedirs(os.path.join(email))\n\texcept OSError as e:\n\t\tif e.errno != errno.EEXIST:\n\t\t\tprint(\"Failed to create directory!!!!!\")\n\t\t\traise\n\n\tdataframe.to_csv(csv_file_name,header=False, index=False)\n\ndef Manager(file_name, val,email,file_num):\t\n\tcount = val[0]\n\tcount_apnea = val[1]\n\tMax_dB = val[2]\n\tMean_dB = val[3]\n\tMax_dB_Time = 0\n\tvalue = [0,0,0,0,0] \n\tvalue[4] = val[4]\n\t'''\n\tvalue[0] = 수면중 무호흡 횟수 count_apnea\n\tvalue[1] = 현재 무호흡 상태 ==>무호흡 환자인지 아닌지 1>= 무호흡 환자, 그외 정상\n\tvalue[2] = Max dB\n\tvalue[3] = Mean_dB\n\tvalue[4] = Max dB file_name\n\t'''\n\n\tresult = Manage(file_name)\n\tcount = count + result[0]\n\tcount_apnea = count_apnea + result[1]\n\tif Max_dB > result[2] or Max_dB == 0:\n\t\tMax_dB = result[2]\n\t\tvalue[4] = file_num \n\tMean_dB = Mean_dB + result[3]\n\n\t\n\t\n\t\n\t#Max_period(file_name, Max_dB, email)\t#######\n\t# file_name = max_dB가 갖고 있는 file name\n\t# Max_dB = 수면 시간 중 최고 코골이 소리 \n\t# email = 사용자 id / 사용자 폴더를 찾기 위해 \n\t# date = 사용자 id 폴더 아래 날짜 폴더 안에 코골이 데시벨 csv 파일을 위치 시킬꺼\n\n\n\tvalue[0] = count_apnea\n\tvalue[1] = count\n\tvalue[2] = Max_dB\n\tvalue[3] = Mean_dB\n\t\n\treturn value \n\n#Manager(\"out_tests.wav\",[0,0,0,0,0], \"jimmy3663\", 2)","sub_path":"Server/Manager.py","file_name":"Manager.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"56406356","text":"import xmltodict\nfrom datacite import DataCiteMDSClient, schema40\nimport glob, json, datetime, re, getpass\nimport os, argparse, subprocess\nfrom epxml_support import download_records, update_repo_doi, cleanhtml\n\n\ndef epxml_to_datacite(eprint):\n\n metadata = {}\n\n # Transforming Metadata\n # Creators\n newa = []\n if isinstance(eprint[\"creators\"][\"item\"], list) == False:\n eprint[\"creators\"][\"item\"] = [eprint[\"creators\"][\"item\"]]\n for info in eprint[\"creators\"][\"item\"]:\n new = {}\n new[\"affiliations\"] = [\"California Institute of Technology\"]\n if \"orcid\" in info:\n idv = []\n nid = {}\n nid[\"nameIdentifier\"] = info[\"orcid\"]\n nid[\"nameIdentifierScheme\"] = \"ORCID\"\n idv.append(nid)\n new[\"nameIdentifiers\"] = idv\n name = info[\"name\"]\n new[\"creatorName\"] = name[\"family\"] + \", \" + name[\"given\"]\n new[\"givenName\"] = name[\"given\"]\n new[\"familyName\"] = name[\"family\"]\n newa.append(new)\n metadata[\"creators\"] = newa\n\n # Contributors\n newc = []\n if \"contributors\" in eprint:\n if isinstance(eprint[\"contributors\"][\"item\"], list) == False:\n # Deal with single item listings\n eprint[\"contributors\"][\"item\"] = [eprint[\"contributors\"][\"item\"]]\n for info in eprint[\"contributors\"][\"item\"]:\n new = {}\n new[\"affiliations\"] = [\"California Institute of Technology\"]\n if \"orcid\" in info:\n idv = []\n nid = {}\n nid[\"nameIdentifier\"] = info[\"orcid\"]\n nid[\"nameIdentifierScheme\"] = \"ORCID\"\n idv.append(nid)\n new[\"nameIdentifiers\"] = idv\n new[\"contributorType\"] = \"Other\"\n name = info[\"name\"]\n new[\"contributorName\"] = name[\"family\"] + \", \" + name[\"given\"]\n new[\"givenName\"] = name[\"given\"]\n new[\"familyName\"] = name[\"family\"]\n newc.append(new)\n if \"local_group\" in eprint:\n newc.append(\n {\n \"contributorName\": eprint[\"local_group\"][\"item\"],\n \"contributorType\": \"ResearchGroup\",\n }\n )\n metadata[\"contributors\"] = newc\n\n metadata[\"titles\"] = [{\"title\": eprint[\"title\"]}]\n metadata[\"publisher\"] = \"CaltechDATA\"\n if len(eprint[\"date\"]) != 4:\n metadata[\"publicationYear\"] = eprint[\"date\"].split(\"-\")[0]\n else:\n metadata[\"publicationYear\"] = eprint[\"date\"]\n metadata[\"resourceType\"] = {\"resourceTypeGeneral\": \"Dataset\"}\n\n if \"doi\" in eprint:\n metadata[\"identifier\"] = {\"identifier\": eprint[\"doi\"], \"identifierType\": \"DOI\"}\n else:\n metadata[\"identifier\"] = {\"identifier\": \"10.5072/1\", \"identifierType\": \"DOI\"}\n\n if \"other_numbering_system\" in eprint:\n ids = []\n if isinstance(eprint[\"other_numbering_system\"][\"item\"], list) == False:\n # Deal with single item listings\n eprint[\"other_numbering_system\"][\"item\"] = [\n eprint[\"other_numbering_system\"][\"item\"]\n ]\n for item in eprint[\"other_numbering_system\"][\"item\"]:\n print\n ids.append(\n {\n \"alternateIdentifier\": item[\"id\"],\n \"alternateIdentifierType\": item[\"name\"][\"#text\"],\n }\n )\n metadata[\"alternateIdentifiers\"] = ids\n\n metadata[\"descriptions\"] = [\n {\"descriptionType\": \"Abstract\", \"description\": cleanhtml(eprint[\"abstract\"])}\n ]\n metadata[\"language\"] = \"English\"\n\n # Subjects\n sub_arr = []\n if \"keywords\" in eprint:\n subjects = eprint[\"keywords\"].split(\";\")\n if len(subjects) == 1:\n subjects = eprint[\"keywords\"].split(\",\")\n for s in subjects:\n sub_arr.append({\"subject\": s.strip()})\n\n if \"classification_code\" in eprint:\n sub_arr.append({\"subject\": eprint[\"classification_code\"]})\n\n if len(sub_arr) != 0:\n metadata[\"subjects\"] = sub_arr\n\n if \"funders\" in eprint:\n array = []\n if isinstance(eprint[\"funders\"][\"item\"], list):\n for item in eprint[\"funders\"][\"item\"]:\n award = {}\n award[\"funderName\"] = item[\"agency\"]\n if \"grant_number\" in item:\n if item[\"grant_number\"] != None:\n award[\"awardNumber\"] = {\"awardNumber\": item[\"grant_number\"]}\n array.append(award)\n else:\n item = eprint[\"funders\"][\"item\"]\n award = {}\n award[\"funderName\"] = item[\"agency\"]\n if \"grant_number\" in item:\n if item[\"grant_number\"] != None:\n award[\"awardNumber\"] = {\"awardNumber\": item[\"grant_number\"]}\n array.append(award)\n metadata[\"fundingReferences\"] = array\n\n if \"rights\" in eprint:\n metadata[\"rightsList\"] = [{\"rights\": eprint[\"rights\"]}]\n\n if \"related_url\" in eprint:\n array = []\n if isinstance(eprint[\"related_url\"][\"item\"], list):\n for item in eprint[\"related_url\"][\"item\"]:\n if \"description\" in item:\n obj = {}\n obj[\"relationType\"] = \"IsSupplementedBy\"\n obj[\"relatedIdentifierType\"] = \"DOI\"\n obj[\"relatedIdentifier\"] = item[\"url\"]\n array.append(obj)\n\n else:\n item = eprint[\"related_url\"][\"item\"]\n if \"description\" in item:\n obj = {}\n obj[\"relationType\"] = \"IsSupplementedBy\"\n obj[\"relatedIdentifierType\"] = \"DOI\"\n obj[\"relatedIdentifier\"] = item[\"url\"]\n array.append(obj)\n metadata[\"relatedIdentifiers\"] = array\n\n # Dates\n dates = []\n dates.append({\"date\": eprint[\"datestamp\"], \"dateType\": \"Available\"})\n metadata[\"dates\"] = dates\n\n return metadata\n\n\ndef download_records(ids):\n username = input(\"Enter your CaltechAUTHORS username: \")\n password = getpass.getpass()\n\n for idv in ids:\n url = (\n \"https://\"\n + username\n + \":\"\n + password\n + \"@authors.library.caltech.edu/rest/eprint/\"\n )\n record_url = url + str(idv) + \".xml\"\n record = subprocess.check_output(\n [\"eputil\", record_url], universal_newlines=True\n )\n outfile = open(idv + \".xml\", \"w\")\n outfile.write(record)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"Make DataCite standard metadata for records from CaltechAUTHORS and register DOIs\"\n )\n parser.add_argument(\n \"-ids\", nargs=\"*\", help=\"CaltechAUTHORS IDs to download XML files\"\n )\n args = parser.parse_args()\n\n if len(args.ids) > 0:\n download_records(args.ids)\n\n files = glob.glob(\"*.xml\")\n for f in files:\n if \"datacite\" not in f:\n\n print(f)\n\n with open(f, encoding=\"utf8\") as fd:\n eprint = xmltodict.parse(fd.read())[\"eprints\"][\"eprint\"]\n print(eprint[\"title\"])\n\n metadata = epxml_to_datacite(eprint)\n\n # Validation fails on Windows\n valid = schema40.validate(metadata)\n # Debugging if this fails\n if valid == False:\n v = schema40.validator.validate(metadata)\n errors = sorted(v.iter_errors(instance), key=lambda e: e.path)\n for error in errors:\n print(error.message)\n\n xml = schema40.tostring(metadata)\n\n outname = f.split(\".xml\")[0] + \"_datacite.xml\"\n outfile = open(outname, \"w\", encoding=\"utf8\")\n outfile.write(xml)\n\n outname = f.split(\".xml\")[0] + \"_datacite.json\"\n outfile = open(outname, \"w\", encoding=\"utf8\")\n json.dump(metadata, outfile)\n","sub_path":"caltech_authors_to_data.py","file_name":"caltech_authors_to_data.py","file_ext":"py","file_size_in_byte":7895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"541634481","text":"\n\n# Create a function that prints the ingredient list of dictionaries to the console in the following format:\n#\n# +--------------------+---------------+----------+\n# | Ingredient | Needs cooling | In stock |\n# +--------------------+---------------+----------+\n# | vodka | Yes | 1 |\n# | coffee_liqueur | Yes | - |\n# | fresh_cream | Yes | 1 |\n# | captain_morgan_rum | Yes | 2 |\n# | mint_leaves | No | - |\n# +--------------------+---------------+----------+\n#\n# OPTIONAL:\n# The frist columns should be automatically as wide as the longest key\n\ningredients = [\n\t{ \"name\": \"vodka\", \"in_stock\": 1, \"needs_cooling\": True },\n\t{ \"name\": \"coffee_liqueur\", \"in_stock\": 0, \"needs_cooling\": True },\n\t{ \"name\": \"fresh_cream\", \"in_stock\": 1, \"needs_cooling\": True },\n\t{ \"name\": \"captain_morgan_rum\", \"in_stock\": 2, \"needs_cooling\": True },\n\t{ \"name\": \"mint_leaves\", \"in_stock\": 0, \"needs_cooling\": False },\n\t{ \"name\": \"sugar\", \"in_stock\": 0, \"needs_cooling\": False },\n\t{ \"name\": \"lime juice\", \"in_stock\": 0, \"needs_cooling\": True },\n\t{ \"name\": \"soda\", \"in_stock\": 0, \"needs_cooling\": True }\n]\n\ndef table_printer():\n\n long = len(ingredients[0]['name'])\n\n for i in range(len(ingredients)):\n if len(ingredients[i]['name']) > long:\n\n long = len(ingredients[i]['name']) + 1\n print(\"+\" + \"-\" * (long + 1) + \"+\" + \"-\" * 15 + \"+\" + \"-\" * 10 + \"+\")\n print(\"| Ingredient\" + \" \" * (long - 10) + \"|\" + \" Needs cooling\" + \" |\" + \" In stock \" + \"|\")\n print(\"+\" + \"-\" * (long + 1) + \"+\" + \"-\" * 15 + \"+\" + \"-\" * 10 + \"+\")\n\n for j in range(len(ingredients)):\n\n ingredient = ingredients[j]['name']\n needscool = str(ingredients[j]['needs_cooling'])\n instock = str(ingredients[j]['in_stock'])\n\n ingred = ingredient + \" \" * (long - len(ingredient))\n needsc = \" \" + needscool + \" \" * (14 - len(needscool))\n\n if instock == \"0\":\n instock = \"-\"\n\n instoc = \" \" + instock + \" \" * (9 - len(instock))\n print(\"| \" + ingred + \"|\" + needsc + \"|\" + instoc + \"|\")\n print(\"+\" + \"-\" * (long + 1) + \"+\" + \"-\" * 15 + \"+\" + \"-\" * 10 + \"+\")\n\ntable_printer()\n","sub_path":"week-02/day-03/dict05.py","file_name":"dict05.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"116889847","text":"# -*- encoding:utf-8 -*-\nfrom datetime import datetime, timedelta\nimport logging\n\nfrom odoo import api\nfrom odoo import models, fields\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n_logger = logging.getLogger(__name__)\n\n\nclass SyncDefine(models.Model):\n _inherit = 'his.sync_define'\n\n\n @api.model\n def sync_data_history(self):\n \"\"\"同步数据标记为历史\"\"\"\n register_obj = self.env['his.register']\n outpatient_fee_obj = self.env['his.outpatient_fee']\n dispose_send_obj = self.env['his.dispose_send']\n # drug_dispense_obj = self.env['his.drug_dispense']\n dispose_obj = self.env['his.dispose']\n\n # today = fields.Date.context_today(self)\n create_date = (datetime.now() - timedelta(days=2)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)\n\n # 病人挂号记录\n register_obj.search([('create_date', '<', create_date)]).unlink()\n # register_obj.search([('register_date', '<', today), ('is_history', '=', False)]).is_history = True\n\n # 门诊费用记录\n outpatient_fee_obj.search([('create_date', '<', create_date)]).unlink()\n # outpatient_fee_obj.search([('register_date', '<', today), ('is_history', '=', False)]).is_history = True\n\n # 病人医嘱发送\n dispose_send_obj.search([('create_date', '<', create_date)]).unlink()\n # dispose_send_obj.search([('send_date', '<', today), ('is_history', '=', False)]).is_history = True\n\n # 病人医嘱记录\n dispose_obj.search([('create_date', '<', create_date)]).unlink()\n # dispose_obj.search([('dispose_date', '<', today), ('is_history', '=', False)]).is_history = True\n\n # # 药品收发记录\n # drug_dispense_obj.search([('create_date', '<', create_date)]).unlink()\n # drug_dispense_obj.search([('check_date', '<', today), ('is_history', '=', False)]).is_history = True\n\n return super(SyncDefine, self).sync_data_history()\n\n","sub_path":"his_data_sync_hcfy/models/sync_define.py","file_name":"sync_define.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"226498212","text":"#!/usr/bin/python3\n'''\nView for state objects\n'''\n\nfrom models import storage\nfrom models.state import State\nfrom flask import jsonify, Flask, request, abort\nimport os\nfrom api.v1.views import app_views\n\n\n@app_views.route('/states/', methods=['GET'], strict_slashes=False)\ndef all_states():\n '''\n Retrieves the list of all State objects\n '''\n\n statesList = storage.all(State)\n states_dict = []\n for state in statesList:\n states_dict.append(statesList[state].to_dict())\n return jsonify(states_dict)\n\n\n@app_views.route('/states/', methods=['GET'], strict_slashes=False)\ndef get_state(state_id=None):\n '''\n Retrieve a State object\n '''\n\n stateObj = storage.get(State, state_id)\n if (stateObj):\n return (jsonify(stateObj.to_dict()))\n else:\n abort(404)\n\n\n@app_views.route(\n '/states/', methods=['DELETE'], strict_slashes=False)\ndef del_state(state_id=None):\n '''\n Delete a state object\n '''\n\n stateObj = storage.get(State, state_id)\n if (stateObj):\n storage.delete(stateObj)\n storage.save()\n return (jsonify({}), 200)\n\n else:\n abort(404)\n\n\n@app_views.route('/states/', methods=['POST'], strict_slashes=False)\ndef state_create():\n\n d = request.get_json()\n\n if isinstance(d, dict):\n pass\n else:\n return (jsonify({\"error\": \"Not a JSON\"}), 400)\n\n if 'name' not in d.keys():\n return jsonify({'error': 'Missing name'}), 400\n\n if 'id' in d.keys():\n d.pop(\"id\")\n if 'created_at' in d.keys():\n d.pop(\"created_at\")\n if 'updated_at' in d.keys():\n d.pop(\"updated_at\")\n\n obj = State(**d)\n\n storage.new(obj)\n storage.save()\n return jsonify(obj.to_dict()), 201\n\n\n@app_views.route('/states/', methods=['PUT'], strict_slashes=False)\ndef state_update(state_id=None):\n '''Updates an object '''\n state = storage.get(State, state_id)\n\n if state is None:\n return abort(404)\n\n data = request.get_json()\n\n if isinstance(data, dict):\n pass\n else:\n return (jsonify({\"error\": \"Not a JSON\"}), 400)\n\n if 'id' in data.keys():\n data.pop(\"id\")\n if 'created_at' in data.keys():\n data.pop(\"created_at\")\n if 'updated_at' in data.keys():\n data.pop(\"updated_at\")\n\n for key, value in data.items():\n setattr(state, key, value)\n\n storage.save()\n return (jsonify(state.to_dict()), 200)\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"72327012","text":"\"\"\" 1FE_compare_N.py\nThis file is a part of Cahn-Hilliard\nAuthors: Cristian Lacey, Sijie Tong, Amlan Sinha\nThis file contains an example of using the class CahnHilliard() to quickly loop\nover simulations with different input parameters.\n\"\"\"\nimport sys\nimport os\nimport time as time\nsrcDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/src'\nsys.path.insert(0,srcDir)\n\nfrom cahnhilliard import CahnHilliard\n\n# -------------------------------\n# INPUT PARAMETERS\n# -------------------------------\nglobal_inputs = {\n# 'N' : 100, # lattice points per axis\n# 'dx' : 0.5, # lattice spacing\n# 'dt' : 0.01, # timestep size\n# 'tsteps' : 10001, # number of timesteps\n'tol' : 1e-5, # convergence criterion for implicit methods (not used for explicit)\n\n# 'dump' : 1000, # dump an image every 'dump' steps\n'phi_avg' : 0, # initial mean value of phi\n'noise' : 0.1, # initial amplitude of fluctuations\n'seed' : 0, # seed for random initilization (use None for random output)\n\n#'spatial_method' : '2CD', # Choice of 2CD, 4CD\n# 'time_method' : '1FE', # Choice of 1FE, RK4, 1BE, 2CN\n'sparse_format' : 'csr', # Choice of dia, csc, csr\n\n'output_gif' : True,\n# 'output_path' : './output.gif',\n}\n\n# Can be easily looped over for multiple runs with different parameters.\n# (comment out looped over inputs in global_inputs dict, ie N, spatial method)\nspecific_inputs = [\n{'N':97,'dx':50/97,'spatial_method':'4CD','time_method':'1FE','dt' : 0.001,'tsteps' : 60001,'dump' : 6000,'output_path' : './output1.gif'},\n{'N':97,'dx':50/97,'spatial_method':'4CD','time_method':'RK4','dt' : 0.001,'tsteps' : 60001,'dump' : 6000,'output_path' : './output2.gif'},\n{'N':97,'dx':50/97,'spatial_method':'4CD','time_method':'1BE','dt' : 0.1,'tsteps' : 601,'dump' : 60,'output_path' : './output3.gif'},\n{'N':97,'dx':50/97,'spatial_method':'4CD','time_method':'2CN','dt' : 0.5,'tsteps' : 121,'dump' : 12,'output_path' : './output4.gif'},\n]\n\n# -------------------------------\n# MAIN\n# -------------------------------\nfor inp in specific_inputs:\n ch = CahnHilliard(**global_inputs,**inp)\n tStart = time.time()\n ch.run()\n tEnd = time.time()\n print('Time taken = '+str(tEnd-tStart))\n","sub_path":"analysis/impexp_runtime.py","file_name":"impexp_runtime.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"140349590","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nwith open('VERSION') as f:\n version = f.read().lstrip().rstrip()\n\nsetup(\n name='treecompare',\n version=version,\n description=\"simple module and tool to compare two directories\",\n url='https://github.com/mx-pycoder/treecompare',\n long_description=readme+\"\\n\\n\",\n author=\"Marnix Kaart\",\n author_email='mx@pycoder.nl',\n packages=['treecompare'],\n license=\"MIT license\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Intended Audience :: End Users/Desktop',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3 :: Only',\n ],\n keywords='diff tree compare duplicate',\n entry_points={\n 'console_scripts': ['treecompare=treecompare.cmdline:main'],\n },\n install_requires=[],\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"624479337","text":"import datetime\n\n\nclass Statistics:\n online_host_timedelta = datetime.timedelta(\n minutes=5,\n )\n online_worker_timedelta = datetime.timedelta(\n minutes=5,\n )\n\n def __init__(self):\n self.hosts = []\n\n def ensure_host(self, host):\n for current_host in self.hosts:\n if host == current_host:\n break\n else:\n self.hosts.append(host)\n\n def ensure_worker(self, host, worker):\n report_time = datetime.datetime.utcnow()\n\n for current_host in self.hosts:\n if host == current_host:\n for current_worker in current_host.workers:\n if current_worker == worker:\n current_worker.last_seen = report_time\n\n break\n else:\n current_host.workers.append(worker)\n worker.last_seen = report_time\n\n def report_worker(self, host, worker, message):\n for current_host in self.hosts:\n if host == current_host:\n for current_worker in current_host.workers:\n if current_worker == worker:\n current_worker.report(\n message=message,\n )\n\n @property\n def workers(self):\n workers = []\n\n for host in self.hosts:\n for worker in host.workers:\n workers.append(\n {\n 'host': host,\n 'worker': worker,\n }\n )\n\n return workers\n\n def get_statistics(self, statistics_type):\n value = 0\n\n for host in self.hosts:\n value += host.get_statistics(\n statistics_type=statistics_type,\n )\n\n return value\n\n @property\n def statistics(self):\n hosts = [\n {\n 'name': host.name,\n 'status': host.status,\n }\n for host in self.hosts\n ]\n\n workers = [\n {\n 'hostname': worker['host'].name,\n 'name': worker['worker'].name,\n 'status': worker['worker'].status,\n 'metrics': {\n 'failure': worker['worker'].get_statistics('failure'),\n 'retry': worker['worker'].get_statistics('retry'),\n 'success': worker['worker'].get_statistics('success'),\n 'process': worker['worker'].get_statistics('process'),\n }\n }\n for worker in self.workers\n ]\n\n statistics = {\n 'hosts': hosts,\n 'workers': workers,\n 'metrics': {\n 'success': self.get_statistics(\n statistics_type='success',\n ),\n 'failure': self.get_statistics(\n statistics_type='failure',\n ),\n 'retry': self.get_statistics(\n statistics_type='retry',\n ),\n 'process': self.get_statistics(\n statistics_type='process',\n ),\n 'heartbeat': self.get_statistics(\n statistics_type='heartbeat',\n ),\n },\n }\n\n return statistics\n","sub_path":"tasker/monitor/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"109130036","text":"import os\nimport random\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import load_model\n\nclass Predictor:\n def __init__(self):\n self.model = self.create_model()\n self.kinds = [\"★☆☆☆☆\", \"★★☆☆☆\", \"★★★☆☆\", \"★★★★☆\", \"★★★★★\"]\n\n # Special thanks to http://aidiary.hatenablog.com/entry/20170110/1484057655\n def create_model(self):\n self.graph = tf.get_default_graph()\n model = load_model(\"./nn/model.h5\")\n return model\n\n def predict_phrase(self, phrase):\n maxlen = 250\n test = np.zeros((1, maxlen), dtype = np.int64)\n for t, char in enumerate(phrase[-250:]):\n test[0, (250-1-t)] = ord(char)\n with self.graph.as_default():\n result = self.model.predict(test)\n index = result.argsort()[0][-1]\n return self.kinds[index], result\n","sub_path":"nn/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"471176654","text":"# --------------------------\r\n# USER: fco\r\n# DATE: 26/6/19\r\n# TIME: 11:14\r\n# --------------------------\r\n\r\nimport os\r\nimport datetime\r\n\r\nimport db\r\nimport journal\r\n\r\n\r\n# TODO: add offline mode: enter entries, save them in a file, and the next time the program is opened, upload them\r\n# TODO: add failed objectives\r\n\r\n\r\ndef inputList(asked):\r\n my_list = []\r\n s = \"\"\r\n while s != \"stop\":\r\n s = input(asked + \"?\")\r\n if len(s)>0:\r\n my_list.append(s)\r\n my_list.pop()\r\n print(asked + \":\" + str(my_list))\r\n return my_list\r\n\r\n\r\ndef askDate():\r\n # returns custom datetime object\r\n day = int(input(\"Day?\"))\r\n month = int(input(\"Month?\"))\r\n year = int(input(\"Year?\"))\r\n hour = int(input(\"Hour?\"))\r\n return datetime.datetime(year, month, day, hour)\r\n\r\n\r\ndef achievedObjs(ach):\r\n # deletes objectives from db that matches achievements\r\n for o in m1.getActiveObjs():\r\n for a in ach:\r\n if a == dict(o).get(\"objective\"):\r\n m1.setObjCompleted(a)\r\n\r\n\r\ndef askEntry():\r\n ok = \"no\"\r\n while ok != \"yes\":\r\n choice = ''\r\n # pedir fecha custom\r\n choice = input(\"Use custom date? (yes/no)\")\r\n if choice == 'yes':\r\n date = askDate()\r\n else:\r\n print(\"Using actual time\")\r\n date = datetime.datetime.now()\r\n\r\n author = input(\"User\")\r\n title = input(\"Title\")\r\n body = input(\"Body\")\r\n\r\n # print objectives that has not been yet completed\r\n print(\"Uncompleted objectives:\")\r\n for o in m1.getActiveObjs():\r\n print(o)\r\n objectives = inputList(\"New obj\")\r\n achievements = inputList(\"Achievements\")\r\n\r\n # calls achievedObjs() which deletes from db the achieved objectives\r\n achievedObjs(achievements)\r\n mood = int(input(\"Mood\"))\r\n sentimental = int(input(\"Sentimental\"))\r\n rating = 0\r\n work = int(input(\"Work\"))\r\n fun = int(input(\"Fun\"))\r\n\r\n # retrieve weights to calculate rating\r\n w = dict(m1.weights.find_one({\"_id\": 0}))\r\n rating = work * w.get(\"work\") + len(achievements) * w.get(\"achievements\") + mood * w.get(\r\n \"mood\") + fun * w.get(\"fun\") + sentimental * w.get(\"sentimental\")\r\n print(\"Calculated rating: \" + str(rating))\r\n tags = inputList(\"Tags\")\r\n\r\n e = journal.Entry(0, author, date, title, body, objectives, achievements, mood, rating, work, fun, sentimental,\r\n tags)\r\n\r\n # upload objectives to historial\r\n for obj in objectives:\r\n o = {\"date\": datetime.datetime.now(), \"objective\": obj,\r\n \"active\": \"True\"}\r\n m1.insertObjective(o)\r\n\r\n e.printEntry()\r\n ok = input(\"Upload? (yes/no)\")\r\n if ok != \"yes\":\r\n print(\"Asking entry again\")\r\n return askEntry()\r\n\r\n return e\r\n\r\n\r\n# Input con string and replaces with user given password\r\ndef auth(conStr):\r\n pwd = input(\"Password?\")\r\n return conStr.replace(\"\", pwd, 1)\r\n\r\n# Asks user for a connection string and saves it in a txt file\r\n\r\n\r\ndef createConStr(filepath):\r\n conStr = input(\"Connection string?\")\r\n choice = input(\"Save? (yes/no)\")\r\n if choice == \"yes\":\r\n # save file\r\n filename = input(\"Filename?\")\r\n f = open(filepath + \"/\" + filename, \"w+\")\r\n f.write(conStr)\r\n if len(os.stat(filepath + \"/\" + filename)) == 0:\r\n print(\"\\tERROR: could not create file\")\r\n return 0\r\n else:\r\n print(\"File created succesfully: %s\" % (filepath + \"/\" + filename))\r\n f.close()\r\n return conStr\r\n else:\r\n return createConStr(filepath)\r\n\r\n\r\n# Searchs for a mongo connection string and returns it. If there are none, asks for it\r\ndef askConStr():\r\n filepath = \"connections\"\r\n\r\n # search for connection strings in folder\r\n try:\r\n os.mkdir(filepath)\r\n print(\"Directory \", filepath, \" created\")\r\n except FileExistsError:\r\n None\r\n\r\n # show existing files\r\n if len(os.listdir(filepath)) == 0:\r\n print(\"No files in folder\")\r\n else:\r\n for i in os.listdir(filepath):\r\n print(\"\\t-\", i)\r\n\r\n choice = \"\"\r\n conStr = \"\"\r\n choice = input(\"Select file or create a new one? (select/new)\")\r\n if choice == \"select\":\r\n # select file from folder\r\n choice = input(\"Select file\")\r\n # if file not in folder\r\n if choice not in os.listdir(filepath):\r\n print(\"File not in folder\")\r\n return askConStr()\r\n else:\r\n # file selected\r\n f = open(filepath + \"/\" + choice, \"r\")\r\n conStr = f.read()\r\n f.close()\r\n choice = input(\"Use this connection string? (yes/no)\")\r\n if choice == \"yes\":\r\n return auth(conStr)\r\n else:\r\n return askConStr()\r\n\r\n elif choice == \"new\":\r\n # create new file in folder\r\n conStr = createConStr(filepath)\r\n choice = input(\"Use this connection string? (yes/no)\")\r\n if choice == \"yes\":\r\n return auth(conStr)\r\n else:\r\n return askConStr()\r\n else:\r\n print(\"Wrong input\")\r\n return askConStr()\r\n\r\n\r\ndef askWeights():\r\n work = 0.0\r\n fun = 0.0\r\n mood = 0.0\r\n sentimental = 0.0\r\n ach = 0.0\r\n\r\n # ask user for weights\r\n sum = 100\r\n while sum != 0:\r\n sum = 100\r\n print(\"Enter the weight for each attribute. Weights must be 0-100, all adding 100\")\r\n work = int(input(\"Work?\"))\r\n sum = sum - work\r\n print(\"Left: %d\" % sum)\r\n fun = int(input(\"Fun?\"))\r\n sum = sum - fun\r\n print(\"Left: %d\" % sum)\r\n mood = int(input(\"mood?\"))\r\n sum = sum - mood\r\n print(\"Left: %d\" % sum)\r\n sentimental = int(input(\"sentimental?\"))\r\n sum = sum - sentimental\r\n print(\"Left: %d\" % sum)\r\n ach = int(input(\"ach?\"))\r\n sum = sum - ach\r\n print(\"Left: %d\" % sum)\r\n if sum != 0:\r\n print(\"ERROR: weights must sum 100\")\r\n\r\n w = {\"_id\": 0, \"work\": work / 100, \"fun\": fun / 100, \"mood\": mood / 100, \"sentimental\": sentimental / 100,\r\n \"achievements\": ach / 100}\r\n return w\r\n\r\n\r\ndef printGlobalStats(n, today):\r\n # Print this year statss\r\n print(\"-----------\")\r\n print (\"Year stats:\")\r\n print(\"Entries: \", str(m1.getYearEntries(today)))\r\n print(\"Achievements: \", str(m1.getYearAchievements(today)))\r\n print(\"Avg rating:\", str(m1.getYearAvgRating(today)))\r\n # Print stats of the last n given days\r\n \r\n print(\"-----------\")\r\n print(\"Last \" + str(n) + \" days stats:\")\r\n print(\"Entries: \" + str(m1.nDaysEntries(n)))\r\n print(\"Achievements: \" + str(m1.nDaysAchs(n)))\r\n #FIXME\r\n #print(\"Avg rating: \" + str(m1.getnAvgRating(n)))\r\n\r\n\r\n# Program starts here\r\nm1 = db.Mongo(askConStr())\r\ntoday = datetime.datetime.now()\r\nprint(\"\\n\\n\\n\")\r\nmenuOption = 0\r\nprintGlobalStats(7, today)\r\nwhile menuOption != 7:\r\n print(\"=======================================\\nMENU\\n\"\r\n \"1. \\tAdd entry\\n\"\r\n \"2. \\tSee weights\\n\"\r\n \"3. \\tEdit weights\\n\"\r\n \"4. \\tSee last entries\\n\"\r\n \"5. \\tAdd new objectives\\n\"\r\n \"6. \\tSee stats\\n\"\r\n \"7. \\tExit\\n=======================================\\n\")\r\n menuOption = int(input(\"Choice?\"))\r\n if menuOption == 1:\r\n print(\"Selected: add entry\")\r\n # Ask entry and upload\r\n m1.insertEntry(askEntry())\r\n elif menuOption == 2:\r\n # Query weights and show\r\n print(\"Selected: see weights\")\r\n print(m1.getWeights())\r\n\r\n elif menuOption == 3:\r\n # Query weights, show weights and ask for new ones, then edit\r\n print(\"Selected: edit weights\")\r\n print(\"Actual weights\")\r\n print(m1.getWeights())\r\n w = askWeights()\r\n m1.editWeights(w)\r\n elif menuOption == 4:\r\n # print x last entries\r\n print(\"Selected: see last entries\")\r\n n = int(input(\"How many entries do you want to see?\"))\r\n e = list(m1.getLastEntries(n))\r\n for elem in e:\r\n print(elem)\r\n elif menuOption == 5:\r\n # manual objectives\r\n print(\"Selected: enter new objetives\")\r\n print(\"Uncompleted objectives:\")\r\n for o in m1.getActiveObjs():\r\n print(o)\r\n objectives = inputList(\"New obj\")\r\n\r\n for obj in objectives:\r\n o = {\"date\": datetime.datetime.now(), \"objective\": obj,\r\n \"active\": \"True\"}\r\n m1.insertObjective(o)\r\n\r\n elif menuOption == 6:\r\n # print stats of last n days\r\n print(\"Selected: see stats\")\r\n n = int(input(\"See stats from n last days. Days?\"))\r\n printGlobalStats(n)\r\n\r\n elif menuOption == 7:\r\n print(\"Exiting program. . .\")\r\n break\r\n else:\r\n print(\"ERROR: Wrong input. Choice must be 1 to 5\")\r\n","sub_path":"mainConsole.py","file_name":"mainConsole.py","file_ext":"py","file_size_in_byte":9018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"475372126","text":"import cv2\nimport time\nimport os\nimport math\n\nclass Scanner():\n\n def __init__(self, savepath, category = 'Unamed', cap_num = 1):\n self.countor = 0\n self.savepath = savepath\n self.category = category\n self.cap = cv2.VideoCapture(cap_num)\n self.angle = 0\n\n def get_next(self, frame):\n fullname = os.path.join(self.savepath, self.category+\n str(self.countor)+'.jpg')\n print(fullname)\n cv2.imwrite(fullname, frame)\n print('Written into ', fullname)\n self.countor += 1\n\n def start(self):\n self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1440)\n self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 780)\n while True:\n _, frame = self.cap.read()\n\n if self.angle == 0:\n cv2.imshow(\"See Window\", frame)\n else:\n cv2.imshow(\"See rotation\", self.rotation(frame, self.angle))\n k = cv2.waitKey(1) & 0xff\n if k == 32:\n self.get_next(frame)\n elif k == 114:\n print('rotate')\n self.angle = (self.angle+90) % 360\n elif k == 'q' or k & 0xff == 27:\n self.quitcap()\n\n def rotation(self, img, angle=90):\n height = img.shape[0]\n width = img.shape[1]\n\n if angle % 180 == 0:\n scale = 1\n elif angle%90 == 0:\n scale = float(max(height, width))/min(height, width)\n else:\n scale = math.sqrt(pow(height,2) + pow(width,2))/min(height, width)\n\n rotateMat = cv2.getRotationMatrix2D((width/2, height/2) , angle, scale=scale)\n rotateImg = cv2.warpAffine(img, rotateMat, (width, height))\n return rotateImg\n\n def quitcap(self):\n self.cap.release()\n print('Released capture')\n cv2.destroyAllWindows()\n\ndef main():\n Hello = Scanner('E:\\\\DeskTop\\\\capture', 'notes')\n Hello.start()\n\nif __name__ == '__main__':\n main()","sub_path":"PV/Formal/Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"535852819","text":"\"\"\"\nNotebook.00.py\n\nUsage: Notebook.00.py \n\nCommands: help\n quit\n delete \n dir\n\"\"\"\n\nimport sys\nimport json\n\ndef get_cmd():\n \"\"\"Get command, return as list, first element lowercase.\"\"\"\n\n while True:\n ans = input('> ')\n ans = ans.strip()\n if ans:\n result = ans.split()\n result[0] = result[0].lower()\n return result\n\ndef pause():\n input('Press ENTER to continue ')\n\ndef usage(msg=None):\n \"\"\"Print usage text with optional message.\"\"\"\n\n if msg:\n print('*' * 60)\n print(msg)\n print('*' * 60)\n print(__doc__)\n\ndef bad_cmd(cmd):\n \"\"\"Describe bad command.\"\"\"\n\n print(f\"Bad command: {' '.join(cmd)}\\n\")\n\ndef bad_title(title):\n \"\"\"Describe error: no such title.\"\"\"\n\n print(f\"No such title: '{title}'\\n\")\n\ndef notebook(notebook_path):\n \"\"\"Handle simple commands in a notebook.\"\"\"\n\n # open input notebook and get JSON dictionary\n try:\n with open(notebook_path) as fd:\n notebook = json.loads(fd.read())\n except FileNotFoundError:\n usage(f\"File '{notebook_path}' not found.\")\n sys.exit(1)\n\n while True:\n # get command string\n cmd = get_cmd()\n if ('|' + cmd[0]) in '|quit':\n return\n if cmd[0] == 'help':\n usage()\n elif cmd[0] == 'dir':\n for (key, value) in notebook.items():\n print(f'{key:20s} {value}')\n print()\n elif cmd[0] in ['del', 'delete']:\n # must have a second argument, the title\n if len(cmd) != 2:\n bad_cmd(cmd)\n continue\n title = cmd[1]\n try:\n del notebook[title]\n except KeyError:\n bad_title(title)\n else:\n bad_cmd(cmd)\n\n# get the input and output filenames and the text message\nif len(sys.argv) != 2:\n usage('Sorry, expected a notebook file')\n sys.exit(1)\n\nnotebook_path = sys.argv[1]\n\nnotebook(notebook_path)\n\n\n","sub_path":"Notebook/Notebook.00.py","file_name":"Notebook.00.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"60088891","text":"import os\nimport sys\nimport csv\nimport rx\nimport torch\nfrom rx.subject import Subject\nfrom yacs.config import CfgNode\nimport utils\nfrom network import RamanAINetwork\n\n\nclass PlotSaveHandler(rx.core.Observer):\n\n def __init__(self, cfg: CfgNode, cfg_dir=\".\"):\n super(PlotSaveHandler, self).__init__()\n self.base_path = utils.abs_or_offset_from(cfg.output.base_path, cfg_dir)\n\n os.makedirs(self.base_path, exist_ok=True)\n os.makedirs(os.path.join(self.base_path, \"weights\"), exist_ok=True)\n\n self.e = []\n self.train_loss = []\n self.val_loss = []\n self.plot_sub = Subject()\n\n def on_next(self, value) -> None:\n e = value[\"epoch\"]\n train_time = value[\"train_time\"]\n val_time = value[\"valid_time\"]\n train_loss = value[\"train_loss\"]\n val_loss = value[\"valid_loss\"]\n net: RamanAINetwork = value[\"net\"]\n\n print(f\"Epoch:{e}, train_loss={train_loss}, val_loss={val_loss}, train_time={train_time}, val_time={val_time}\")\n self.e.append(e)\n self.train_loss.append(train_loss)\n self.val_loss.append(val_loss)\n\n # save\n torch.save(net, os.path.join(self.base_path, \"weights\", f\"weights_{e}.pkl\"))\n\n self.plot_sub.on_next({\n \"epoch\": self.e,\n \"train\": self.train_loss,\n \"valid\": self.val_loss,\n \"test_output\": value[\"test_output\"],\n })\n\n def on_error(self, error: Exception) -> None:\n raise error\n\n def on_completed(self) -> None:\n print(\"Completed\")\n with open(os.path.join(self.base_path, f\"loss.csv\"), \"w\", newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"Epoch\", \"Train\", \"Valid\"])\n for e, t, v, in zip(self.e, self.train_loss, self.val_loss):\n writer.writerow([e, t, v])\n\n self.plot_sub.on_completed()","sub_path":"train_stream_handlers.py","file_name":"train_stream_handlers.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"369250398","text":"# class ContactList(list):\n# def search(self, name):\n# matching_contacts = []\n# for contact in self:\n# if name in contact.name:\n# matching_contacts.append(contact)\n# return matching_contacts\n#\n# class Contact:\n# all_contacts = ContactList()\n#\n# def __init__(self, name, email):\n# self.name = name\n# self.email = email\n# self.all_contacts.append(self)\n#\n# class Supplier(Contact):\n# def order(self, order):\n# print(\"If this were a real system we would send {} order to {}\".format(order, self.name))\n#\n# # class Friend(Contact):\n# # def __init__(self, name, email, phone):\n# # self.name = name\n# # self.email = email\n# # self.phone = phone\n#\n# contacts = Contact('contactexample', 'contactexample@mail.com')\n# supplier = Supplier('supplierexample', 'supplierexample@mail.com')\n# pizzeria = Supplier('pizzeria', 'pizza@mail.com')\n# # friend = Friend('john', 'john@mail.com', '07481755028')\n# print(contacts.all_contacts)\n# print([contact.name for contact in Contact.all_contacts.search('example')])\n# pizzeria.order('pizza')\n# contacts.order('pizza')\n\nclass Contact:\n all_contacts = []\n def __init__(self, name='', email='', **kwargs):\n super().__init__(**kwargs)\n self.name = name\n self.email = email\n self.all_contacts.append(self)\n\nclass AddressHolder:\n def __init__(self, street='', city='', state='', code='', **kwargs):\n super().__init__(**kwargs)\n self.street = street\n self.city = city\n self.state = state\n self.code = code\n\nclass Friend(Contact, AddressHolder):\n def __init__(self, phone='', **kwargs):\n super().__init__(**kwargs)\n self.phone = phone\n\ncontacts = Contact('contactexample', 'contactexample@mail.com')\n","sub_path":"inheritance/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"607101940","text":"# Made by disKret\r\nimport sys\r\nfrom net.sf.l2j.gameserver.model.quest import State\r\nfrom net.sf.l2j.gameserver.model.quest import QuestState\r\nfrom net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest\r\n\r\n#NPC\r\nCARADINE = 8740\r\nLADY_OF_LAKE = 8745\r\n\r\n#QUEST ITEM\r\nCARADINE_LETTER_LAST = 7679\r\nNOBLESS_TIARA = 7694\r\n\r\nclass Quest (JQuest) :\r\n\r\n def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)\r\n\r\n def onEvent (self,event,st) :\r\n htmltext = event\r\n cond = st.getInt(\"cond\") \r\n if event == \"8740-3.htm\" :\r\n if cond == 0 :\r\n st.set(\"cond\",\"1\")\r\n st.setState(STARTED)\r\n st.playSound(\"ItemSound.quest_accept\")\r\n elif event == \"8740-5.htm\" :\r\n if cond == 1 :\r\n st.set(\"cond\",\"2\")\r\n st.takeItems(CARADINE_LETTER_LAST,1)\r\n st.getPlayer().teleToLocation(143209,43968,-3038)\r\n elif event == \"8745-5.htm\" :\r\n if cond == 2 :\r\n st.set(\"cond\",\"0\")\r\n st.getPlayer().setNoble(True)\r\n st.giveItems(NOBLESS_TIARA,1)\r\n st.playSound(\"ItemSound.quest_finish\")\r\n st.setState(COMPLETED)\r\n return htmltext\r\n\r\n def onTalk (Self,npc,st):\r\n htmltext = \"<html><body>I have nothing to say to you.</body></html>\"\r\r\n npcId = npc.getNpcId()\r\n id = st.getState()\r\n if npcId != CARADINE and id != STARTED :\r\n return htmltext\r\n cond = st.getInt(\"cond\")\r\n if id == CREATED :\r\n st.set(\"cond\",\"0\")\r\n if st.getPlayer().isSubClassActive() :\r\n if npcId == CARADINE :\r\n if st.getQuestItemsCount(CARADINE_LETTER_LAST) == 1 :\r\n if cond in [0,1] :\r\n if id == COMPLETED :\r\n htmltext = \"<html><body>This quest has already been completed.</body></html>\"\r\n elif st.getPlayer().getLevel() < 75 : \r\n htmltext = \"8740-2.htm\"\r\n st.exitQuest(1)\r\n elif st.getPlayer().getLevel() >= 75 :\r\n htmltext = \"8740-1.htm\"\r\n elif cond == 2 :\r\n htmltext = \"8740-6.htm\"\r\n elif npcId == LADY_OF_LAKE and cond == 2 :\r\n htmltext = \"8745-1.htm\"\r\n else :\r\n htmltext = \"<html><body>This quest may only be undertaken by sub-class characters of level 75 or above.</body></html>\"\r\n return htmltext\r\n\r\nQUEST = Quest(247,\"247_PossessorOfAPreciousSoul_4\",\"Possessor Of A Precious Soul - 4\")\r\nCREATED = State('Start', QUEST)\r\nSTARTED = State('Started', QUEST)\r\nCOMPLETED = State('Completed', QUEST)\r\n\r\nQUEST.setInitialState(CREATED)\r\nQUEST.addStartNpc(CARADINE)\r\nQUEST.addTalkId(CARADINE)\r\nQUEST.addTalkId(LADY_OF_LAKE)","sub_path":"DataPack/data/scripts/quests/247_PossessorOfAPreciousSoul_4/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"247151430","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef obj_track(hsv_img, r=20):\n low = np.array([60 - r, 50, 100])\n high = np.array([60 + r, 255, 255])\n\n mask = cv2.inRange(hsv_img, low, high)\n return mask\n\n\nimgs = ['20160525_143739', '20160525_143754', 'photo_mm']\nlines = len(imgs)\n\ni = 1\nfor img in imgs:\n\n img = cv2.cvtColor(cv2.imread('data/%s.jpg' % img), cv2.COLOR_BGR2RGB)\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n plt.subplot(\"%s2%s\" % (lines, i)), plt.imshow(img)\n plt.subplot(\"%s2%s\" % (lines, i + 1)), plt.imshow(obj_track(hsv))\n\n i += 2\n\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"459287749","text":"import json\nimport logging\nimport os\nimport flask\nimport pymysql\nfrom datetime import date\nfrom flask import Flask, request, jsonify\nfrom flask_httpauth import HTTPBasicAuth\nfrom pymysql import IntegrityError\n\napp = Flask(__name__)\napp.config['JSON_SORT_KEYS'] = False # otherwise Flask would sort data alphabetically\nport = 1080\nauth = HTTPBasicAuth()\nlogging.basicConfig(level=logging.DEBUG)\n\nrest_base_url = '/info/v1'\n\n# Save env variables from run.sh\nDB_HOST = os.environ['DB_HOST']\nDB_PORT = int(os.environ['DB_PORT'])\nDB_USER = os.environ['DB_USER']\nDB_PASS = os.environ['DB_PASS']\nDB_DBNAME = os.environ['DB_DBNAME']\nHTTP_USER = os.environ['HTTP_USER']\nHTTP_PASS = os.environ['HTTP_PASS']\n\nUSER_DATA = {\n HTTP_USER: HTTP_PASS\n}\n\ntodays_date = date.today()\n\n@auth.verify_password\ndef verify(username, password):\n if not (username and password):\n return False\n return USER_DATA.get(username) == password\n\n\ndef con_db():\n return pymysql.connect(host=DB_HOST, port=DB_PORT, db=DB_DBNAME, user=DB_USER, password=DB_PASS)\n\n\ndef make_error(status_code, description):\n response = jsonify({\n 'description': description\n })\n response.status_code = status_code\n return response\n\n\ndef success():\n response = jsonify({\n 'description': 'Successful operation'\n })\n response.status_code = 200\n return response\n\n\n@app.route(rest_base_url + '/watch', methods=['POST'])\n@auth.login_required\ndef add_watch():\n con = con_db()\n watch = json.loads(request.data)\n sql = 'INSERT INTO watches (sku, type, status, gender, year, dial_material, ' \\\n 'dial_color, case_material, case_form, bracelet_material, movement)' \\\n 'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'\n\n # init variables empty, and try to fill them with values received from json.\n sku = typ = status = gender = year = ''\n try:\n sku = str(watch['sku'])\n typ = str(watch['type'])\n status = str(watch['status'])\n gender = str(watch['gender'])\n year = int(watch['year'])\n assert typ == 'watch' or typ == 'chrono', 'Allowed values for type [watch|chrono].'\n assert status == 'old' or status == 'current' or status == 'outlet', 'Allowed values for gender [old|current|outlet].'\n assert gender == 'man' or gender == 'woman', 'Allowed values for gender [man|woman]'\n\n assert valid_year(year), 'Year is invalid. Allowed range [1900 - {0}]'.format(todays_date.year)\n assert sku != '' and typ != '' and status != '' and gender != '' and year != '', 'sku, type, status, gender and year are mandatory fields!'\n except KeyError:\n return make_error(400, 'Invalid input')\n except ValueError:\n return make_error(400, 'Invalid input: Field has wrong value.')\n except AssertionError as e:\n return make_error(400, 'Invalid input: %s' % e)\n\n d_mat = d_color = c_mat = c_form = b_mat = mov = ''\n try:\n d_mat = str(watch['dial_material'])\n d_color = str(watch['dial_color'])\n c_mat = str(watch['case_material'])\n c_form = str(watch['case_form'])\n b_mat = str(watch['bracelet_material'])\n mov = str(watch['movement'])\n except ValueError:\n pass\n except KeyError:\n # does not matter if optional parameter has value or not\n pass\n\n try:\n with con.cursor() as cur:\n cur.execute(sql, (sku, typ, status, gender, year, d_mat, d_color,\n c_mat, c_form, b_mat, mov))\n except IntegrityError:\n return make_error(400, 'Invalid input: Watch already exists.')\n finally:\n con.commit()\n con.close()\n return success()\n\n\n@app.route(rest_base_url + '/watch/<sku>', methods=['GET', 'PUT', 'DELETE'])\n@auth.login_required\ndef query_watch(sku):\n con = con_db()\n select = 'SELECT * FROM watches WHERE sku LIKE %s'\n if request.method == 'GET':\n try:\n with con.cursor() as cur:\n cur.execute(select, sku)\n rows = cur.fetchall()\n if len(rows) != 1:\n return make_error(404, 'Watch not found')\n else:\n row_headers = [x[0] for x in cur.description] # this will extract row headers\n json_data = []\n for result in rows:\n json_data.append(dict(zip(row_headers, result)))\n response = flask.make_response(jsonify(json_data[0]))\n response.cache_control.max_age = 3600\n return response\n finally:\n con.commit()\n con.close()\n\n if request.method == 'PUT':\n sql = 'UPDATE watches SET '\n # check if clock exists\n try:\n with con.cursor(pymysql.cursors.DictCursor) as cur:\n cur.execute(select, sku)\n rows = cur.fetchall()\n if len(rows) != 1:\n return make_error(404, 'Watch not found')\n except ConnectionError:\n con.close()\n\n watch = json.loads(request.data)\n params = {}\n try:\n for key in watch:\n # Validation\n if 'type' == key:\n assert str(watch[key]) == 'watch' or str(watch[key]) == 'chrono', 'Allowed values for type [' \\\n 'watch|chrono] '\n if 'status' == key:\n assert str(watch[key]) == 'old' or str(watch[key]) == 'current' or str(watch[key]) == 'outlet' \\\n , 'Allowed values for gender [old|current|outlet]'\n if 'gender' == key:\n assert str(watch[key]) == 'man' or str(watch[key]) == 'woman', 'Allowed values for gender [' \\\n 'man|woman] '\n if 'year' == key:\n assert valid_year(watch[key]), 'Year is invalid. Allowed range [1900 - {0}]'.format(todays_date.year)\n\n params[key] = str(watch[key])\n\n except KeyError:\n return make_error(400, 'Invalid input: Provide values for all mandatory parameters!')\n except AssertionError as e:\n return make_error(400, 'Invalid inputs: %s' % e)\n except ValueError:\n return make_error(400, 'Invalid input: ValueError')\n\n try:\n first_param = True\n with con.cursor() as cur:\n # building SQL query\n for key in params:\n if first_param:\n first_param = False\n sql = sql + key + '=\\'' + params[key] + '\\''\n else:\n sql = sql + ' , ' + key + '=\\'' + params[key] + '\\''\n sql = sql + ' WHERE sku =\\'' + sku + '\\''\n\n cur.execute(sql)\n\n except IntegrityError:\n return make_error(400, 'Invalid input: Watch with this sku already exists')\n finally:\n con.commit()\n con.close()\n return success()\n\n if request.method == 'DELETE':\n sql = 'DELETE FROM watches WHERE sku LIKE %s'\n try:\n with con.cursor() as cur:\n cur.execute(select, sku)\n rows = cur.fetchall()\n if len(rows) != 1:\n return make_error(404, 'Watch not found')\n else:\n cur.execute(sql, sku)\n finally:\n con.commit()\n con.close()\n return success()\n\n\n@app.route(rest_base_url + '/watch/complete-sku/<prefix>', methods=['GET'])\n@auth.login_required\ndef get_list_by_prefix(prefix):\n con = con_db()\n sql = 'SELECT sku FROM watches WHERE sku LIKE %s'\n try:\n with con.cursor() as cur:\n cur.execute(sql, (prefix + '%',))\n rows = cur.fetchall()\n json_data = []\n for result in rows:\n json_data.append(result[0])\n response = flask.make_response(jsonify({'sku': json_data}))\n response.cache_control.max_age = 3600\n return response\n finally:\n con.commit()\n con.close()\n\n\n@app.route(rest_base_url + '/watch/find', methods=['GET'])\n@auth.login_required\ndef get_list_by_criteria():\n con = con_db()\n # building SQL query\n sql = 'SELECT * FROM watches WHERE '\n sql_and = ' AND '\n params = {'sku': request.args.get('sku'),\n 'type': request.args.get('type'),\n 'status': request.args.get('status'),\n 'gender': request.args.get('gender'),\n 'year': request.args.get('year')}\n\n first_param = True\n for key, value in params.items():\n if value is not None:\n if first_param:\n if key == 'sku':\n sql = sql + key + ' LIKE \\'' + value + '%\\''\n else:\n sql = sql + key + '=\\'' + value + '\\''\n first_param = False\n else:\n if key == 'sku':\n sql = sql + sql_and + key + ' LIKE \\'' + value + '%\\''\n else:\n sql = sql + sql_and + key + '=\\'' + value + '\\''\n\n logging.info(sql) #see SQL query in console\n\n try:\n with con.cursor() as cur:\n cur.execute(sql)\n rows = cur.fetchall()\n if len(rows) == 0:\n return make_error(404, 'Watch not found')\n else:\n row_headers = [x[0] for x in cur.description] # this will extract row headers\n json_data = []\n for result in rows:\n json_data.append(dict(zip(row_headers, result)))\n response = flask.make_response(jsonify(json_data))\n response.cache_control.max_age = 3600\n return response\n finally:\n con.commit()\n con.close()\n\n\ndef valid_year(year):\n if year:\n return 1900 <= int(year) <= todays_date.year\n return False\n\n\nif __name__ == '__main__':\n print('server listening on port: ' + str(port))\n app.run(port=port, debug=True, host='0.0.0.0')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572329021","text":"import torch.nn.functional as F\nfrom driver.Utils import *\nimport torch.optim.lr_scheduler\nfrom driver.Layer import *\nimport numpy as np\n\n\nclass SRLLabeler(object):\n def __init__(self, model):\n self.model = model\n p = next(filter(lambda p: p.requires_grad, model.parameters()))\n self.use_cuda = p.is_cuda\n self.device = p.get_device() if self.use_cuda else None\n\n def forward(self, words, extwords, predicts, inmasks, bert_hidden):\n if self.use_cuda:\n words, extwords = words.cuda(self.device), extwords.cuda(self.device)\n predicts = predicts.cuda(self.device)\n inmasks = inmasks.cuda(self.device)\n bert_hidden = bert_hidden.cuda()\n\n label_scores = self.model.forward(words, extwords, predicts, inmasks, bert_hidden)\n # cache\n self.label_scores = label_scores\n\n\n def compute_loss(self, answers, outmasks):\n if self.use_cuda:\n answers = answers.cuda(self.device)\n outmasks = outmasks.cuda(self.device)\n loss = self.model.compute_loss(self.label_scores, answers, outmasks)\n stats = self.stats(loss.item(), self.label_scores.data, answers.data)\n return loss, stats\n\n def stats(self, loss, scores, target):\n \"\"\"\n Compute and return a Statistics object.\n Args:\n loss(Tensor): the loss computed by the loss criterion.\n scores(Tensor): a sequence of predict output with scores.\n \"\"\"\n pred = scores.max(2)[1]\n non_padding = target.ne(self.model.PAD)\n num_words = non_padding.sum()\n num_correct = pred.eq(target).masked_select(non_padding).sum()\n return Statistics(loss, num_words, num_correct)\n\n\n def label(self, words, extwords, predicts, inmasks, bert_hidden):\n if words is not None:\n self.forward(words, extwords, predicts, inmasks, bert_hidden)\n\n predict_labels = self.model.decode(self.label_scores, inmasks)\n\n return predict_labels\n\n","sub_path":"CrossLanguageOPMining-bert-2languageTrain-PGNAdapter/driver/Labeler.py","file_name":"Labeler.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"347563829","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom matplotlib import colors\nfrom collections import Counter\nimport networkx as nx\n\n\ndef get_data_will(fname, ratio):\n \"\"\"get data edge list from file. should return an (n,2) array of edges\"\"\"\n f = open(fname, 'r')\n [next(f) for _ in range(5)]\n n_edges = int(f.readline())\n print(n_edges)\n\n res = []\n for _ in range(n_edges):\n line = list(map(int, f.readline().strip().split(' ')))\n res += [line]\n res = np.array(res)\n links = res[:, :2]\n clusters = res[:, 2]\n nodes = list(set(links.flatten()))\n sz = int(links.flatten().max() + 1)\n adj = np.zeros((sz, sz), dtype=int)\n\n # node clusters\n next(f) # skip blank line\n node_cluster = [list(map(int, line.strip().split(' '))) for line in f]\n\n idxperm = np.random.permutation(len(links))\n cutp = math.floor(len(links) * ratio)\n idx_train = idxperm[:cutp]\n idx_test = idxperm[cutp:]\n links_train = links[idx_train, :]\n links_test = links[idx_test, :]\n clusters_train = clusters[idx_train]\n clusters_test = clusters[idx_test]\n\n for e, c in zip(links, clusters):\n adj[e[0], e[1]] = c + 5\n\n return links_train, links_test, clusters_train, clusters_test, nodes, node_cluster\n\n\ndef get_data_simple(fname):\n \"\"\"get data edge list from file. should return an (n,2) array of edges\"\"\"\n f = open(fname, 'r')\n res = np.array([list(map(int, line.strip().split(' '))) for line in f], dtype=int)\n nodes = list(set(res.flatten()))\n sz = int(res.flatten().max() + 1)\n adj = np.zeros((sz, sz), dtype=int)\n\n for e in res:\n adj[e[0], e[1]] += 1\n\n return res, nodes, adj\n\n\ndef display_adjacency(edges, clusters=None):\n cmap = colors.ListedColormap(['white', 'red', 'green', 'blue', 'yellow', 'purple', 'orange', 'brown', 'black'])\n bounds = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n norm = colors.BoundaryNorm(bounds, cmap.N)\n count = Counter(clusters).most_common()\n count = [c[0] for c in count]\n temp = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n color = {count[x]: temp[x] if x < 8 else temp[8] for x in range(len(count))}\n sz = edges.max(axis=1).max() + 1\n adj = np.zeros([sz, sz], dtype=int)\n for e, c in zip(edges, clusters):\n adj[e[0], e[1]] = color[c]\n plt.imshow(adj, cmap=cmap, norm=norm)\n plt.show()\n\n\ndef display_graphx(edges, clusters=None):\n \"\"\"\n Given 2d array of edges, plot 2d embedding of nodes using force-directed.\n :param edges:\n :param clusters:\n :return:\n \"\"\"\n plt.set_cmap('gist_rainbow')\n g = nx.DiGraph()\n unique_edges = []\n unique_clusters = []\n for i, e in enumerate(edges):\n if g.has_edge(e[0], e[1]):\n continue\n else:\n g.add_edge(e[0], e[1])\n unique_edges += [(e[0], e[1])]\n unique_clusters += [clusters[i]]\n\n pos = nx.spring_layout(g)\n node = sorted([i for i in pos.keys()])\n nx.draw_networkx_nodes(g, pos, nodelist=node, node_size=30)\n nx.draw_networkx_edges(g, pos, edgelist=unique_edges, edge_color=unique_clusters, width=0.5)\n plt.show()\n\n\nif __name__ == '__main__':\n links_train, links_test, clusters_train, clusters_test, nodes, node_cluster = get_data_will('toy_test', ratio=1)\n # links_train = links_train.tolist()\n # trunfreeInfiniteClusterDirichletMix()\n print(node_cluster)\n display_graphx(links_train, clusters_train)\n","sub_path":"csli_presentation/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"150864691","text":"\n\n#calss header\nclass _CONSTITUTION():\n\tdef __init__(self,): \n\t\tself.name = \"CONSTITUTION\"\n\t\tself.definitions = [u'the set of political principles by which a state or organization is governed, especially in relation to the rights of the people it governs: ', u\"the general state of someone's health: \", u'how something is made up of different parts: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_constitution.py","file_name":"_constitution.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"607587223","text":"# -*- coding: utf-8 -*-\nfrom time import strptime\nfrom datetime import date, datetime, time, timedelta\nfrom calendar import monthrange\nfrom string import uppercase\nfrom decimal import Decimal\nimport xlwt\n\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.context_processors import csrf\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom django.db.models import F # updated__gte=F('added_toSolr_date')\n\nfrom finance.models import *\nfrom contract.models import Visits\nfrom core.models import User\nfrom employees.models import (\n Visits as eVisits, Shift, Timetable, WorkRecord, Employee)\nfrom reception.models import GuestVisits\nfrom organizer.models import Guest as OGuest\nfrom .models import *\nfrom .forms import *\nfrom .dbmodels import *\nfrom .styles import *\n\nreport_top_prefix = settings.REPORT_TOP_PREFIX\npay_type = (u'нал.', u'без нал.', u'иное')\n\n\n@login_required(login_url='/login')\ndef manager_sells(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=manager_sells.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"manager_sells\")\n\n columns = []\n columns.append((u'Дата покупки', 4000))\n columns.append((u'ФИО ', 10000, ))\n columns.append((u'Наименование услуги', 6000))\n columns.append((u'Стоимость', 6000))\n columns.append((u'Скидка', 6000))\n columns.append((u'Внесенная сумма', 6000))\n head = u'Отчет по продажам менеджеров с: ' + s_date.strftime(\"%d.%m.%Y\")\n head += u' по: ' + e_date.strftime(\"%d.%m.%Y\")\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n row_num = 1\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 35*20\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n manager = 0\n manager_name = ''\n total_man = 0\n total = 0\n for ch in ManagerSells.objects.filter(\n date__range=(s_date, e_date), selltype__gt=0, firstptt=1\n ).order_by('manager', 'date'):\n row_num += 1\n total_man += ch.amount\n total += ch.amount\n if manager != ch.manager.pk:\n if manager > 0:\n ws.write_merge(\n row_num, row_num, 0, len(columns)-1,\n u'Итого по ' + manager_name + ': ' + str(total_man),\n styleth)\n total_man = 0\n row_num += 1\n manager = ch.manager.pk\n manager_name = ch.manager.initialsC()\n ws.write_merge(\n row_num, row_num, 0, len(columns)-1,\n u'Продавец: ' + manager_name, styleth)\n row_num += 1\n\n if ch.selltype == 1:\n # Contract data\n client = ch.contract.client.initialsC()\n if ch.contract.date_joined.date() == ch.date.date():\n goodsname = ch.contract.contract_type.name\n else:\n goodsname = ch.contract.contract_type.name + u' доплата'\n price = ch.contract.amount\n if ch.contract.discount:\n discount = ch.contract.discount.value\n else:\n discount = None\n else:\n client = ch.client.initialsC()\n goodsname = ch.goods.name\n price = ch.goods.priceondate(ch.date)\n discount = None\n\n ws.write(row_num, 0, ch.date.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 1, client, style)\n ws.write(row_num, 2, goodsname, style)\n ws.write(row_num, 3, price, style)\n ws.write(row_num, 4, discount, style)\n ws.write(row_num, 5, ch.amount, style)\n\n row_num += 1\n ws.write_merge(\n row_num, row_num, 0, len(columns)-1,\n u'Итого по ' + manager_name + ': ' + str(total_man), styleth)\n row_num += 1\n ws.write_merge(\n row_num, row_num, 0, len(columns)-1, u'Итого по всем: ' + str(total),\n styleth)\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef contract_end(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=contract_end.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"contract_end\")\n\n columns = []\n columns.append((u'ФИО ', 10000, ))\n columns.append((u'Телефон', 6000))\n columns.append((u'Вид контракта', 6000))\n columns.append((u'Дата покупки', 4000))\n columns.append((u'Номер контракта', 4000))\n columns.append((u'Дата начала', 4000))\n columns.append((u'Дата окончания', 4000))\n columns.append((u'ФИО менеджера', 8000))\n columns.append((u'Активный', 4000))\n\n head = u'Отчет об окончании контракта с: ' + s_date.strftime(\"%d.%m.%Y\")\n head += u' по: ' + e_date.strftime(\"%d.%m.%Y\")\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n row_num = 1\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 35*20\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n s_date = s_date + timedelta(days=1)\n e_date = e_date + timedelta(days=1)\n client_has_new = Contract.objects.filter(is_current=2).values('client')\n contracts = Contract.objects.select_related('client')\n contracts_end = contracts.filter(\n date_end__gte=s_date, date_end__lte=e_date).exclude(is_current=3)\n exclude_prlongation = contracts_end.exclude(client__in=client_has_new)\n clients = []\n for c in exclude_prlongation.order_by('client__manager', 'date_end'):\n if c.client in clients:\n continue\n clients.append(c.client)\n row_num += 1\n is_active = 'да' if c.client.is_active else 'нет'\n date_end = (c.date_end - timedelta(days=1)).strftime(\"%d.%m.%Y\")\n ws.write(row_num, 0, c.client.initialsC(), style)\n ws.write(row_num, 1, c.client.phone, style)\n ws.write(row_num, 2, c.contract_type.name, style)\n ws.write(row_num, 3, c.date_joined.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 4, c.number, style)\n ws.write(row_num, 5, c.date_start.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 6, date_end, styled)\n ws.write(row_num, 7, c.client.manager.initialsC(), style)\n ws.write(row_num, 8, is_active, style)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef trainer_ptt(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=trainer_ptt.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"trainer_ptt\", cell_overwrite_ok=True)\n head_data = s_date.strftime(\"%d.%m.%Y\"), e_date.strftime(\"%d.%m.%Y\")\n head = u'Статистика по тренерам с %s по %s' % head_data\n columns = []\n columns.append((u'Наименование услуги', 6000))\n columns.append((u'Дата продажи', 8000))\n columns.append((u'Стоимость', 6000))\n\n row_num = 0\n ws.write_merge(row_num, 0, 0, len(columns)-1, head, styleh)\n\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n ch = CreditsHistory.objects.filter(\n date__range=(s_date, e_date), employee__isnull=False\n ).values('employee')\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n\n for t in Employee.objects.filter(\n pk__in=ch).order_by('lastname', 'firstname'):\n row_num += 1\n fname = t.lastname.title(), t.firstname.title(), t.patronymic.title()\n fullname = u'Тренер: %s %s %s' % fname\n ws.write_merge(row_num, row_num, 0, len(columns)-1, fullname, styleth)\n total = 0\n for cr in CreditsHistory.objects.filter(\n date__range=(s_date, e_date), employee=t):\n row_num += 1\n total += cr.amount\n ws.write(row_num, 0, cr.goods.name, style)\n ws.write(row_num, 1, cr.date.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 2, cr.amount, stylef)\n row_num += 1\n total_str = u'Итого по %s:' % (t.initials(),)\n ws.write(row_num, 0, total_str, styleth)\n # ws.write(row_num, 1, )\n ws.write_merge(row_num, row_num, 1, len(columns)-1, total, stylethf)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef employees(request, ):\n d = datetime.now()\n month = int(d.month)\n year = int(d.year)\n day = int(d.day)\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=employees.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"employees\", cell_overwrite_ok=True)\n head_data = day, month_name_ru(month), year\n head = u'Список сотрудников по состоянию на: %s/%s/%s' % head_data\n columns = []\n columns.append((u'№', 2000))\n columns.append((u'ФИО', 8000))\n columns.append((u'Должность', 6000))\n columns.append((u'Телефон', 6000))\n\n row_num = 0\n ws.write_merge(row_num, 0, 0, len(columns)-1, head, styleh)\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n wr = WorkRecord.objects.filter(date_end__isnull=True).values('employee')\n row_cnt = 0\n for e in Employee.objects.filter(pk__in=wr).order_by('lastname'):\n row_num += 1\n row_cnt += 1\n fname = e.lastname.title(), e.firstname.title(), e.patronymic.title()\n fullname = '%s %s %s' % fname\n position = e.currwork().wposition.position.name\n ws.write(row_num, 0, row_cnt, style)\n ws.write(row_num, 1, fullname, style)\n ws.write(row_num, 2, position, style)\n ws.write(row_num, 3, e.phone, style)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef debtors_menu(request, ):\n m_list = User.objects.filter(groups__name='manager') # manual create\n context_dict = dict(request=request, m_list=m_list)\n return render_to_response('r_debtors.html', context_dict)\n\n\n@login_required(login_url='/login')\ndef debtors(request, manager, ):\n manager = User.objects.filter(groups__name='manager', id=int(manager))\n if manager.count() != 1:\n return HttpResponse(u'Not exist manager', mimetype='text/html')\n else:\n manager = manager[0]\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"debtors\", cell_overwrite_ok=True)\n head = u'отчет по должникам по рассрочкам \\n'\n head += u'Менеджер: ' + manager.initials()\n\n columns = []\n columns.append((u'ФИО клиента', 8000))\n columns.append((u'Телефон', 6000))\n columns.append((u'Номер контракта', 4000))\n columns.append((u'Вид контракта', 6000))\n columns.append((u'Дата покупки', 4000))\n columns.append((u'Дата окончания', 4000))\n columns.append((u'Схема рассрочки', 6000))\n columns.append((u'Стоимость (с учетом скидки)', 5000))\n columns.append((u'Сумма оплаты', 4000))\n columns.append((u'Сумма задолжности на текущий момент', 5000))\n columns.append((u'Остаток задолжности', 5000))\n\n row_num = 0\n ws.write_merge(row_num, 0, 0, len(columns)-1, head, styleh)\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 25*20\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n row_num = 1\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 35*20\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n row_num = 2\n clients = Client.objects.filter(manager=manager)\n # contracts = Contract.objects.filter(client__in=clients)\n contracts = Credits.objects.filter(\n contract__isnull=False, plan_date__lte=datetime.now()\n ).values('contract')\n for c in Contract.objects.filter(client__in=clients, pk__in=contracts, ):\n # for cr in Credits.objects.filter(contract__in=contracts):\n ws.write(row_num, 0, c.client.initialsC(), style)\n ws.write(row_num, 1, c.client.phone, style)\n ws.write(row_num, 2, c.number, style)\n ws.write(row_num, 3, c.contract_type.name, style)\n ws.write(row_num, 4, c.date_joined.strftime(\"%d.%m.%Y\"), styledt)\n ws.write(row_num, 5, c.date_end.strftime(\"%d.%m.%Y\"), styledt)\n if c.pay_plan:\n if c.pay_plan.plantype < 2:\n ws.write(row_num, 6, c.pay_plan.name, style)\n else:\n ws.write(row_num, 6, u'индивидуальная', style)\n else:\n ws.write(row_num, 6, '', style)\n ws.write(row_num, 7, c.amount, stylef)\n # the payments has done\n payments = CreditsHistory.objects.filter(\n contract=c).aggregate(Sum('amount'))\n if payments['amount__sum']:\n payments = payments['amount__sum']\n else:\n payments = 0\n ws.write(row_num, 8, payments, stylef)\n # the credits sum\n credits = Credits.objects.filter(\n contract=c, plan_date__lte=datetime.now()\n ).aggregate(Sum('amount'))\n credits = credits['amount__sum']\n ws.write(row_num, 9, credits, stylef)\n last_credits = Credits.objects.filter(\n contract=c, plan_date__gte=datetime.now()\n ).aggregate(Sum('amount'))\n last_credits = last_credits['amount__sum']\n ws.write(row_num, 10, last_credits, stylef)\n row_num += 1\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef manager(request, year, month):\n year = int(year)\n month = int(month)\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"manager\", cell_overwrite_ok=True)\n head = u'отчет менеджера за: ' + month_name_ru(month) + ' '\n head += str(year) + u'года'\n\n columns = []\n columns.append((u'дата ', 4000))\n columns.append((u'Номер контракта', 4000))\n columns.append((u'Вид контракта', 6000))\n columns.append((u'Скидка', 4000))\n columns.append((u'Продление / впервые', 4000))\n columns.append((u'Номер карты', 6000))\n columns.append((u'ФИО клиента', 8000))\n columns.append((u'Оплата: полная / рассрочка', 3000))\n columns.append((u'Вид оплаты', 4000))\n columns.append((u'Стоимость', 4000))\n columns.append((u'Взнос', 4000))\n columns.append((u'Доплата', 4000))\n columns.append((u'Фактическая оплата', 8000))\n columns.append((u'ФИО менеджера', 8000))\n columns.append((u'Итого за день', 6000))\n columns.append((u'ФИО продовца', 8000))\n\n row_num = 0\n ws.write_merge(row_num, 0, 0, len(columns)-1, head, styleh)\n\n alignment = xlwt.Alignment()\n alignment.wrap = 1\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n styleth.alignment = alignment\n row_num = 1\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 35*20\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n first_text = (u'Повторно', u'Впервые', u'')\n day_summ = 0\n mdays = monthrange(year, month)[1]\n for d in xrange(mdays):\n day = d + 1\n d = date(year, month, day)\n if day_summ > 0:\n ws.write(row_num, 14, day_summ, style)\n day_summ = 0\n for cr in CreditsHistory.objects.filter(\n date__month=month, date__year=year, date__day=day,):\n if cr.contract:\n c = cr.contract\n row_num += 1\n if c.date_joined.date() == d:\n contribution = cr.amount\n e_pay = ''\n if c.is_first():\n first = 1\n else:\n first = 0\n else:\n contribution = ''\n e_pay = cr.amount\n first = 2\n\n if c.pay_plan:\n pplan = u'Рассрочка'\n else:\n pplan = u'Полная'\n ws.write(row_num, 1, c.number, style)\n ws.write(row_num, 2, c.contract_type.name, style)\n ws.write(row_num, 4, first_text[first], style)\n ws.write(row_num, 5, c.card, style)\n ws.write(row_num, 6, c.client.initialsC(), style)\n ws.write(row_num, 7, pplan, style)\n ws.write(row_num, 9, c.contract_type.price, style)\n ws.write(row_num, 10, contribution, style)\n ws.write(row_num, 11, e_pay, style)\n ws.write(row_num, 12, cr.amount, style)\n ws.write(row_num, 13, c.client.manager.initials(), style)\n if cr.contract.discount:\n ws.write(row_num, 3, c.discount.value, style)\n else:\n ws.write(row_num, 3, '', style)\n day_summ += cr.amount\n elif cr.goods:\n ptt_line = 0\n if cr.goods.goods_type.name == 'PTT':\n row_num += 1\n ptts = Client_PTT.objects.filter(\n date__month=month, date__year=year, date__day=day,\n employee=cr.employee, goods=cr.goods, client=cr.client\n ).order_by('date')\n if ptts.count() > 1:\n ptt = ptts[ptt_line]\n ptt_line += 1\n else:\n ptt_line = 0\n ptt = ptts[0]\n\n ws.write(row_num, 1, ptt.number(), style)\n ws.write(row_num, 2, cr.goods.name, style)\n ws.write(row_num, 3, '', style)\n ws.write(row_num, 4, first_text[ptt.is_first()], style)\n ws.write(row_num, 5, ptt.number(), style)\n ws.write(row_num, 6, ptt.client.initialsC(), style)\n ws.write(row_num, 7, '', style)\n ws.write(row_num, 9, cr.goods.priceondate(d), style)\n ws.write(row_num, 10, cr.amount, style)\n ws.write(row_num, 11, '', style)\n ws.write(row_num, 12, cr.amount, style)\n ws.write(row_num, 13, ptt.client.manager.initials(), style)\n day_summ += cr.amount\n else:\n continue\n else:\n continue\n ws.write(row_num, 0, d, styled)\n ws.write(row_num, 8, pay_type[cr.payment_type], style)\n ws.write(row_num, 14, '', style)\n ws.write(row_num, 15, cr.user.initials(), style)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef ptt(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"ptt\")\n\n head = u'Персональные тренировки за период c: '\\\n + s_date.strftime(\"%d.%m.%Y\")\n head += u' по: ' + e_date.strftime(\"%d.%m.%Y\")\n ws.write_merge(0, 0, 0, 10, head, styleh)\n\n row_num = 1\n columns = []\n columns.append((u'Номер карты ', 4000))\n columns.append((u'Дата продажи', 6000))\n columns.append((u'Вид блока', 6000))\n columns.append((u'Стоимость, руб.', 5000))\n columns.append((u'Вид оплаты', 4000))\n columns.append((u'Впервые / Повторно', 5000))\n columns.append((u'ФИО ', 8000))\n columns.append((u'Тренер ', 8000))\n columns.append((u'Менеджер ', 8000))\n columns.append((u'Продавец', 8000))\n columns.append((u'Карта выдана ', 4000, 0))\n\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n lst = Client_PTT.objects.filter(\n date__range=(s_date, e_date)).order_by('date')\n\n ptt_first = (u'Повторно', u'Впервые')\n\n for ptt in lst:\n row_num += 1\n fullname = ptt.client.initialsC()\n trainer = ptt.employee.initials()\n manager = ptt.client.manager.initials()\n seller = ptt.user.initials()\n if not ptt.is_card:\n url = reverse('ptt_card', args=(ptt.pk, ))\n url = request.build_absolute_uri(url)\n link = u'HYPERLINK(\"' + url + u'\"; \"Не выдана\")'\n is_card = xlwt.Formula(link)\n st = style_red\n else:\n is_card = u'Выдана'\n st = style\n ws.write(row_num, 0, str(ptt.number()), style)\n ws.write(row_num, 1, ptt.date.strftime(\"%d.%m.%Y %H:%M\"), styledt)\n ws.write(row_num, 2, ptt.goods.name, style)\n ws.write(row_num, 3, ptt.goods.priceondate(ptt.date), stylef)\n ws.write(row_num, 4, pay_type[ptt.payment_type], style)\n ws.write(row_num, 5, ptt_first[ptt.is_first()], style)\n ws.write(row_num, 6, fullname, style)\n ws.write(row_num, 7, trainer, style)\n ws.write(row_num, 8, manager, style)\n ws.write(row_num, 9, seller, style)\n ws.write(row_num, 10, is_card, st)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef e_visits(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n ldate = Shift.objects.all().aggregate(Max('date'))\n shifts = Shift.objects.filter(date=ldate['date__max'])\n ttable = Timetable.objects.filter(\n date__range=(s_date, e_date), shift__in=shifts)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"e_visits\")\n\n head = u'Посещения клуба за период c: ' + s_date.strftime(\"%d.%m.%Y\")\n head += u' по: ' + e_date.strftime(\"%d.%m.%Y\")\n\n row_num = 1\n columns = []\n columns.append((u'дата ', 4000))\n columns.append((u'день недели ', 4000))\n columns.append((u'ФИО ', 8000))\n columns.append((u'Время прихода ', 4000))\n columns.append((u'Время ухода ', 4000))\n\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n lst = eVisits.objects.filter(\n date_start__gte=s_date, date_start__lte=e_date).order_by('date_start')\n for v in lst:\n row_num += 1\n fullname = v.employee.initials()\n try:\n Timetable.objects.get(\n date=v.date_start.date(), employee=v.employee)\n nstyle = style_red\n except Timetable.DoesNotExist:\n nstyle = style\n ws.write(row_num, 0, v.date_start.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 1, week_days_ru(v.date_start.weekday()), nstyle)\n ws.write(row_num, 2, fullname, nstyle)\n ws.write(row_num, 3, v.date_start.strftime(\"%H:%M\"), stylet)\n if v.date_end:\n data = v.date_end.strftime(\"%H:%M\")\n else:\n data = ''\n ws.write(row_num, 4, data, stylet)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef reception_visits(request, ):\n Y = datetime.today().year\n m = datetime.today().strftime(\"%m\")\n d = datetime.today().strftime(\"%d\")\n context_dict = dict(request=request, Y=Y, m=m, d=d)\n return render_to_response('reception_visits.html', context_dict)\n\n\n@login_required(login_url='/login')\ndef organizer(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"visits\")\n\n columns = []\n columns.append((u'Номер', 2000, ))\n columns.append((u'ФИО ', 8000, ))\n columns.append((u'Телефон', 4000, ))\n columns.append((u'Гость/звонок', 6000, ))\n columns.append((u'Дата занесения в органайзер', 8000, ))\n columns.append((u'Абонемент куплен да/нет', 8000, ))\n columns.append((u'Коментарий', 4000, ))\n columns.append((u'Менеджер', 8000, ))\n\n head = u'Выгрузка органайзера в exel'\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n row_num = 1\n guests = OGuest.objects.filter(\n date__range=(s_date, e_date)).order_by('date')\n for i, g in enumerate(guests):\n row_num += 1\n ws.write(row_num, 0, i, style)\n ws.write(row_num, 1, g.fullname(), style)\n ws.write(row_num, 2, g.phone, style)\n ws.write(row_num, 3, g.gtype_str(), style)\n ws.write(row_num, 4, g.date.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 5, g.is_client_str(), style)\n ws.write(row_num, 6, g.note, style)\n ws.write(row_num, 7, g.manager.initialsC(), style)\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef organizer_full(request):\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"visits\")\n\n columns = []\n columns.append((u'Номер п/п', 2000, ))\n columns.append((u'ФИО ', 8000, ))\n columns.append((u'Телефон', 4000, ))\n columns.append((u'Гость/звонок', 6000, ))\n columns.append((u'Дата занесения в органайзер', 8000, ))\n columns.append((u'Абонемент куплен да/нет', 8000, ))\n columns.append((u'Коментарий', 4000, ))\n columns.append((u'Менеджер', 8000, ))\n\n head = u'Выгрузка органайзера в exel'\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n row_num = 1\n guests = OGuest.objects.all().order_by('date')\n for i, g in enumerate(guests):\n row_num += 1\n ws.write(row_num, 0, i, style)\n ws.write(row_num, 1, g.fullname(), style)\n ws.write(row_num, 2, g.phone, style)\n ws.write(row_num, 3, g.gtype_str(), style)\n ws.write(row_num, 4, g.date.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 5, g.is_client_str(), style)\n ws.write(row_num, 6, g.note, style)\n ws.write(row_num, 7, g.manager.initialsC(), style)\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef visits(request, syear, smonth, sday, eyear, emonth, eday):\n syear = int(syear)\n smonth = int(smonth)\n sday = int(sday)\n eyear = int(eyear)\n emonth = int(emonth)\n eday = int(eday)\n\n s_date = datetime.combine(date(syear, smonth, sday), time.min)\n e_date = datetime.combine(date(eyear, emonth, eday), time.max)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"visits\")\n\n columns = []\n columns.append((u'дата ', 4000, ))\n columns.append((u'ФИО ', 8000, ))\n columns.append((u'Время прихода ', 4000, ))\n columns.append((u'Время ухода ', 4000, ))\n columns.append((u'Шкафчик # ', 3000, ))\n\n head = u'Посещения клуба за период c: ' + s_date.strftime(\"%d.%m.%Y\")\n head += u' по: ' + e_date.strftime(\"%d.%m.%Y\")\n ws.write_merge(0, 0, 0, len(columns)-1, head, styleh)\n\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n lst = Visits.objects.filter(date_start__gte=s_date,\n date_end__lte=e_date).order_by('date_start')\n for v in lst:\n row_num += 1\n fullname = v.contract.client.initialsC()\n ws.write(row_num, 0, v.date_start.strftime(\"%d.%m.%Y\"), styled)\n ws.write(row_num, 1, fullname, style)\n ws.write(row_num, 2, v.date_start.strftime(\"%H:%M\"), stylet)\n ws.write(row_num, 3, v.date_end.strftime(\"%H:%M\"), stylet)\n ws.write(row_num, 4, v.locker, style)\n\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef sells(request, year, month, other):\n month = int(month)\n year = int(year)\n other = int(other)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"sells\")\n\n ch_dep = CreditsHistory.objects.filter(\n date__month=month, date__year=year,).values('department')\n need_dp = DepartmentsNames.objects.filter(\n department__in=ch_dep).values_list('pk', flat=True)\n columns = []\n columns.append((u'Дата ', 4000, 0))\n for dn in DepartmentsNames.list():\n if dn not in need_dp:\n continue\n if DepartmentsNames.list()[dn]:\n columns.append((DepartmentsNames.list()[dn], 4000, dn))\n else:\n columns.append((u'Отдел ' + str(dn), 4000, dn))\n\n columns.append((u'Сумма ', 4000, 9999))\n\n row_num = 0\n head = month_name_ru(month) + ' ' + str(year)\n col_join = len(columns) - 4\n ws.row(row_num).height_mismatch = True\n ws.row(row_num).height = 15*20\n if col_join < 1:\n col_join = 1\n ws.write_merge(row_num, 0, 0, col_join, head, styleh)\n ws.write_merge(\n row_num, 0, col_join + 1, col_join + 3, report_top_prefix, styleph)\n row_num = 1\n last_col = len(columns) - 1\n for col_num in xrange(len(columns)):\n if col_num == 0:\n ws.write_merge(row_num, 2, 0, 0, columns[col_num][0], styleth)\n elif col_num == last_col:\n ws.write_merge(\n row_num, 2, last_col, last_col, columns[col_num][0], styleth)\n else:\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n ws.write(\n row_num + 1, col_num,\n u'Отдел ' + str(columns[col_num][2]), styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n row_num = 2\n total_summ = 0\n mdays = monthrange(year, month)[1]\n for d in xrange(mdays):\n row_num += 1\n day = d + 1\n day_summ = 0\n for col_num in xrange(len(columns)):\n if col_num == 0:\n data = date(year, month, day).strftime(\"%d.%m.%Y\")\n st = stylethd\n elif columns[col_num][2] == 9999:\n st = styleth\n sl = col_idx2str(1)\n el = col_idx2str(col_num-1)\n formula = 'SUM(' + sl + str(row_num + 1) + ':'\\\n + el + str(row_num + 1) + ')'\n data = xlwt.Formula(formula)\n else:\n st = style\n department = columns[col_num][2] # cash section\n if other:\n dep_summ = CreditsHistory.objects.filter(\n date__month=month, date__year=year, date__day=day,\n department=department, is_return=0,\n ).aggregate(Sum('amount'))\n else:\n dep_summ = CreditsHistory.objects.filter(\n date__month=month, date__year=year, date__day=day,\n department=department, is_return=0,\n ).exclude(\n payment_type=2).aggregate(Sum('amount'))\n data = dep_summ['amount__sum']\n if data:\n day_summ += data\n ws.write(row_num, col_num, data, st)\n\n row_num += 1\n ws.write(row_num, 0, 'Итого:', styleth)\n for col_num in xrange(1, len(columns)):\n l = col_idx2str(col_num)\n formula = 'SUM(' + l + '4:' + l + str(mdays+3) + ')'\n ws.write(row_num, col_num, xlwt.Formula(formula), styleth)\n wb.save(response)\n return response\n\n\n@login_required(login_url='/login')\ndef menu(request, ):\n Y = datetime.today().year\n m = datetime.today().strftime(\"%m\")\n d = datetime.today().strftime(\"%d\")\n\n context_dict = dict(request=request, Y=Y, m=m, d=d,)\n return render_to_response('reports_menu.html', context_dict)\n\n\n@login_required(login_url='/login')\ndef departments_names(request, ):\n if request.method == 'POST':\n i = 0\n form_val = dict()\n for n in request.POST.getlist('name'):\n i += 1\n form_val['department'] = i\n form_val['name'] = n\n try:\n inst = DepartmentsNames.objects.get(pk=i)\n form = FormDepartmentsNames(form_val, instance=inst)\n except DepartmentsNames.DoesNotExist:\n form = FormDepartmentsNames(form_val)\n if form.is_valid():\n form.save()\n else:\n return HttpResponse(form.errors, mimetype=\"text/plain\")\n return HttpResponseRedirect(reverse('reports_menu'))\n lst = DepartmentsNames.list()\n context_dict = dict(request=request, lst=lst)\n context_dict.update(csrf(request))\n return render_to_response('departments_names.html', context_dict)\n\n\n@login_required(login_url='/login')\ndef reception_day(request, year, month, day,):\n title = u'Отчет рецепциониста'\n month = int(month)\n year = int(year)\n day = int(day)\n td = date(year, month, day)\n b_date = datetime.combine(td, time.min)\n e_date = datetime.combine(td, time.max)\n lst = CreditsHistory.objects.filter(\n date__range=(b_date, e_date)).exclude(payment_type=2).values('check')\n\n cclst = CashCheck.objects.filter(pk__in=lst).order_by('date')\n\n total = CreditsHistory.objects.filter(\n date__range=(b_date, e_date), is_return=0).exclude(\n payment_type=2).aggregate(Sum('amount'))['amount__sum']\n dtotal = []\n for d in settings.DEPARTMENTS:\n dsumm = 0\n cash = CreditsHistory.objects.filter(\n department=d, payment_type=0, date__range=(b_date, e_date),\n is_return=0).aggregate(Sum('amount'))['amount__sum']\n if cash:\n dsumm += cash\n\n cashless = CreditsHistory.objects.filter(\n department=d, payment_type=1, date__range=(b_date, e_date),\n is_return=0, ).aggregate(Sum('amount'))['amount__sum']\n if cashless:\n dsumm += cashless\n\n dtotal.append((d, dsumm, cash, cashless))\n\n Y = td.year\n m = td.strftime(\"%m\")\n d = td.strftime(\"%d\")\n context_dict = dict(\n request=request, lst=cclst, title=title, total=total,\n dtotal=dtotal, cashhost=settings.CASHIER_HOST, Y=Y, m=m, d=d)\n response = render_to_response('reception_day.html', context_dict)\n\n return response\n\n\n@login_required(login_url='/login')\ndef reception(request, year, month, day, other, ):\n day = int(day)\n month = int(month)\n year = int(year)\n other = int(other)\n td = date(year, month, day)\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=mymodel.xls'\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(\"receprion\")\n\n head = u'Отчет рецепциониста за: %s' % td.strftime(\"%d.%m.%Y\")\n columns = []\n columns.append((u'Время', 6000))\n columns.append((u'Клиент', 8000))\n columns.append((u'Товар', 6000))\n columns.append((u'Количество', 6000))\n columns.append((u'Цена', 6000))\n columns.append((u'Сумма', 6000))\n columns.append((u'Вид оплаты', 6000))\n\n row_num = 0\n ws.write_merge(row_num, 0, 0, len(columns)-1, head, styleh)\n\n row_num = 1\n for col_num in xrange(len(columns)):\n ws.write(row_num, col_num, columns[col_num][0], styleth)\n # set column width\n ws.col(col_num).width = columns[col_num][1]\n\n b_date = datetime.combine(td, time.min)\n e_date = datetime.combine(td, time.max)\n if other:\n payments = CreditsHistory.objects.filter(\n date__range=(b_date, e_date)).order_by('date')\n else:\n payments = CreditsHistory.objects.filter(\n date__range=(b_date, e_date)).exclude(\n payment_type=2).order_by('date')\n for ch in payments:\n row_num += 1\n ws.write(row_num, 0, ch.date.strftime(\"%H:%M\"), stylet)\n ws.write(row_num, 1, ch.username(), style)\n ws.write(row_num, 2, ch.goodsname(), style)\n ws.write(row_num, 3, ch.count, style)\n\n ws.write(row_num, 4, ch.goodsprice(), stylef)\n ws.write(row_num, 5, ch.amount, style)\n\n if ch.payment_type == 1:\n str_paytype = u'безнал'\n elif ch.payment_type == 2:\n str_paytype = u'иное'\n else:\n str_paytype = u'наличными'\n\n ws.write(row_num, 6, str_paytype, style)\n\n if other:\n total = CreditsHistory.objects.filter(\n date__range=(b_date, e_date)).aggregate(\n Sum('amount'))['amount__sum']\n else:\n total = CreditsHistory.objects.filter(\n date__range=(b_date, e_date)).exclude(\n payment_type=2).aggregate(Sum('amount'))['amount__sum']\n\n row_num += 1\n ws.write(row_num, 0, 'Итого:', styleh)\n ws.write(row_num, 1, total, stylethf)\n # add the line before details\n row_num += 1\n\n dsumm = 0\n for d in settings.DEPARTMENTS:\n # if the previous department has sells, miss one line\n if dsumm > 0:\n row_num += 1\n dsumm = 0\n cash = CreditsHistory.objects.filter(\n department=d, payment_type=0, date__range=(b_date, e_date)\n ).aggregate(Sum('amount'))['amount__sum']\n if cash:\n dsumm += cash\n\n cashless = CreditsHistory.objects.filter(\n department=d, payment_type=1, date__range=(b_date, e_date)\n ).aggregate(Sum('amount'))['amount__sum']\n if cashless:\n dsumm += cashless\n\n if other:\n other_summ = CreditsHistory.objects.filter(\n department=d, payment_type=2, date__range=(b_date, e_date)\n ).aggregate(Sum('amount'))['amount__sum']\n if other_summ:\n dsumm += other_summ\n else:\n other_summ = 0\n\n if dsumm > 0:\n row_num += 1\n d_str = 'отдел №%s' % d\n ws.write(row_num, 0, d_str, styleh)\n ws.write(row_num, 1, dsumm, stylethf)\n if cash > 0:\n row_num += 1\n ws.write(row_num, 0, 'наличными:', styleh)\n ws.write(row_num, 1, cash, stylethf)\n if cashless > 0:\n row_num += 1\n ws.write(row_num, 0, 'безнал:', styleh)\n ws.write(row_num, 1, cashless, stylethf)\n if other_summ > 0:\n row_num += 1\n ws.write(row_num, 0, 'иное:', styleh)\n ws.write(row_num, 1, other_summ, stylethf)\n wb.save(response)\n return response\n\n\ndef month_name_ru(idx):\n month_name = (\n u'', u'Январь', u'Февраль', u''\n u'Март', u'Апрель', u'Май',\n u'Июнь', u'Июль', u'Август',\n u'Сентябрь', u'Октябрь', u'Ноябрь',\n u'Декабрь')\n return month_name[idx]\n\n\ndef week_days_ru(idx):\n week_days = (u'Понедельник', u'Вторник', u'Среда', u'Четверг',\n u'Пятница', u'Суббота', u'Воскресенье')\n return week_days[idx]\n\n\ndef col_idx2str(idx):\n idx += 1\n col = ''\n while (idx > 0):\n mod = (idx - 1) % 26\n col = uppercase[mod] + col\n idx = (idx - mod) / 26\n return col\n","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":44355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"297647564","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nfrom wallet import Wallet\nfrom blockchain import Blockchain\n\n\napp = Flask(__name__)\n\n\nCORS(app)\n\n\n\"\"\"\nCreate wallet keys method\n\"\"\"\n@app.route('/create-wallet', methods=['POST'])\ndef create_wallet_keys():\n # initialize wallet object\n wallet = Wallet()\n # extract data from request as json\n request_data = request.get_json()\n # get user id from request sent\n user_id = request_data['userId']\n # check if error in creating keys for user otherwise continue\n if not wallet.create_keys(user_id):\n response = {\n 'message': 'User Wallet already exists! Try loading wallet'\n }\n return jsonify(response), 400\n\n # check if keys saved return appropriate response\n if wallet.save_keys(user_id):\n # return success save wallet keys response\n response = {\n 'message': 'Wallet Created Successfully',\n 'funds': 0\n }\n return jsonify(response), 201\n else:\n # return error save wallet keys response\n response = {\n 'message': 'creating/saving keys failed! Please Try again...'\n }\n return jsonify(response), 500\n\n\n\"\"\"\nLoad wallet keys method\n\"\"\"\n@app.route('/load-wallet', methods=['POST'])\ndef load_wallet_keys():\n # initialize wallet object\n wallet = Wallet()\n # getting request data from request as json\n request_data = request.get_json()\n # get user id sent in request\n user_id = request_data['userId']\n\n # check if loading wallet is successful\n if wallet.load_keys(user_id):\n # create/load your blockchain instance\n blockchain = Blockchain(wallet.public_key, user_id)\n\n # return response if loaded your chain data\n response = {\n 'message': 'Successfully Loaded Wallet',\n 'public_key': wallet.public_key,\n 'private_key': wallet.private_key,\n 'funds': blockchain.get_user_balance(wallet.public_key)\n }\n return jsonify(response), 200\n else:\n # loading keys failed return error response\n response = {\n 'message': 'loading keys failed! Create a Wallet or Please Try again...'\n }\n return jsonify(response), 400\n\n\n\"\"\"\nGet users coin balance\n\"\"\"\n@app.route('/get-balance', methods=['POST'])\ndef get_balance():\n # define required fields to be passed in request\n required_fields = ['userId', 'public_key']\n\n # getting request data from request as json\n request_data = request.get_json()\n\n if not request_data:\n response = {\n 'message': 'No User Data found!'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # get user id sent in request\n user_id = request_data['userId']\n\n public_key = request_data['public_key']\n\n # create blockchain instance\n blockchain = Blockchain(public_key, user_id)\n # get your balance\n balance = blockchain.get_user_balance(public_key)\n # check balance is not None\n if balance != None:\n # return success response\n response = {\n 'message': 'Successfully fetched balance',\n 'funds': balance\n }\n return jsonify(response), 200\n else:\n # return fail response\n response = {\n 'message': 'Loading balance failed!',\n 'wallet-setup': public_key != None\n }\n return jsonify(response), 500\n\n\n\"\"\"\n GET route for getting open transactions in blockchain\n\"\"\"\n@app.route('/get-open-transactions', methods=['POST'])\ndef get_open_transactions():\n # define required fields to be passed in request\n required_fields = ['userId', 'public_key']\n\n # getting request data from request as json\n request_data = request.get_json()\n\n if not request_data:\n response = {\n 'message': 'No User Data found!'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # get user id sent in request\n user_id = request_data['userId']\n public_key = request_data['public_key']\n\n # create blockchain instance\n blockchain = Blockchain(public_key, user_id)\n # get open transactions from blockchain instance\n transactions = blockchain.get_open_transactions()\n # convert transactions to dictionaries so can be sent as JSON\n json_transactions = [tx.__dict__ for tx in transactions]\n return jsonify(json_transactions), 200\n\n\n\"\"\"\nGET route returns copy of blockchain to user\n\"\"\"\n@app.route('/get-blockchain', methods=['POST'])\ndef get_blockchain():\n # define required fields to be passed in request\n required_fields = ['userId', 'public_key']\n\n # getting request data from request as json\n request_data = request.get_json()\n\n if not request_data:\n response = {\n 'message': 'No User Data found!'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # get user id sent in request\n user_id = request_data['userId']\n\n public_key = request_data['public_key']\n\n # create blockchain instance\n blockchain = Blockchain(public_key, user_id)\n\n # get copy of your blockchain data\n chain_copy = blockchain.get_blockchain()\n # convert to dictionary so can be sent as part of response\n json_chain = [block.__dict__.copy() for block in chain_copy]\n\n # loop for transactions in chain and convert transactions to dictionary format\n for json_block in json_chain:\n json_block['transactions'] = [tx.__dict__.copy()\n for tx in json_block['transactions']]\n return jsonify(json_chain), 200\n\n\n\"\"\"\n Add new transaction route\n\"\"\"\n@app.route('/add-transaction', methods=['POST'])\ndef add_transaction():\n # create wallet instance\n wallet = Wallet()\n\n # define required fields to be passed in request\n required_fields = ['recipient', 'amount',\n 'userId', 'public_key', 'private_key']\n\n # get request data as json\n request_data = request.get_json()\n\n # if no request data return error response\n if not request_data:\n response = {\n 'message': 'No transaction data found'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # extract request data\n user_id = request_data['userId']\n public_key = request_data['public_key']\n private_key = request_data['private_key']\n recipient = request_data['recipient']\n amount = request_data['amount']\n\n # create blockchain instance for users chain data\n blockchain = Blockchain(public_key, user_id)\n # create a signature for new transaction to be added\n signature = wallet.sign_transaction(\n public_key, recipient, amount, private_key)\n # check for success of added transaction\n added_tx = blockchain.add_transaction(\n public_key, recipient, signature, amount)\n # check success of adding transaction\n if added_tx:\n # return success response\n response = {\n 'message': 'Successfully added a new transaction',\n 'funds': blockchain.get_user_balance(public_key)\n }\n return jsonify(response), 201\n else:\n # return failed transaction response\n response = {\n 'message': 'Adding a new transaction failed!'\n }\n return jsonify(response), 500\n\n\n\"\"\"\nPOST route for user to try and mine a block on blockchain\n\"\"\"\n@app.route('/mine-block', methods=['POST'])\ndef mine_block():\n # define required fields to be passed in request\n required_fields = ['userId', 'public_key']\n\n # getting request data from request as json\n request_data = request.get_json()\n\n if not request_data:\n response = {\n 'message': 'No User Data found!'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # get user id and public key sent in request\n user_id = request_data['userId']\n public_key = request_data['public_key']\n\n # create users blockchain instance\n blockchain = Blockchain(public_key, user_id)\n # check user doesn't need to resolve conflicts before continuing\n if blockchain.resolve_conflicts:\n # return error response if they need to resolve conflicts\n response = {\n 'message': 'Resolve conflicts in Blockchain, Block not added!'\n }\n return jsonify(response), 409\n\n # mine a new block\n block = blockchain.mine_block()\n # if mining succeded\n if block != None:\n # convert block object to dictionary\n block_dict = block.__dict__.copy()\n # convert block objects transaction objects to dictionaries using list comprehension\n block_dict['transactions'] = [\n tx.__dict__ for tx in block_dict['transactions']]\n # return success response\n response = {\n 'message': 'Successfully mined a new block!',\n 'block': block_dict,\n 'funds': blockchain.get_user_balance(public_key)\n }\n return jsonify(response), 201\n else:\n # return mine block failure response\n response = {\n 'message': 'Failed to add a block!',\n 'wallet-setup': public_key != None\n }\n return jsonify(response), 500\n\n\n\"\"\"\nRoute to handle updating users copy of blockchain if they need to resolve conflicts\n\"\"\"\n@app.route('/resolve-conflicts', methods=['POST'])\ndef resolve_conflicts():\n # define required fields to be passed in request\n required_fields = ['userId', 'public_key']\n\n # getting request data from request as json\n request_data = request.get_json()\n\n if not request_data:\n response = {\n 'message': 'No User Data found!'\n }\n return jsonify(response), 400\n\n # if all required fields not part of request return error response\n if not all(field in required_fields for field in request_data):\n response = {\n 'message': 'Required fields are missing, try again!'\n }\n return jsonify(response), 400\n\n # get user id sent in request\n user_id = request_data['userId']\n\n public_key = request_data['public_key']\n\n # create users blockchain instance\n blockchain = Blockchain(public_key, user_id)\n\n # check wheteher users blockchain was replaced with updated chain\n replaced = blockchain.resolve_chain_conflicts()\n if replaced:\n # return response if chain replaced\n response = {\n 'message': 'Your Chain was replaced with most up to date version of chain!'\n }\n else:\n # return response if users chain kept as winning chain\n response = {\n 'message': 'Loacal Chain remains!'\n }\n return jsonify(response), 200\n\n\n\"\"\"\nReturn the public key of a user upon request\n\"\"\"\n@app.route('/get-public-key/<user_id>', methods=['GET'])\ndef get_user_public_key(user_id):\n # check for user id passed\n if user_id == None:\n # return error response if no data passed\n response = {\n 'message': 'No user data passed'\n }\n return jsonify(response), 400\n\n # create wallet instance\n wallet = Wallet()\n # load wallet data for user\n if wallet.load_keys(user_id):\n # return success response with users public key\n response = {\n 'message': 'fetched user public key successfully',\n 'public_key': wallet.public_key\n }\n return jsonify(response), 200\n else:\n # return error response, loading wallet failed\n response = {\n 'message': 'Error loading user wallet! Please try again.'\n }\n return jsonify(response), 500\n\n\n# run server\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, threaded=True)\n","sub_path":"Server/Flask/http_node.py","file_name":"http_node.py","file_ext":"py","file_size_in_byte":12915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"499364931","text":"class NeuralNetwork(object):\n\n \"\"\"\n 神经网络模型\n \"\"\"\n\n # 构建仅含有层容器的空模型\n def __init__(self):\n\n self.layers = [] # 层的容器:组织层结构的列表,使添加的层变得有序\n\n # 将层添加进模型中,并连接\n def add(self, layer):\n \n \"\"\"\n :param layer: (Layer)添加的层\n :return: None\n \"\"\"\n \n # add\n self.layers.append(layer)\n \n # link\n if len(self.layers) > 1:\n self.layers[-1].prelayer = self.layers[-2]\n self.layers[-2].nextlayer = self.layers[-1]\n\n # 训练\n def train(self, x, y, epochs=3000):\n\n \"\"\"\n :param x: (ndarray)数据集的特征\n :param y: (ndarray)数据集的标签\n :param epochs: (int)迭代次数\n :return: None\n \"\"\"\n \n # input processing\n x = x.T\n y = y.T\n \n # init model\n print('initialization epoch:')\n for index, layer in enumerate(self.layers):\n \n # 第一层\n if index == 0:\n layer.feedin = x\n layer.init(layer.feedin.shape[0], x.shape[1])\n layer.feedforward()\n # 中间层\n elif 0 < index < len(self.layers)-1:\n layer.init(layer.prelayer.units, x.shape[1])\n layer.feedforward()\n # Cost层\n else:\n layer.backin = y\n layer.feedforward()\n \n # training\n epoch = 0\n while epoch < epochs:\n \n print('epochs', epoch+1, '/', epochs)\n epoch += 1\n \n # 反向传播\n for layer in self.layers[::-1]:\n \n layer.backpropagation()\n \n # 正向传播\n for layer in self.layers:\n\n layer.feedforward()\n\n # 测试\n def test(self, x, y):\n\n \"\"\"\n :param x: (ndarray)测试集特征\n :param y: (ndarray)测试集标签\n :return: None\n \"\"\"\n\n for index, layer in enumerate(self.layers):\n\n if index == 0:\n layer.feedin = x\n layer.feedforward()\n elif 0 < index < len(self.layers)-1:\n layer.feedforward()\n else:\n layer.backin = y\n layer.feedforward()\n\n # 预测\n def predict(self, x):\n\n \"\"\"\n :param x: (ndarray)新样本\n :return: None\n \"\"\"\n\n for index, layer in self.layers[:-1]:\n\n if index == 0:\n layer.feedin = x\n layer.feedforward()\n else:\n layer.feedforward()\n\n print(self.layers[-2].feedout)\n","sub_path":"MDLF/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"573132268","text":"for x in range(12, 12 + 8 * 6, 8):\n for y in range(12, 12 + 8 * 7, 8):\n hero.buildXY(\"fire-trap\", x, y)\n hero.moveXY(hero.pos.x + 8, hero.pos.y)\n\nmine = hero.findNearest(hero.findHazards())\n\nwhile True:\n enemy = hero.findNearestEnemy()\n if enemy and hero.distanceTo(enemy) <= 20:\n hero.moveXY(mine.pos.x, mine.pos.y)\n break\n","sub_path":"8_Cloudrip_Mountain/434-Grid_Minefield/grid_minefield.py","file_name":"grid_minefield.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"403016874","text":"import os, sys, random\n\nN, J = 32, 500\nbases = range(2, 11)\npowers = {}\nfor b in bases:\n a = [1]\n for i in range(1, N):\n a.append(a[-1] * b)\n powers[b] = a\n\ndef random_set():\n res = []\n for i in range(1, N - 1):\n if random.random() < 0.5:\n res.append(i)\n return res\n\ndef gen_numbers():\n s = random_set()\n ns = []\n for b, ps in powers.iteritems():\n n = ps[0] + ps[-1]\n n += sum(ps[i] for i in s)\n ns.append(n)\n return ns, s\n\nprimes = []\nP = int(sum(powers[10]) ** 0.5) + 1\nP = int(3.5e7)\nsieve = [True] * (P + 1)\nsieve[0] = sieve[1] = False\nfor i in range(2, P + 1):\n if sieve[i]:\n primes.append(i)\n j = i + i\n while j < P + 1:\n sieve[j] = False\n j += i\n\ndef prime_test(n):\n u = int(n ** 0.5)\n for i in xrange(len(primes)):\n if primes[i] > u: break\n if n % primes[i] == 0: return primes[i]\n return 1\n\nprint(\"Case #1:\")\n\nuniq = set()\nres = []\niters = 0\nwhile len(res) < J:\n iters += 1\n # if iters % 1000 == 0: print(iters)\n ns, s = gen_numbers()\n factors = []\n for n in ns:\n f = prime_test(n)\n if f == 1: break\n factors.append(f)\n if len(factors) == 9 and ns[0] not in uniq:\n uniq.add(ns[0])\n res.append((ns[-1], factors))\n print(\"{} {}\".format(ns[-1], ' '.join(map(str, factors))))\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_fmardini_jamcoin.py","file_name":"16_0_3_fmardini_jamcoin.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"363889084","text":"from nbt.nbt import NBTFile, TAG_Long, TAG_Int, TAG_String, TAG_List, TAG_Compound\nimport pprint\nimport sys\nimport glob\n\n\n\nfiles = glob.glob(sys.argv[1])\n\n\n# print(files)\n\n\n\n\n'''\nposition = [ bla.value for bla in nbtdata[\"Pos\"] ]\ndimension = nbtdata[\"Dimension\"].value\nUUIDleast = nbtdata[\"UUIDLeast\"].value\nUUIDmost = nbtdata[\"UUIDMost\"].value\n'''\n\ndef unpack_nbt(tag):\n \"\"\"\n Unpack an NBT tag into a native Python data structure.\n \"\"\"\n \n if isinstance(tag, TAG_List):\n return [unpack_nbt(i) for i in tag.tags]\n elif isinstance(tag, TAG_Compound):\n return dict((i.name, unpack_nbt(i)) for i in tag.tags)\n else:\n return tag.value\n\n\nfor each in files:\n\n nbtData = NBTFile(each)\n\n pp = pprint.PrettyPrinter(depth=1, indent=4, width=10)\n\n\n\n\n Obj = unpack_nbt(nbtData)\n\n pp.pprint(Obj)\n #print([a[\"Players\"] for a in Obj[\"data\"][\"Teams\"] if a[\"Name\"] == \"mute\"])\n\n\n\n\n","sub_path":"utils/nbtcat.py","file_name":"nbtcat.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"233218951","text":"import os\nos.environ['DJANGO_SETTINGS_MODULE']='settings'\nimport numpy as np\nimport os\nos.environ['DJANGO_SETTINGS_MODULE']='settings'\nimport webapp2 as webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nimport numpy as np\nimport cgi\nimport cgitb\ncgitb.enable()\n\n# The mass of the sediment at equilibrium with the water column\n\ndef msed(dsed,a,pb):\n try:\n dsed = float(dsed)\n a = float(a)\n pb = float(pb)\n except IndexError:\n raise IndexError\\\n ('The sediment depth, area of the rice paddy, and/or the bulk'\\\n ' density of the sediment must be supplied the command line.')\n except ValueError:\n raise ValueError\\\n ('The sediment depth must be a real number, not \"%m\"' % dsed)\n except ValueError:\n raise ValueError\\\n ('The area of the rice paddy must be a real number, not \"%ha\"' % a)\n except ValueError:\n raise ValueError\\\n ('The bulk density of the sediment must be a real number, not \"%kg/m3\".' %pb)\n if dsed < 0:\n raise ValueError\\\n ('dsed=%g is a non-physical value.' % dsed)\n if a < 0:\n raise ValueError\\\n ('a=%g is a non-physical value.' % a)\n if pb < 0:\n raise ValueError\\\n ('pb=%g is a non-physical value.' %pb)\n return dsed * a * pb\n\n\nclass MsedService(webapp.RequestHandler):\n \n def get(self):\n data = simplejson.loads(self.request.body)\n data = json_utils.convert(data)\n msed_output = msed(data['dsed'],data['a'],data['pb'])\n msed_json = simplejson.dumps(msed_output)\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(msed_json)\n\n\n# The volume of the water column plus pore water\n\ndef vw(dw,a,dsed,osed):\n try:\n dw = float(dw)\n a = float(a)\n dsed = float(dsed)\n osed = float(osed)\n except IndexError:\n raise IndexError\\\n ('The water column depth, area of the rice paddy, sediment depth, and/or'\\\n ' porosity of sediment must be supplied the command line.')\n except ValueError:\n raise ValueError\\\n ('The water column depth must be a real number, not \"%m\"' % dw)\n except ValueError:\n raise ValueError\\\n ('The area of the rice paddy must be a real number, not \"%ha\"' % a)\n except ValueError:\n raise ValueError\\\n ('The sediment depth must be a real number, not \"%cm\"' % dsed)\n except ValueError:\n raise ValueError\\\n ('The porosity of sediment must be a real number\"' % osed)\n if dw < 0:\n raise ValueError\\\n ('dw=%g is a non-physical value.' % dw)\n if a < 0:\n raise ValueError\\\n ('a=%g is a non-physical value.' % a)\n if dsed < 0:\n raise ValueError\\\n ('dsed=%g is a non-physical value.' % dsed)\n if osed < 0:\n raise ValueError\\\n ('osed=%g is a non-physical value.' % osed)\n return(dw * a) + (dsed * osed * a)\n\n\n\n# The pesticide mass per unit area\n\ndef mai1(mai,a):\n mai = float(mai)\n a = float(a)*1e-4\n return mai/a\n# if a <= 0:\n# print('The area of the rice paddy must be greater than 0 m2')\n\n\n\n\n# Water Concentration\n\ndef cw(mai1,dw,dsed,osed,pb,kd):\n try:\n mai1 = float(mai1)\n dw = float(dw)\n dsed = float(dsed)\n osed = float(osed)\n pb = float(pb)\n kd = float(kd)\n except IndexError:\n raise IndexError\\\n ('The mass of pesticide applied per unit area, water column depth,'\\\n ' the sediment depth, porosity of sediment, the bulk density of sediment,'\\\n 'and/or the water-sediment partitioning coefficient must be supplied on'\\\n ' the command line.')\n except ValueError:\n raise ValueError\\\n ('The mass of pesticide applied per unit area must be a real number, '\\\n 'not \"%kg/ha\"' %mai1)\n except ValueError:\n raise ValueError\\\n ('The water column depth must be a real number, not \"%cm\"' % dw)\n except ValueError:\n raise ValueError\\\n ('The sediment depth must be a real number, not \"%cm\"' %dsed)\n except ValueError:\n raise ValueError\\\n ('The porosity of the sediment must be a real number' %osed)\n except ValueError:\n raise ValueError\\\n ('The bulk density of the sediment must be a real number, not\"%kg/m3\"' %pb)\n except ValueError:\n raise ValueError\\\n ('The water-sediment partitioning coefficient must be a real number,'\\\n ' not\"%kg/L\"' %kd)\n if mai1 < 0:\n raise ValueError\\\n ('mai1=%g is a non-physical value.' % mai1)\n if dw < 0:\n raise ValueError\\\n ('dw=%g is a non-physical value.' % dw)\n if dsed < 0:\n raise ValueError\\\n ('dsed=%g is a non-physical value.' % dsed)\n if osed < 0:\n raise ValueError\\\n ('osed=g% is a non-physical value.' %osed)\n if pb < 0:\n raise ValueError\\\n ('pb=g% is a non-physical value.' %pb)\n if kd < 0:\n raise ValueError\\\n ('kd=g% is a non-physical value.' % kd)\n return mai1*1e-2 / (dw + (dsed * (osed + (pb * kd*0.001))))\n\napp = webapp.WSGIApplication([('/msed', MsedService)],\n debug=True)\n\ndef main():\n run_wsgi_app(app)\n\nif __name__ == '__main__':\n main()","sub_path":"rice/rice_model.py","file_name":"rice_model.py","file_ext":"py","file_size_in_byte":5414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"645816000","text":"#!/usr/bin/python3\n\nfrom math import sqrt\n\ndef manhattanDistanceForSolvability(puzzle, goal):\n\theuristic = 0\n\tpuzzleRowSize = int(sqrt(len(puzzle)))\n\tfor square in goal:\n\t\tgoalSquareI = goal.index(square)\n\t\tpuzzleSquareI = puzzle.index(square)\n\t\theuristic += abs(puzzleSquareI % puzzleRowSize - goalSquareI % puzzleRowSize) + abs(puzzleSquareI // puzzleRowSize - goalSquareI // puzzleRowSize)\n\treturn heuristic\n\n# @profile\ndef manhattanDistance(puzzle, goal):\n\theuristic = 0\n\tpuzzleRowSize = int(sqrt(len(puzzle)))\n\tfor square in goal:\n\t\tif square != 0 and puzzle.index(square) != goal.index(square):\n\t\t\tgoalSquareI = goal.index(square)\n\t\t\tpuzzleSquareI = puzzle.index(square)\n\t\t\theuristic += abs(goalSquareI % puzzleRowSize - puzzleSquareI % puzzleRowSize) + abs(goalSquareI // puzzleRowSize - puzzleSquareI // puzzleRowSize)\n\treturn heuristic\n\ndef linearConflictLoopConditions(puzzleNextSquareI, puzzleSquareI, puzzleRowSize, puzzle, nbLinearConflict, goalSquareI, division, goal):\n\t\n\treturn nbLinearConflict\n\n# @profile\ndef linearConflict(puzzle, goal):\n\tpuzzleRowSize = int(sqrt(len(puzzle)))\n\tnbLinearConflict = 0\n\tfor square in puzzle:\n\t\tif square != 0 and puzzle.index(square) != goal.index(square):\n\t\t\tgoalSquareI = goal.index(square)\n\t\t\tpuzzleSquareI = puzzle.index(square)\n\t\t\tif puzzleSquareI // puzzleRowSize == goalSquareI // puzzleRowSize:\n\t\t\t\tpuzzleSquareRow = puzzleSquareI // puzzleRowSize\n\n\t\t\t\tfor puzzleNextSquareI in range(puzzleRowSize * puzzleSquareRow, puzzleSquareI + (puzzleRowSize * (puzzleSquareRow + 1) - puzzleSquareI) - 1):\n\t\t\t\t\tif puzzleNextSquareI != 0 and puzzleNextSquareI != puzzleSquareI and puzzleNextSquareI // puzzleRowSize == goal.index(puzzle[puzzleNextSquareI]) // puzzleRowSize:\n\t\t\t\t\t\tgoalNextSquareI = goal.index(puzzle[puzzleNextSquareI])\n\t\t\t\t\t\tif (puzzleNextSquareI > puzzleSquareI and goalNextSquareI < goalSquareI) or (puzzleNextSquareI < puzzleSquareI and goalNextSquareI > goalSquareI):\n\t\t\t\t\t\t\tnbLinearConflict += 1\n\n\t\t\tif puzzleSquareI % puzzleRowSize == goalSquareI % puzzleRowSize:\n\n\t\t\t\tfor puzzleNextSquareI in range(puzzleSquareI, len(puzzle) - 1, puzzleRowSize):\n\t\t\t\t\tif puzzleNextSquareI != 0 and puzzleNextSquareI != puzzleSquareI and puzzleNextSquareI % puzzleRowSize == goal.index(puzzle[puzzleNextSquareI]) % puzzleRowSize:\n\t\t\t\t\t\tgoalNextSquareI = goal.index(puzzle[puzzleNextSquareI])\n\t\t\t\t\t\tif (puzzleNextSquareI > puzzleSquareI and goalNextSquareI < goalSquareI) or (puzzleNextSquareI < puzzleSquareI and goalNextSquareI > goalSquareI):\n\t\t\t\t\t\t\tnbLinearConflict += 1\n\t\n\t# print(manhattanDistance(puzzle, goal, withZero) + nbLinearConflict)\n\n\treturn manhattanDistance(puzzle, goal) + nbLinearConflict\n\ndef tilesOutOfRowAndColumn(puzzle, goal):\n\tpuzzleRowSize = int(sqrt(len(puzzle)))\n\tnbTilesOutOfRowAndColumn = 0\n\n\tfor square in puzzle:\n\t\tif square != 0 and puzzle.index(square) != goal.index(square):\n\t\t\tgoalSquareI = goal.index(square)\n\t\t\tpuzzleSquareI = puzzle.index(square)\n\t\t\tif puzzleSquareI // puzzleRowSize != goalSquareI // puzzleRowSize:\n\t\t\t\tnbTilesOutOfRowAndColumn += 1\n\t\t\tif puzzleSquareI % puzzleRowSize != goalSquareI % puzzleRowSize:\n\t\t\t\tnbTilesOutOfRowAndColumn += 1\n\n\treturn nbTilesOutOfRowAndColumn\n\n\ndef misplacedTiles(puzzle, goal):\n\tnbMisplacedTiles = 0\n\n\tfor square in puzzle:\n\t\tif square != 0 and puzzle.index(square) != goal.index(square):\n\t\t\tnbMisplacedTiles += 1\n\treturn nbMisplacedTiles","sub_path":"Projects/npuzzle/heuristics.py","file_name":"heuristics.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"141406675","text":"import ConfigParser\t\t#to get API keys from another configuration file\nimport json\n\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream #required only for streaming api\nfrom tweepy import API\n\nclass Create_conn:\n\t\"\"\"This class is responsible for OAuth required by Twitter API\n\t\tKeys and tokens need to be generated by making new app on dev.twitter.com.\n\t\tThey should be placed in a separate file (.twitter)\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\"This gets the api keys and tokens from external file\"\"\"\t\n\n\t\tconfig = ConfigParser.ConfigParser()\n\t\tconfig.read('.twitter')\n\n\t\tself.consumer_key = config.get('apikey', 'key')\n\t\tself.consumer_secret = config.get('apikey', 'secret')\n\t\tself.access_token = config.get('token', 'token')\n\t\tself.access_token_secret = config.get('token', 'secret')\n\t\tself.stream_rule = config.get('app', 'rule')\n\t\tself.account_screen_name = config.get('app', 'account_screen_name').lower() \n\t\tself.account_user_id = config.get('app', 'account_user_id')\n\n\tdef authorize(self):\n\t\t\"\"\"This is responsible for generating newapi OAuth (creating conncetion)\"\"\"\n\t\tauth = OAuthHandler(self.consumer_key, self.consumer_secret)\n\t\tauth.set_access_token(self.access_token, self.access_token_secret)\n\t\tself.tweetApi = API(auth)\n\t\treturn self.tweetApi\n\t\t\nif __name__ == '__main__':\n\tmyconn= Create_conn()\n\ttwitterApi= myconn.authorize()","sub_path":"Desktop Application/twitter_connection.py","file_name":"twitter_connection.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"397286384","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport datetime\n\nfrom forms import MessageForm\n\n################ \n#### config #### \n################\n\napp = Flask(__name__)\napp.config.from_pyfile('_config.py')\ndb = SQLAlchemy(app)\n\nfrom models import Messages\n\n################ \n#### routes #### \n################\n\ndef list_messages():\n return db.session.query(Messages).order_by(Messages.message_date.desc())\n\n\n@app.route(\"/\", methods=['GET','POST'])\ndef main():\n error = None\n form = MessageForm(request.form)\n if request.method == 'POST':\n if form.validate_on_submit():\n new_message = Messages(\n datetime.datetime.utcnow(),\n form.message.data\n )\n db.session.add(new_message)\n db.session.commit()\n return redirect(url_for('main'))\n return render_template(\n 'main.html',\n messages=list_messages(),\n form=form,\n error=error\n )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"323468306","text":"import torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nfrom importlib import import_module\nimport shutil\nimport glob\nimport os\nimport sys\n\nfrom data_loader.data_generator import DataLoader\nfrom utils.data_utils import *\nfrom utils.training_utils import ModelCheckpoint, EarlyStopping\nfrom losses_and_metrics import loss_functions, metrics\nfrom config import Config\n\n'''seed = 0\ntorch.manual_seed(seed)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(seed)\nnp.random.seed(seed)'''\n\n\nclass Trainer:\n def __init__(self, config):\n self.config = config\n self.terminal_width = shutil.get_terminal_size((80, 20)).columns\n\n # Model\n print(f' Model: {self.config.architecture} '.center(self.terminal_width, '*'))\n model_type = import_module('models.' + self.config.architecture)\n create_model = getattr(model_type, 'create_model')\n self.model = create_model(self.config)\n print(self.model, end='\\n\\n')\n\n # Loss, Optimizer and LRScheduler\n self.criterion = getattr(loss_functions, self.config.loss_fn)(self.config)\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.config.learning_rate)\n self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, factor=0.5,\n patience=4, verbose=True)\n self.early_stopping = EarlyStopping(patience=10)\n self.agg_sum = self.config.loss_fn[:3] == 'SPL'\n self.loss_agg = np.sum if self.agg_sum else np.mean\n\n # Metric\n self.metric = getattr(metrics, config.metric)()\n self.metric_2 = getattr(metrics, config.secondary_metric)()\n\n print(f' Loading Data '.center(self.terminal_width, '*'))\n data_loader = DataLoader(self.config)\n self.ids = data_loader.ids\n\n self.train_loader = data_loader.create_train_loader()\n self.val_loader = data_loader.create_val_loader()\n self.n_windows = data_loader.n_windows\n\n self.start_epoch, self.min_val_error = 1, None\n # Load checkpoint if training is to be resumed\n self.model_checkpoint = ModelCheckpoint(config=self.config)\n if config.resume_training:\n self.model, self.optimizer, self.scheduler, [self.start_epoch, self.min_val_error, num_bad_epochs] = \\\n self.model_checkpoint.load(self.model, self.optimizer, self.scheduler)\n self.early_stopping.best = self.min_val_error\n self.early_stopping.num_bad_epochs = num_bad_epochs\n print(f'Resuming model training from epoch {self.start_epoch}')\n else:\n # remove previous logs, if any\n if self.config.fold is None:\n logs = glob.glob('./logs/.*') + glob.glob('./logs/*')\n for f in logs:\n try:\n os.remove(f)\n except IsADirectoryError:\n shutil.rmtree(f)\n else:\n logs = glob.glob(f'./logs/fold_{self.config.fold}/.*') + glob.glob(f'./logs/fold_{self.config.fold}/*')\n for f in logs:\n os.remove(f)\n\n # logging\n self.writer = SummaryWriter(f'logs') if self.config.fold is None \\\n else SummaryWriter(f'logs/fold_{self.config.fold}')\n\n def _get_val_loss_and_err(self):\n self.model.eval()\n progbar = tqdm(self.val_loader)\n progbar.set_description(\" \")\n losses, epoch_preds, epoch_ys, epoch_ws, epoch_scales = [], [], [], [], []\n for i, [x, y, norm_factor, ids_idx, loss_input, _] in enumerate(progbar):\n epoch_ys.append(y.data.numpy())\n epoch_scales.append(loss_input[0].data.numpy())\n epoch_ws.append(loss_input[1].data.numpy())\n\n x = [inp.to(self.config.device) for inp in x]\n y = y.to(self.config.device)\n norm_factor = norm_factor.to(self.config.device)\n loss_input = [inp.to(self.config.device) for inp in loss_input]\n\n preds = self.model(*x) * norm_factor[:, None, None]\n epoch_preds.append(preds.data.cpu().numpy())\n loss = self.criterion(preds, y, *loss_input)\n losses.append(loss.data.cpu().numpy())\n\n epoch_preds, epoch_ys = np.concatenate(epoch_preds, axis=0), np.concatenate(epoch_ys, axis=0)\n epoch_ws, epoch_scales = np.concatenate(epoch_ws, axis=0), np.concatenate(epoch_scales, axis=0)\n\n val_error = self.metric.get_error(epoch_preds, epoch_ys, epoch_scales, epoch_ws)\n val_error_2 = self.metric_2.get_error(epoch_preds[:, :, 4], epoch_ys, epoch_scales, epoch_ws)\n\n return self.loss_agg(losses), val_error, val_error_2\n\n def train(self):\n print(f' Training '.center(self.terminal_width, '*'), end='\\n\\n')\n\n for epoch in range(self.start_epoch, self.config.num_epochs + 1):\n print(f' Epoch [{epoch}/{self.config.num_epochs}] '.center(self.terminal_width, 'x'))\n self.model.train()\n progbar = tqdm(self.train_loader)\n losses, epoch_preds, epoch_ys, epoch_ws, epoch_scales = [], [], [], [], []\n for i, [x, y, norm_factor, ids_idx, loss_input, window_id] in enumerate(progbar):\n x = [inp.to(self.config.device) for inp in x]\n y = y.to(self.config.device)\n norm_factor = norm_factor.to(self.config.device)\n loss_input = [inp.to(self.config.device) for inp in loss_input]\n\n # Forward + Backward + Optimize\n self.optimizer.zero_grad()\n preds = self.model(*x) * norm_factor[:, None, None]\n\n if self.config.sliding_window:\n if torch.sum(window_id == self.n_windows - 1) > 0:\n epoch_ys.append(y[window_id == self.n_windows - 1].data.cpu().numpy().reshape(-1, 28))\n epoch_scales.append(loss_input[0][window_id == self.n_windows - 1]\n .data.cpu().numpy().reshape(-1))\n epoch_ws.append(loss_input[1][window_id == self.n_windows - 1]\n .data.cpu().numpy().reshape(-1))\n epoch_preds.append(preds[window_id == self.n_windows - 1].data.cpu().numpy().reshape(-1, 28, 9))\n else:\n epoch_ys.append(y.data.cpu().numpy())\n epoch_scales.append(loss_input[0].data.cpu().numpy())\n epoch_ws.append(loss_input[1].data.cpu().numpy())\n epoch_preds.append(preds.data.cpu().cpu().numpy())\n\n loss = self.criterion(preds, y, *loss_input)\n losses.append(loss.data.cpu().numpy())\n\n if self.agg_sum:\n progbar.set_description(\"loss = %0.3f \" % np.round(\n (len(self.train_loader) / (i + 1)) * self.loss_agg(losses) / self.n_windows, 3))\n else:\n progbar.set_description(\"loss = %0.3f \" % np.round(self.loss_agg(losses), 3))\n\n loss.backward()\n self.optimizer.step()\n\n # Get training and validation loss and error\n epoch_preds, epoch_ys = np.concatenate(epoch_preds, axis=0), np.concatenate(epoch_ys, axis=0)\n epoch_ws, epoch_scales = np.concatenate(epoch_ws, axis=0), np.concatenate(epoch_scales, axis=0)\n\n if self.agg_sum:\n train_loss = self.loss_agg(losses) / self.n_windows\n else:\n train_loss = self.loss_agg(losses)\n\n train_error = self.metric.get_error(epoch_preds, epoch_ys, epoch_scales, epoch_ws)\n train_error_2 = self.metric_2.get_error(epoch_preds[:, :, 4], epoch_ys, epoch_scales, epoch_ws)\n\n val_loss, val_error, val_error_2 = self._get_val_loss_and_err()\n\n print(f'Training Loss: {train_loss:.4f}, Training Error: {train_error:.4f}, '\n f'Training Secondary Error: {train_error_2:.4f}\\n'\n f'Validation Loss: {val_loss:.4f}, Validation Error: {val_error:.4f}, '\n f'Validation Secondary Error: {val_error_2:.4f}')\n\n # Change learning rate according to scheduler\n self.scheduler.step(val_error)\n\n # save checkpoint and best model\n if self.min_val_error is None:\n self.min_val_error = val_error\n is_best = True\n print(f'Best model obtained at the end of epoch {epoch}')\n else:\n if val_error < self.min_val_error:\n self.min_val_error = val_error\n is_best = True\n print(f'Best model obtained at the end of epoch {epoch}')\n else:\n is_best = False\n self.model_checkpoint.save(is_best, self.min_val_error, self.early_stopping.num_bad_epochs,\n epoch, self.model, self.optimizer, self.scheduler)\n\n # write logs\n self.writer.add_scalar(f'{self.config.loss_fn}/train', train_loss, epoch * i)\n self.writer.add_scalar(f'{self.config.loss_fn}/val', val_loss, epoch * i)\n self.writer.add_scalar(f'{self.config.metric}/train', train_error, epoch * i)\n self.writer.add_scalar(f'{self.config.metric}/val', val_error, epoch * i)\n self.writer.add_scalar(f'{self.config.secondary_metric}/train', train_error_2, epoch * i)\n self.writer.add_scalar(f'{self.config.secondary_metric}/val', val_error_2, epoch * i)\n\n # Early Stopping\n if self.early_stopping.step(val_error):\n print(f' Training Stopped'.center(self.terminal_width, '*'))\n print(f'Early stopping triggered after epoch {epoch}')\n break\n\n self.writer.close()\n\n\nif __name__ == \"__main__\":\n # sys.stdout = open('train.log', 'w')\n # sys.stderr = sys.stdout\n config = Config\n terminal_width = shutil.get_terminal_size((80, 20)).columns\n # Check if k-fold training is enabled\n if config.k_fold:\n print(f' K-fold Training '.center(terminal_width, '*'))\n\n # If resuming model training, start training from specified fold\n start_fold = config.resume_from_fold - 1 if config.resume_training else 0\n\n # Loop over all folds and train model using the corresponding fold config\n for fold, [fold_train_ts, fold_val_ts] in enumerate(config.k_fold_splits):\n if fold < start_fold:\n continue\n config.fold = fold + 1\n print()\n print(f' Fold [{config.fold}/{len(config.k_fold_splits)}] '.center(terminal_width, '*'))\n config.training_ts, config.validation_ts = fold_train_ts, fold_val_ts\n\n trainer = Trainer(config)\n trainer.train()\n config.resume_training = False # Train future folds from the beginning\n else:\n config.fold = None\n trainer = Trainer(config)\n trainer.train()\n","sub_path":"course/msbd5013/2022/project2/group6_TSE_YUEN(M5)/code/Seq2Seq_Others/uncertainty_stream/.ipynb_checkpoints/train-checkpoint.py","file_name":"train-checkpoint.py","file_ext":"py","file_size_in_byte":11098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"134770935","text":"from sys import stdin\np=(stdin.readline().strip())\n\np=p.lower()\n\ndef letra(frase,x,y,pal):\n if pal>0:\n if frase[x]==frase[y]:\n letra(frase,x+1,y-1,pal-1)\n else:\n print(\"Incorrecta\")\n\n else:\n print(\"Correcta\")\n\nletra(p,0,len(p)-1,len(p))\n","sub_path":"soluciones/semana4/palindromas.py","file_name":"palindromas.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"468567923","text":"# -*- coding: utf-8 -*-\n# © 2019 Comunitea\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\nfrom openerp.addons.connector.event import (\n on_record_create,\n on_record_unlink,\n on_record_write,\n)\nfrom openerp.addons.connector.queue.job import job\nfrom openerp.addons.connector.unit.synchronizer import Exporter\n\nfrom ..backend import bananas\nfrom ..unit.backend_adapter import GenericAdapter\nfrom .utils import _get_exporter, get_next_execution_time\n\n\n@bananas\nclass ProductExporter(Exporter):\n\n _model_name = [\"product.product\"]\n\n def update(self, binding_id, mode):\n product = self.model.browse(binding_id)\n vals = {\n \"referencia\": str(product.id),\n \"nombre\": product.name,\n \"unidad\": product.container_id.name or 'unidad',\n \"unidadbulto\": \"caja\",\n \"unidadesxbulto\": product.box_elements,\n \"familia\": product.line.name,\n \"subfamilia\": product.subline.name,\n \"vendounidad\": 1,\n \"vendobulto\": 1,\n \"descripcion\": product.description_sale or \"\",\n \"foto\": product.external_image_url,\n \"precio\": 9999.99, # La app siempre muestra el precio mas bajo.\n }\n if mode == \"insert\":\n if not self.backend_adapter.check_id(vals['referencia']):\n return self.backend_adapter.insert(vals)\n else:\n return self.backend_adapter.update(binding_id, vals)\n\n def delete(self, binding_id):\n return self.backend_adapter.remove(binding_id)\n\n\n@bananas\nclass ProductAdapter(GenericAdapter):\n _model_name = \"product.product\"\n _bananas_model = \"articulos\"\n\n\n@on_record_create(model_names=\"product.product\")\ndef delay_export_product_create(session, model_name, record_id, vals):\n product = session.env[model_name].browse(record_id)\n up_fields = [\n \"name\",\n \"container_id\",\n \"box_elements\",\n \"line\",\n \"subline\",\n \"description_sale\",\n ]\n eta = get_next_execution_time(session)\n if vals.get(\"bananas_synchronized\", False) and vals.get(\n \"active\", product.active\n ):\n export_product.delay(session, model_name, record_id, priority=1, eta=eta+60)\n elif (\n vals.get(\"active\", False)\n and vals.get(\"bananas_synchronized\", False)\n and product.bananas_synchronized\n ):\n export_product.delay(session, model_name, record_id, priority=1, eta=eta+60)\n elif product.bananas_synchronized:\n for field in up_fields:\n if field in vals:\n update_product.delay(\n session, model_name, record_id, priority=5, eta=eta+120\n )\n break\n\n\n@on_record_write(model_names=[\"product.product\", \"product.template\"])\ndef delay_export_product_write(session, model_name, record_id, vals):\n eta = get_next_execution_time(session)\n if model_name == \"product.product\":\n products = session.env[model_name].browse(record_id)\n else:\n products = session.env[model_name].browse(record_id).product_variant_ids\n for product in products:\n up_fields = [\n \"name\",\n \"container_id\",\n \"box_elements\",\n \"line\",\n \"subline\",\n \"description_sale\",\n ]\n if vals.get(\"bananas_synchronized\", False) and vals.get(\n \"active\", product.active\n ):\n if vals['bananas_synchronized']:\n export_product.delay(\n session, \"product.product\", product.id, priority=1, eta=eta+60\n )\n\n elif (\n \"bananas_synchronized\" in vals and not vals[\"bananas_synchronized\"]\n ):\n unlink_product.delay(\n session, \"product.product\", product.id, priority=1, eta=eta+60\n )\n\n elif (\n product.bananas_synchronized\n and \"active\" in vals\n and not vals[\"active\"]\n ):\n unlink_product.delay(\n session, \"product.product\", product.id, priority=1, eta=eta+60\n )\n\n elif product.bananas_synchronized:\n for field in up_fields:\n if field in vals:\n update_product.delay(\n session,\n \"product.product\",\n product.id,\n priority=2,\n eta=eta+120,\n )\n break\n\n\n@on_record_unlink(model_names=\"product.product\")\ndef delay_unlink_product(session, model_name, record_id):\n product = session.env[model_name].browse(record_id)\n if product.bananas_synchronized:\n eta = get_next_execution_time(session)\n unlink_product.delay(session, model_name, record_id, eta=eta+60)\n\n\n@job(retry_pattern={1: 10 * 60, 2: 20 * 60, 3: 30 * 60, 4: 40 * 60, 5: 50 * 60})\ndef export_product(session, model_name, record_id):\n product_exporter = _get_exporter(\n session, model_name, record_id, ProductExporter\n )\n return product_exporter.update(record_id, \"insert\")\n\n\n@job(retry_pattern={1: 10 * 60, 2: 20 * 60, 3: 30 * 60, 4: 40 * 60, 5: 50 * 60})\ndef update_product(session, model_name, record_id):\n product_exporter = _get_exporter(\n session, model_name, record_id, ProductExporter\n )\n return product_exporter.update(record_id, \"update\")\n\n\n@job(retry_pattern={1: 10 * 60, 2: 20 * 60, 3: 30 * 60, 4: 40 * 60, 5: 50 * 60})\ndef unlink_product(session, model_name, record_id):\n product_exporter = _get_exporter(\n session, model_name, record_id, ProductExporter\n )\n return product_exporter.delete(record_id)\n","sub_path":"project-addons/connector_20_bananas/events/product_events.py","file_name":"product_events.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"388462915","text":"from pymetasploit3.msfrpc import *\nfrom parser import process_parser\nfrom update import getCvesDescrip\nimport pymysql\nimport json\n\n'''\nexploit_product\n\nsteps\n1. 通過cve找尋可用modules\n2. 設定modules\n3. 設定payload\n4. 結果回傳到msfconcole\n5. 將有弱點之設備回傳\n\ninput\n1. prod_info\n{ip:xxx,port:xxx,cve:xxx}\n'''\n\nalert_infos = []\ndef exploit_product(prod_info):\n #connnect to msfconcole\n client = MsfRpcClient('a407410040',port=55552)\n '''\n 1. search module\n '''\n cve = 'cve:' + prod_info[\"cve\"]\n cve_modules = client.modules.search(cve)\n \n #check modules empty or not\n if len(cve_modules) == 0:\n print(\"no corresponding modules\")\n return\n \n module_fullname = cve_modules[0][\"fullname\"]\n if module_fullname.split('/')[0] != 'exploit':\n return\n module = '/'.join(module_fullname.split('/')[1:])\n #print(module)\n \n '''\n 2. set module\n '''\n exploit = client.modules.use('exploit',module)\n #print(exploit.missing_required)\n if \"RHOSTS\" in exploit.missing_required:\n exploit['RHOSTS'] = prod_info[\"ip\"]\n exploit['RPORT'] = prod_info[\"port\"]\n elif \"SESSION\" in exploit.missing_required:\n print(\"we need session\")\n return\n \n '''\n 3. set payload\n '''\n #check payload empty or not\n if len(exploit.payloads) == 0:\n print(\"no useful payload\")\n return\n \n p = exploit.payloads[0]\n payload = client.modules.use('payload',p)\n #print(payload.missing_required)\n if 'LHOST' in payload.missing_required:\n payload['LHOST'] = '140.123.230.32'\n payload['LPORT'] = 4444\n\n f = open(\"/var/www/html/ccu_proj_manyPorts/api/exploit.txt\",\"a+\")\n f.write(prod_info[\"ip\"]+\" \" + prod_info[\"port\"] + \" \" + prod_info[\"cve\"]+\"\\n\")\n f.close()\n \n '''\n 4. connect to console\n '''\n console_id = client.consoles.console().cid\n console = client.consoles.console(console_id)\n output = console.run_module_with_output(exploit,payload=payload)\n \n '''\n 5. 將有弱點之設備回傳\n '''\n f = open(\"/var/www/html/ccu_proj_manyPorts/www/alert.json\",\"w\")\n if 'session' in output:\n if 'open' in output:\n cveInfo = getCvesDescrip(prod_info[\"cve\"])\n info = {\n \"ip\" : prod_info[\"ip\"],\n \"port\" : prod_info[\"port\"],\n \"cve\" : prod_info[\"cve\"],\n \"cvss\" : cveInfo[\"cvss\"],\n \"description\" : cveInfo[\"description\"]\n }\n alert_infos.append(info)\n json.dump(alert_infos,f)\n f.close() \n\n'''\nprodinfo_from_db\n\n功能\n1. 從資料庫中取資料\n\ninput\n1. table_id : 欲exploit的db\n\n'''\n\ndef prodinfo_from_db(table_id):\n \n prod_infos = []\n db = pymysql.connect(host=\"140.123.230.32\",user=\"root\",passwd=\"a407410040\",db=\"iot\",cursorclass=pymysql.cursors.DictCursor)\n cursor = db.cursor()\n \n sql = \"select * from ip_\" + table_id\n cursor.execute(sql)\n res = cursor.fetchall()\n for row in res:\n info = {\n \"ip\":None,\n \"port\":[],\n \"cve\":[]\n } \n #print(row)\n ip = row[\"ip\"]\n info[\"ip\"] = ip\n \n #port\n sql = \"select * from port_\" + table_id + \" where port_ip='\" + ip + \"'\"\n cursor.execute(sql)\n port_res = cursor.fetchall()\n #print(port_res)\n for port_row in port_res:\n info[\"port\"].append(str(port_row[\"port\"]))\n \n #cve\n sql = \"select * from cve_\" + table_id + \" where cve_ip='\" + ip + \"'\"\n cursor.execute(sql)\n cve_res = cursor.fetchall()\n for cve_row in cve_res:\n info[\"cve\"].append(cve_row[\"cve_id\"])\n prod_infos.append(info.copy())\n #print(prod_infos)\n return prod_infos\n\n'''\nexploit()\n\nsteps\n1. 區分資料\n2. 執行exploit_product\n'''\n\ndef exploit(prod_infos):\n info = {}\n for i in range(len(prod_infos)):\n info[\"ip\"] = prod_infos[i][\"ip\"]\n for j in range(len(prod_infos[i][\"port\"])):\n info[\"port\"] = prod_infos[i][\"port\"][j]\n for k in range(len(prod_infos[i][\"cve\"])):\n info[\"cve\"] = prod_infos[i][\"cve\"][k]\n print(info[\"ip\"]+\" \"+info[\"port\"]+\" \"+info[\"cve\"])\n exploit_product(info)\n\n'''\n__main__\n\nsteps\n1. prodinfo_from_db\n2. exploit\n'''\n\nif __name__ == \"__main__\":\n args = process_parser()\n prod_infos = prodinfo_from_db(str(args.table_id)) \n '''\n #test\n prod_infos = []\n info = {\n \"ip\":\"140.123.230.32\",\n \"port\":['8080'],\n \"cve\":['CVE-2017-17562']\n }\n prod_infos.append(info)\n '''\n exploit(prod_infos)\n","sub_path":"api/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"110918681","text":"import FeatureExtraction as ft\nimport numpy as np\n\n\ndef get_x_y_train(train_forms_filenames, method):\n Y_train = []\n X_train = None\n\n for writer_index, writer_forms in enumerate(train_forms_filenames):\n label = writer_index\n\n for form_filename in writer_forms:\n feature_vectors = ft.get_form_feature_vectors(form_filename, methods=method)\n labels = [label] * len(feature_vectors)\n\n if X_train is None:\n X_train = feature_vectors\n else:\n X_train = np.concatenate([X_train, feature_vectors], axis=0)\n Y_train = Y_train + labels\n\n return X_train, Y_train\n\n\ndef get_guessed_writer(test_form, clf, feature_method, voting_method='majority'):\n X_test = ft.get_form_feature_vectors(test_form, methods=feature_method)\n\n if voting_method == 'majority':\n per_block_predictions = list(clf.predict(X_test))\n guessed_writer = max(set(per_block_predictions), key=per_block_predictions.count) # ALERT on tie chooses first\n confidence = per_block_predictions.count(guessed_writer) / len(per_block_predictions)\n elif voting_method == 'confidence_sum':\n per_block_predictions = list(np.sum(clf.predict_proba(X_test), 0) / len(X_test))\n guessed_writer = np.argmax(per_block_predictions)\n confidence = per_block_predictions[guessed_writer]\n elif voting_method == 'square_confidence_sum':\n per_block_predictions = np.sum(np.power(clf.predict_proba(X_test),2), 0)\n per_block_predictions = per_block_predictions / np.sum(per_block_predictions)\n guessed_writer = np.argmax(per_block_predictions)\n confidence = per_block_predictions[guessed_writer]\n else:\n raise NotImplementedError(\"No such method for guessing writer was implemented:\", voting_method)\n\n return guessed_writer, confidence\n\n\ndef get_predictions(test_forms_filenames, clf, feature_method, voting_method):\n predictions = []\n confidences = []\n for form_filename in test_forms_filenames:\n prediction, confidence = get_guessed_writer(form_filename, clf, feature_method, voting_method)\n predictions.append(prediction)\n confidences.append(confidence)\n\n return predictions, confidences\n\n\ndef train(train_forms_filenames, clf, feature_method):\n X_train, Y_train = get_x_y_train(train_forms_filenames, feature_method)\n clf.fit(X_train, Y_train)\n return clf\n\n\ndef run_trial(train_forms_filenames, test_forms_filenames, clf, feature_method, voting_method):\n clf = train(train_forms_filenames, clf, feature_method)\n return get_predictions(test_forms_filenames, clf, feature_method, voting_method)\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"611943483","text":"import pprint\n\nfrom discord.abc import User\nfrom discord.ext import commands\nfrom discord.ext.commands.context import Context\n\nfrom milton.core.bot import Milton\nfrom milton.core.database import MiltonUser\nfrom milton.core.errors import MiltonInputError\nfrom milton.utils.paginator import Paginator\nfrom milton.utils.tools import fetch\nfrom milton.utils.tools import id_from_mention\n\n\nclass DebugCog(commands.Cog, name=\"Debug\"):\n \"\"\"\"\"\"\n\n def __init__(self, bot) -> None:\n self.bot: Milton = bot\n\n def cog_check(self, ctx: Context):\n # Assure that these commands may only be executed from the owner of the\n # bot.\n return self.bot.is_owner(ctx.author)\n\n @commands.command()\n async def test(self, ctx: Context):\n \"\"\"Sends a test message in order to try pagination.\n\n The contents are retrieved from a remote sever, baconipsum.com, which\n generates meaty fillers.\n \"\"\"\n out = Paginator(title=\"Powered by www.baconipsum.com\")\n endpoint = \"https://baconipsum.com/api/\"\n\n response = await fetch(\n self.bot.http_session,\n endpoint,\n params={\n \"type\": \"meat-and-filler\",\n \"paras\": 15,\n \"start-with-lorem\": 1,\n \"format\": \"text\",\n },\n )\n\n for line in response.split(\"\\n\"):\n out.add_line(line)\n await out.paginate(ctx)\n\n @commands.command()\n async def inspect(self, ctx: Context, name: str):\n \"\"\"Shows someone's statistics\"\"\"\n\n try:\n id_, type_ = id_from_mention(name)\n except ValueError:\n raise MiltonInputError(\"Not a valid mention or ID\")\n\n member: User = self.bot.get_user(id_)\n if not member:\n raise MiltonInputError(\"Cannot Find User\")\n\n out = Paginator(force_embed=True, title=f\"Data for user {member.name}\")\n async with MiltonUser(id_) as user:\n formatted = pprint.pformat(user.data, indent=4)\n print(formatted)\n formatted = formatted.split(\"\\n\")\n for line in formatted:\n out.add_line(line)\n await out.paginate(ctx)\n\n\ndef setup(bot: Milton):\n bot.add_cog(DebugCog(bot))\n","sub_path":"milton/core/cogs/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"429134500","text":"# Piano\n# \n# A simple multi-touch piano.\n\nfrom scene import *\nimport sound\nfrom itertools import chain\n\nclass Key (object):\n\tdef __init__(self, frame):\n\t\tself.frame = frame\n\t\tself.name = None\n\t\tself.touch = None\n\t\tself.color = Color(1, 1, 1)\n\t\tself.highlight_color = Color(0.9, 0.9, 0.9)\n\t\t\n\tdef hit_test(self, touch):\n\t\treturn touch.location in self.frame\n\nclass Piano (Scene):\n\tdef setup(self):\n\t\tself.white_keys = []\n\t\tself.black_keys = []\n\t\twhite_key_names = ['weier3.wav', 'weier5.wav', 'weier7.wav',\n\t\t 'weier8.wav', 'weier10.wav', 'weier0.wav', \n\t\t 'weier2.wav']\n\t\tblack_key_names = ['weier4.wav', 'weier6.wav', 'weier9.wav', \n\t\t 'weier11.wav', 'weier1.wav']\n\t\tfor key_name in chain(white_key_names, black_key_names):\n\t\t\tsound.load_effect(key_name)\n\t\twhite_positions = range(7)\n\t\tblack_positions = [0.5, 1.5, 3.5, 4.5, 5.5]\n\t\tkey_w = self.size.w / 7\n\t\tkey_h = self.size.h \n\t\tfor i in range(len(white_key_names)):\n\t\t\tpos = white_positions[i]\n\t\t\tkey = Key(Rect(pos*key_w, 0, key_w, key_h))\n\t\t\tkey.name = white_key_names[i]\n\t\t\tself.white_keys.append(key)\n\t\tfor i in range(len(black_key_names)):\n\t\t\tpos = black_positions[i]\n\t\t\tkey = Key(Rect( pos * key_w + 10,key_h*0.4, key_w -20, key_h))\n\t\t\tkey.name = black_key_names[i]\n\t\t\tkey.color = Color(0, 0, 0)\n\t\t\tkey.highlight_color = Color(0.2, 0.2, 0.2)\n\t\t\tself.black_keys.append(key)\n\t\t\n\tdef draw(self):\n\t\tstroke_weight(1)\n\t\tstroke(0.5, 0.5, 0.5)\n\t\tfor key in chain(self.white_keys, self.black_keys):\n\t\t\tif key.touch is not None:\n\t\t\t\tfill(*key.highlight_color.as_tuple())\n\t\t\telse:\n\t\t\t\tfill(*key.color.as_tuple())\n\t\t\trect(*key.frame.as_tuple())\n\t\n\tdef touch_began(self, touch):\n\t\tfor key in chain(self.black_keys, self.white_keys):\n\t\t\tif key.hit_test(touch):\n\t\t\t\tkey.touch = touch\n#\t\t\t\tprint(touch.__dict__)\n\t\t\t\tsound.play_effect(key.name)\n\t\t\t\treturn\n\t\n\tdef touch_moved(self, touch):\n\t\thit_key = None\n\t\tfor key in chain(self.black_keys, self.white_keys):\n\t\t\thit = key.hit_test(touch)\n\t\t\tif hit and hit_key is None:\n\t\t\t\thit_key = key\n\t\t\t\tif key.touch is None:\n\t\t\t\t\tkey.touch = touch\n\t\t\t\t\tsound.play_effect(key.name)\n\t\t\tif key.touch == touch and key is not hit_key:\n\t\t\t\tkey.touch = None\n\t\t\t\t\n\tdef touch_ended(self, touch):\n\t\tfor key in chain(self.black_keys, self.white_keys):\n\t\t\tif key.touch == touch:\n\t\t\t\tkey.touch = None\n\nrun(Piano(), LANDSCAPE)\n","sub_path":"Weierstrass_piano.py","file_name":"Weierstrass_piano.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"461482985","text":"# -*- coding: utf-8 -*-\nfrom engines.utils import use_website\n\n\ndef write_tests(output_filename, siteTests, input_skip, input_take):\n with open(output_filename, 'w') as outfile:\n current_index = 0\n for test in siteTests:\n if use_website(current_index, input_skip, input_take):\n format_str = \"\"\"INSERT INTO sitetests (site_id, test_date, type_of_test, check_report, json_check_data, most_recent, rating)\n VALUES (\"{siteid}\", \"{testdate}\", \"{testtype}\", \"{report}\", \"{json}\", \"{recent}\", \"{rating}\");\\n\"\"\"\n sql_command = format_str.format(siteid=test[\"site_id\"], testdate=test[\"date\"], testtype=test[\"type_of_test\"],\n report=test[\"report\"], json=test[\"data\"], recent=1, rating=test[\"rating\"])\n\n current_index += 1\n outfile.write(sql_command)\n","sub_path":"engines/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"318052190","text":"def questionFourteen():\n longest = 0\n winner = 0\n for number in range(600001, 1000000, 2):\n count = 0\n if count == 0:\n x = number\n while number > 1:\n number = int(number)\n #print(number, end=\" \")\n if number % 2 == 0:\n number = number / 2\n else:\n number = 3 * number + 1\n count = count + 1\n if count > longest:\n longest = count\n winner = x\n #print(\"\")5\n print(winner, \", \", longest)\n","sub_path":"001-099/014/todd.py","file_name":"todd.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"190727581","text":"import requests\nimport time\nimport csv\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\nclass Category:\n\n def __init__(self,cat_id,prod_quan,comm_quan):\n\n self.cat_id = cat_id\n self.prod_quan = prod_quan\n self.comm_quan = comm_quan\n\n def check(self):\n print('현재 설정된 카테고리 넘버는 {0}이고, 지정한 상품의 개수는 {1}, 후기의 개수는 {2}입니다.'.format(self.cat_id,self.prod_quan,self.comm_quan))\n\n def max_prod_check(self):\n\n url = \"https://search.shopping.naver.com/search/category?catId=\"+ self.cat_id + \"&frm=NVSHCAT&origQuery&pagingIndex=1&pagingSize=40&productSet=model&query&sort=rel×tamp=&viewType=list\"\n req = requests.get(url)\n html = req.text\n soup = BeautifulSoup(html, 'html.parser')\n\n max_count = soup.select(\n 'ul[class=subFilter_seller_filter__3yvWP] > li > a > span[class=subFilter_num__2x0jq]'\n )\n\n max_prod = max_count[1].text.replace(',','')\n\n if self.prod_quan == 'all' :\n self.prod_quan = max_prod\n\n elif int(self.prod_quan) > int(max_prod) :\n print(\"지정한 상품의 개수가 최대 상품의 개수를 초과하여, 최대개수인 {0}개로 조정됩니다.\".format(max_prod))\n self.prod_quan = max_prod\n\n def max_comm_check(self, max_comm):\n\n if self.comm_quan == 'all' :\n self.comm_quan = max_comm\n elif int(self.comm_quan) > max_comm :\n print(\"지정한 후기의 개수가 최대 후기의 개수를 초과하여, 최대개수인 {0}개로 조정됩니다.\".format(max_comm))\n self.comm_quan = max_comm\n\n\n def url_getter(self):\n\n global url_truck\n\n if int(self.prod_quan) % 80 == 0 :\n page_no = int(self.prod_quan)//80\n else :\n page_no = int(self.prod_quan)//80 + 1\n\n url_truck = []\n\n for i in range(page_no) :\n\n url = \"https://search.shopping.naver.com/search/category?catId=\"+ self.cat_id + \"&frm=NVSHCAT&origQuery&pagingIndex=\"+ str(i + 1) +\"&pagingSize=80&productSet=model&query&sort=rel×tamp=&viewType=list\"\n\n driver = webdriver.Chrome('./chromedriver')\n driver.get(url)\n\n self.scroller(driver)\n\n ls = driver.find_elements_by_class_name('basicList_item__2XT81')\n\n for data in ls :\n url_truck.append(data.find_element_by_css_selector('a').get_attribute('href'))\n\n def scroller(self,driver):\n\n scroll_pause_sec = 1\n\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n while True:\n\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n time.sleep(scroll_pause_sec)\n\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n if new_height == last_height:\n\n time.sleep(scroll_pause_sec)\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n if new_height == last_height:\n break\n\n last_height = new_height\n\n def fake_check(self, driver):\n\n list = driver.find_element_by_class_name('floatingTab_detail_tab__2T3U7').find_elements_by_css_selector('li')\n for index in list :\n if index.find_element_by_tag_name('strong').text == '쇼핑몰리뷰' :\n return True\n\n def page_swap(self, driver, page_info):\n\n if page_info == 'next':\n print(\"실행1\")\n print(driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_element_by_class_name('pagination_next__3ycRH').text)\n cord = driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_element_by_class_name('pagination_next__3ycRH')\n\n elif page_info > 8 :\n print(\"실행2\")\n cord = driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_elements_by_css_selector('a')[(page_info + 1) % 10 + 2]\n else :\n print(\"실행3\")\n cord = driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_elements_by_css_selector('a')[page_info + 1]\n\n driver.execute_script(\"arguments[0].click();\", cord)\n\n\n def comm_getter(self):\n\n for index in range(int(self.prod_quan)) :\n\n url = url_truck[index]\n\n driver = webdriver.Chrome('./chromedriver')\n driver.get(url)\n\n self.scroller(driver)\n\n if self.fake_check(driver) != True:\n continue\n\n max_comm = driver.find_element_by_class_name('floatingTab_detail_tab__2T3U7').find_elements_by_css_selector('li')[-2].find_element_by_css_selector('em').text.replace(',','')\n self.max_comm_check(int(max_comm))\n\n comm_page = int(self.comm_quan) // 20\n comm_left = int(self.comm_quan) % 20\n\n prod_name = driver.find_element_by_class_name('top_summary_title__15yAr').find_element_by_tag_name('h2').text\n f = open(prod_name + '.csv' , 'w' , newline='',encoding='utf-8')\n wr = csv.writer(f)\n wr.writerow(['star_point', 'comment', 'photo'])\n for i in range(comm_page) :\n\n self.comm_getter_2(driver, 20, wr)\n\n if (i % 10) == 9 :\n self.page_swap(driver, 'next')\n time.sleep(1)\n #driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_element_by_class_name('pagination_next__3ycRH').click()\n\n if i == (comm_page - 1) :\n break\n self.page_swap(driver, i)\n # driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_elements_by_css_selector('a')[i+2].click()\n self.scroller(driver)\n\n if comm_left != 0 :\n\n if comm_page != 0 :\n\n self.page_swap(driver, comm_page - 1)\n # driver.find_element_by_class_name('review_section_review__1hTZD').find_element_by_class_name('pagination_pagination__2M9a4').find_elements_by_css_selector('a')[comm_page % 10].click()\n self.scroller(driver)\n\n\n self.comm_getter_2(driver, comm_left, wr)\n\n f.close()\n\n def comm_getter_2(self,driver,r,writer) :\n\n items = driver.find_element_by_class_name('reviewItems_list_review__1sgcJ').find_elements_by_css_selector('li')\n\n for prod in range(r):\n img_truck = []\n\n star = items[prod].find_element_by_class_name('reviewItems_average__16Ya-').text\n comm = items[prod].find_element_by_class_name('reviewItems_text__XIsTc').text\n if len(items[prod].find_element_by_class_name(\"reviewItems_review__1eF8A\").find_elements_by_css_selector('div')) == 2:\n img_ls = items[prod].find_element_by_class_name('reviewItems_review_thumb__CK7I2').find_elements_by_class_name(\n 'reviewItems_img_box__2zrNv')\n\n for img in img_ls:\n img_truck.append(img.find_element_by_tag_name('img').get_attribute('src'))\n\n writer.writerow([star,comm,img_truck.replace('[','')])\n\n\n\n\n\ndef setting() :\n\n cat_id = input(\"원하는 상품의 카테고리 ID를 입력해주세요. : \") # 원하는 상품의 카테고리 id를 입력받는다\n prod_quan = input(\"카테고리 내 후기를 긁고싶은 상품의 개수를 입력하세요. 모든 상품을 긁으시려면 all 입력. : \") # 후기를 긁고싶은 상품의 개수를 입력받는다. 입력한 값이 네이버에서 보유한 상품의 개수를 초과할 경우, 자동으로 그 상한에 맞춰진다.\n comm_quan = input(\"상품별로 얻고싶은 후기의 개수를 입력하세요. 모든 후기를 얻으시려면 all 입력. : \") # 상품별 긁을 후기의 개수를 설정한다.\n\n new_prod = Category(cat_id,prod_quan,comm_quan)\n\n return new_prod\n\n\nnew_prod = setting()\nnew_prod.check()\nnew_prod.max_prod_check()\nnew_prod.url_getter()\nnew_prod.comm_getter()","sub_path":".ipynb_checkpoints/comment_getter-checkpoint.py","file_name":"comment_getter-checkpoint.py","file_ext":"py","file_size_in_byte":8462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"188813764","text":"from market_maker import bitmex\nfrom market_maker.settings import settings\nfrom time import sleep\nimport os\nimport sys\nimport math\n# Helpers\n# help(bitmex.BitMEX)\nbitmex = bitmex.BitMEX(base_url = settings.BASE_URL,\n symbol = settings.SYMBOL,\n apiKey = settings.API_KEY,\n apiSecret = settings.API_SECRET,\n orderIDPrefix = settings.ORDERID_PREFIX,\n postOnly = settings.POST_ONLY,\n timeout = settings.TIMEOUT)\n\n# total position available\ndef print_ret():\n cur_px = bitmex.ticker_data()['last']\n pos_ret, neg_ret = 0, 0\n k = 2.0 ** (-1/5)\n while(True):\n sleep(60)\n cur_px, prev_px = bitmex.ticker_data()['last'], cur_px\n ret = (cur_px/prev_px - 1)\n if ret > 0:\n pos_ret = pos_ret * k + ret * (1 -k)\n elif ret < 0:\n neg_ret = neg_ret * k - ret * (1 -k) \n print('return: {}, neg_ret: {}, pos_ret: {}'.format(ret, pos_ret, neg_ret))\n\ndef _test():\n try:\n print_ret()\n except(KeyboardInterrupt, SystemExit):\n sys.exit()\n\nif __name__ == '__main__':\n _test()\n","sub_path":"vol_est.py","file_name":"vol_est.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"512066853","text":"# def get_sum(n):\r\n# if n == 0:\r\n# return 0\r\n# return get_sum(n - 1) + n\r\n\r\n# print(get_sum(10))\r\n\r\n# def fibonacci(n): # 递归法求第n个斐波那契数列\r\n# if n == 1 or n == 2:\r\n# return 1\r\n# return fibonacci(n - 2) + fibonacci(n - 1)\r\n\r\n# m = int(input('请输入一个正整数:'))\r\n# print(fibonacci(m))\r\n\r\n\r\ndef move(n, a, b, c): # 汉诺塔游戏\r\n if n == 1:\r\n print(a, '->', c)\r\n else:\r\n move(n - 1, a, c, b)\r\n print(a, '->', c)\r\n move(n - 1, b, a, c)\r\n \r\n\r\n\r\n# m = int(input('请输入一个正整数:'))\r\nmove(5, 'A', 'B', 'C')\r\n","sub_path":"递归.py","file_name":"递归.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"130676894","text":"from flask import Flask\nimport json\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n\treturn 'Hello, World from Flask'\n\n\n@app.route('/data')\ndef data():\n\tdata = [\n\t\t{ \"name\":\"edu\", \"age\":25 },\n\t\t{ \"name\":\"jobs\", \"age\": 56}\n\t]\n\treturn json.dumps(data)","sub_path":"app_rest.py","file_name":"app_rest.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"462543370","text":"from model.group import Group\nfrom model.contact import New_contact\nimport random\n\n\ndef test_add_contact_to_group(app, orm):\n if len(orm.get_group_list()) == 0:\n app.group.create(Group(name=\"testtesttest\"))\n if len(orm.get_contact_list()) == 0:\n app.group_new_contact.add_new_contact(\n New_contact(firstname=\"Alex\", middlename=\"fffefe\", lastname=\"wfawf\", nickname=\"fwwfett\", title=\"wfwfwer\",\n company=\"erreeg\",\n address=\"fwfawfaf fwfwaf fferwrr\", homephone=\"454655665\", mobilephone=\"89077777777\",\n workphone=\"5656565656\",\n fax=\"809876\",\n email=\"fesefsf@mail.ru\", email1=\"fwfwf@mail.ru\", email2=\"wfwfwfwfrer@gg.ru\",\n email3=\"fwghehjrlt@ruru\", address2=\"awwaagwg ffeef fefert\", secondary_phone=\"89066666666\",\n notes=\"awfawafwa fjfjhw fehgerrt\"))\n all_groups = orm.get_group_list()\n group = random.choice(all_groups)\n all_contacts = orm.get_contact_list()\n contact = random.choice(all_contacts)\n if contact in (orm.get_contacts_in_group(group)):\n app.contact.delete_contact_from_group(contact, group)\n app.group_new_contact.add_contact_to_group(contact, group)\n assert contact in orm.get_contacts_in_group(group)","sub_path":"test/test_add_contact_to_group.py","file_name":"test_add_contact_to_group.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"440109775","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\" This script is used to make wall posts in vk groups.\n In order to do it, you have to specify vk group id and vk api token.\n\n Notice that:\n\n 1. In -i argument image paths shall be separated by commas.\n 2. The syntax of -t argument is like \\d+[YMdhms]*, so generally\n it looks like 2016Y9M7d12h10m (any symbols rather than YMdhms will be dropped),\n but you don't need to type the full date. For example, 20h30m will grab\n your current date and change it's time to 20:30. If -i argument starts with \"+\"\n (as in \"-i +10m\"), timer will be set to your current date + specified time. \"\"\"\n\n\nimport re\nimport time\nimport argparse\nimport requests\nfrom datetime import datetime\n\n\ngid = 'int'\ntoken = 'str'\n\n\ndef log(text, end='\\n'):\n print(datetime.now().strftime('[%H:%M:%S] {}').format(text), end=end)\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-m', '--message', dest='message', action='store')\n parser.add_argument('-i', '--images', dest='images', action='store')\n parser.add_argument('-t', '--timer', dest='timer', action='store')\n parser.add_argument('-l', '--link', dest='link', action='store')\n\n return parser.parse_args()\n\n\nclass Post:\n def __init__(self):\n self.link = ''\n self.timer = ''\n self.message = ''\n self.attachments = []\n\n def upload_images(self, images):\n url = 'https://api.vk.com/method/photos.getWallUploadServer?'\n response = requests.post(url, {'access_token': token, 'gid': gid})\n upload_url = response.json()['response']['upload_url']\n\n for image_path in images.split(','):\n log('{}... '.format(image_path), end='')\n image = {'photo': (image_path, open(image_path, 'rb'))}\n response = requests.post(upload_url, files=image)\n upload_info = response.json()\n\n url = 'https://api.vk.com/method/photos.saveWallPhoto?'\n data = {'access_token': token, 'server': upload_info['server'],\n 'gid': gid, 'photo': upload_info['photo'], 'hash': upload_info['hash']}\n response = requests.post(url, data)\n\n self.attachments.append(response.json()['response'][0]['id'])\n log('done')\n\n def parse_timer(self, timer):\n timer = re.findall('(\\d+)([YMdhms])', timer)\n if not timer:\n log('Incorrect time')\n quit()\n\n if args.timer.startswith('+'):\n multiply = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'M': 2678400}\n post.timer = int(time.time())\n for pair in timer:\n self.timer += int(pair[0]) * multiply[pair[1]]\n else:\n # this is needed for compatibility with strftime syntax\n replace = {'s': 'S', 'm': 'M', 'h': 'H', 'd': 'd', 'M': 'm', 'Y': 'Y'}\n pattern = \"%Y-%m-%d %H:%M:%S\"\n\n for pair in timer:\n pattern = pattern.replace('%' + replace[pair[1]], pair[0])\n timer = datetime.now().strftime(pattern)\n\n dt_object = datetime.strptime(timer, \"%Y-%m-%d %H:%M:%S\")\n self.timer = int(time.mktime(dt_object.timetuple()))\n\n def perform(self):\n url = 'https://api.vk.com/method/wall.post?'\n data = {'access_token': token, 'owner_id': '-' + gid, 'publish_date': self.timer,\n 'attachments': ','.join(self.attachments), 'message': self.message}\n response = requests.post(url, data)\n post_id = response.json()['response']['post_id']\n\n return post_id\n\n\nif __name__ == '__main__':\n args = parse_args()\n post = Post()\n\n if args.images:\n log('Uploading images')\n post.upload_images(args.images)\n if args.message:\n post.message = args.message\n if args.link:\n post.attachments.append(args.link)\n if args.timer:\n args.timer = re.sub('\\s', '', args.timer)\n post.parse_timer(args.timer)\n\n post_id = post.perform()\n log(post_id)\n","sub_path":"post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"390491866","text":"#!/usr/bin/python3\n\n# email with attachments and smtplib example\n\nimport email\nimport smtplib\nimport sys\n\nfrom email.mime.text import MIMEText\n\n# email\nmsg = email.message.EmailMessage()\nmsg['Subject'] = 'my subject'\nmsg['From'] = 'email@my.domain'\nmsg['To'] = 'recipient@their.domain'\nmsg.attach(MIMEText('my message', 'plain'))\nwith open('/tmp/test.pdf', 'rb') as fd:\n pdf_data = fd.read()\n msg.add_attachment(pdf_data, maintype='application', subtype='pdf', filename='test.pdf')\nwith open('/tmp/test.txt', 'rb') as fd:\n txt_data = fd.read()\n msg.add_attachment(txt_data, maintype='text', subtype='plain', filename='test.txt')\n\n# smtplib\ntry:\n s = smtplib.SMTP('smtp.my.domain')\n s.send_message(msg)\n s.quit()\nexcept smtplib.SMTPException as e:\n print(e)\n sys.exit(1)\n","sub_path":"languages/python/module-email-smtplib.py","file_name":"module-email-smtplib.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"122295191","text":"# coding:utf-8\nimport re\nimport pymssql\ndbinfo = {\n \"server\": \"114.115.153.29\",\n \"user\": \"sa\",\n \"password\": \"qwe@58jzr\"\n}\nclass DbConnect():\n def __init__(self,db_cof,database):\n self.db_cof = db_cof\n # 数据库连接\n try:\n self.db = pymssql.connect(database=database,\n **db_cof)\n except Exception as a:\n print(\"数据库连接异常:%s\" % a)\n self.cursor = self.db.cursor()\n\n def select(self,sql):\n # SQL查询语句\n try:\n self.cursor.execute(sql)\n results = self.cursor.fetchall()\n except Exception as a:\n print(\"执行SQL查询语句出现异常:%s\" % a)\n return results\n\n def execute(self,sql):\n # SQL 删除、添加、修改语句\n try:\n self.cursor.execute(sql)\n self.db.commit()\n except Exception as a:\n self.db.rollback()\n print(\"执行SQL增改删出现异常:%s\" % a)\n\n def close(self):\n self.db.close()\n\ndef select_sql(select_sql):\n '''查询数据库'''\n db = DbConnect(dbinfo, database=\"JZRZP_V1_KF\")\n result = db.select(select_sql) #查询\n db.close()\n return result\n\ndef execute_sql(exe_sql):\n '''执行sql'''\n db = DbConnect(dbinfo, database=\"JZRZP_V1_KF\")\n db.execute(exe_sql)\n db.close()\n\ndef table_exists(m, table_name):\n '''判断表是否存在'''\n sql_table = \"show tables;\"\n m.execute(sql_table)\n tables = [m.cursor.fetchall()]\n table_list = re.findall('(\\'.*?\\')', str(tables))\n table_list = [re.sub(\"'\", '', each) for each in table_list]\n if table_name in table_list:\n return 1 # 存在返回1\n else:\n return 0 # 不存在返回0\n\nif __name__ == \"__main__\":\n db = DbConnect(dbinfo, database=\"JZRZP_V1_KF\")\n # # 判断是否存在表\n # table_name = 'linguser'\n # if (table_exists(db, table_name) != 1):\n # sql_create = \"create table linguser(id INT primary key NOT NULL AUTO_INCREMENT,username VARCHAR(32),password VARCHAR(32));\"\n # db.execute(sql_create)\n # else:\n # pass\n #\n # insert_sql = '''insert into linguser(`username`,`password`) values('lsird','s34sd');'''\n # db.execute(insert_sql) # 插入数据\n delete_sql = '''DELETE FROM [User] WHERE Phone = 18328015689'''\n execute_sql(delete_sql)\n # sel_sql = '''select * from [User];'''\n # result = db.select(sel_sql)\n # print(result)\n # db.close()\n\n# import pymysql\n# '''\n# pip install PyMySQL==0.9.3\n# '''\n#\n# dbinfo = {\n# \"host\": \"49.235.92.12\",\n# \"user\": \"root\",\n# \"password\": \"123456\",\n# \"port\": 3309}\n#\n#\n# class DbConnect():\n# def __init__(self, db_cof, database=\"\"):\n# self.db_cof = db_cof\n# # 打开数据库连接\n# self.db = pymysql.connect(database=database,\n# cursorclass=pymysql.cursors.DictCursor,\n# **db_cof)\n#\n# # 使用cursor()方法获取操作游标\n# self.cursor = self.db.cursor()\n#\n# def select(self, sql):\n# # SQL 查询语句\n# # sql = \"SELECT * FROM EMPLOYEE \\\n# # WHERE INCOME > %s\" % (1000)\n# self.cursor.execute(sql)\n# results = self.cursor.fetchall()\n# return results\n#\n# def execute(self, sql):\n# # SQL 删除、提交、修改语句\n# # sql = \"DELETE FROM EMPLOYEE WHERE AGE > %s\" % (20)\n# try:\n# # 执行SQL语句\n# self.cursor.execute(sql)\n# # 提交修改\n# self.db.commit()\n# except:\n# # 发生错误时回滚\n# self.db.rollback()\n#\n# def close(self):\n# # 关闭连接\n# self.db.close()\n#\n# def select_sql(select_sql):\n# '''查询数据库'''\n# db = DbConnect(dbinfo, database=\"apps\")\n# result = db.select(select_sql) # 查询\n# db.close()\n# return result\n#\n# def execute_sql(insert_sql):\n# '''执行sql'''\n# db = DbConnect(dbinfo, database=\"apps\")\n# db.execute(insert_sql) # 查询\n# db.close()\n#\n#\n# if __name__ == '__main__':\n# # db = DbConnect(db_cof=dbinfo, database=\"apps\")\n# # sql = 'SELECT * from auth_user WHERE username=\"test\";'\n# # result = db.select(select_sql)\n# # print(result[0][\"username\"])\n# sql = 'SELECT * from auth_user WHERE username=\"test\";'\n# a = select_sql(sql)\n# print(a)\n","sub_path":"common/connect_mysql.py","file_name":"connect_mysql.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"269507646","text":"import sys\n\n\nclass MetaExtractor():\n '''\n class which applies all feature extractors to an object\n '''\n\n def __init__(self, extractors):\n sys.stderr.write('This is MetaExtractor init\\n')\n self.extractors = extractors\n\n def get_features(self, context_obj):\n features = []\n for ext in self.extractors:\n features.extend(ext.get_features(context_obj))\n return features\n\n def get_feature_names(self):\n feature_names = []\n for ext in self.extractors:\n feature_names.extend(ext.get_feature_names())\n return feature_names\n","sub_path":"marmot/features/phrase/meta_extractor.py","file_name":"meta_extractor.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"389264307","text":"#!/usr/bin/env python\n\n\"\"\"Find files that have not been ingested and link them to incoming\"\"\"\n\nimport argparse\nimport os.path\nimport posixpath\nimport re\nimport sys\n\nimport dbprocessing.DButils\nimport dbprocessing.DBstrings\n\n\ndef parse_args(argv=None):\n \"\"\"Parse arguments for this script\n\n Parameters\n ----------\n argv : list\n Argument list, default from sys.argv\n\n Returns\n -------\n kwargs : dict\n Keyword arguments for :func:`main`.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--mission\", required=True,\n help=\"selected mission database\")\n parser.add_argument(\"-p\", \"--product\", action='append', dest=\"products\",\n help=\"Product name or ID to check; specify multiple\"\n \" times for multiple products (default: all).\")\n options = parser.parse_args(argv)\n return vars(options)\n\n\ndef list_files(dbu, product):\n \"\"\"List all files on disk matching a product\n\n Parameters\n ----------\n dbu : dbprocess.DButils.DButils\n Open mission database\n\n product : int or str\n Product name or ID\n\n Returns\n -------\n list\n Path to all matching files relative to mission directory.\n \"\"\"\n prod = dbu.getEntry('Product', product)\n tb = dbu.getTraceback('Product', prod.product_id)\n kwargs = {'INSTRUMENT': tb['instrument'].instrument_name,\n 'MISSION': tb['mission'].mission_name,\n 'PRODUCT': prod.product_name,\n 'SATELLITE': tb['satellite'].satellite_name,\n 'SPACECRAFT': tb['satellite'].satellite_name,\n }\n fmtr = dbprocessing.DBstrings.DBformatter()\n pat = fmtr.re(prod.format, **kwargs)\n proddir = fmtr.re(prod.relative_path, **kwargs)\n md = os.path.normpath(dbu.getMissionDirectory())\n # Because in general the relative path may include wildcards,\n # we have to go through everything. It would be a nice improvement\n # to find the static parts of the relative path and only hit that...\n # spacepy.datamanager would do that for us.\n pat = posixpath.normpath(posixpath.join(proddir, pat))\n if os.path.sep == '\\\\': # Path-separator and regex escape are ambiguous.\n # This path is well-formatted (from normpath); can be handled naively.\n pat = '\\\\\\\\'.join(pat.split(posixpath.sep))\n flist = (os.path.join(dn, f)[len(md) + 1:]\n for dn, _, fnames in os.walk(md) for f in fnames)\n flist = [f for f in flist if re.match(pat, f)]\n return flist\n\n\ndef indb(dbu, fname, prod):\n \"\"\"Checks if a filename is in database\n\n Parameters\n ----------\n\n dbu : dbprocess.DButils.DButils\n Open mission database\n\n fname : str\n Filename (no pathing)\n\n product : int\n Product ID\n\n Returns\n -------\n bool\n True if file with that name and product are present.\n \"\"\"\n return bool(dbu.session.query(dbu.File)\n .filter_by(product_id=prod, filename=fname).count())\n\n\ndef main(mission, products=None):\n \"\"\"Check for files not in database\n\n Find all files that match a product specification but are not in the\n database and symlink them to incoming.\n\n Parameters\n ----------\n mission : str\n Path to the mission file\n\n products : list\n Product names or IDs to check; default all\n \"\"\"\n dbu = dbprocessing.DButils.DButils(mission)\n md = os.path.normpath(dbu.getMissionDirectory())\n plist = dbu.getAllProducts() if products is None \\\n else [dbu.getEntry('Product', p) for p in products]\n inc = dbu.getIncomingPath()\n for prod in plist:\n flist = list_files(dbu, prod.product_id)\n missing = [f for f in flist\n if not indb(dbu, os.path.basename(f), prod.product_id)]\n for m in missing:\n os.symlink(os.path.join(md, m),\n os.path.join(inc, os.path.basename(m)))\n\n\nif __name__ == \"__main__\":\n main(**parse_args())\n\n","sub_path":"scripts/linkUningested.py","file_name":"linkUningested.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"311088975","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# A Simple way to send a message to telegram\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler\nfrom telegram import MessageEntity, TelegramObject, ChatAction\nfrom pprint import pprint\nfrom functools import wraps\nfrom future.builtins import bytes\nfrom pymongo import MongoClient\nfrom pathlib import Path\nimport numpy as np\nimport argparse\nimport logging\nimport telegram\nimport sys\nimport json\nimport random\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport re\nimport os\nimport sys\nimport yaml\nfrom PIL import Image\n\n# For plotting messages / price charts\nimport pandas as pd\n\nimport requests\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle, Patch\nfrom matplotlib.finance import candlestick_ohlc\n\nimport talib as ta\n\nfrom urllib.parse import quote_plus\n\nPATH = os.path.dirname(os.path.abspath(__file__))\n\n\"\"\"\n# Configure Logging\n\"\"\"\nFORMAT = '%(asctime)s -- %(levelname)s -- %(module)s %(lineno)d -- %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT)\nlogger = logging.getLogger('root')\nlogger.info(\"Running \"+sys.argv[0])\n\n\"\"\"\n#\tLoad the config file\n#\tSet the Botname / Token\n\"\"\"\nconfig_file = \"%s/config.yaml\" % (PATH)\nmy_file = Path(config_file)\n\nif my_file.is_file():\n\twith open(config_file) as fp:\n\t config = yaml.load(fp)\nelse:\n\tpprint('config.yaml file does not exists. Please make from config.sample.yaml file')\n\tsys.exit()\n\n\"\"\"\n# Mongodb\n\"\"\"\nclient = MongoClient(\n\tusername=config['MDB_USER'],\n\tpassword=config['MDB_PW'],\n\thost=(\"mongodb://%s:%d/%s?authSource=%s\" % (\n\t\tconfig['MDB_HOST'], config['MDB_PORT'], config['MDB_DB'], config['MDB_DB']\n\t))\n)\n\ndb = client.bfx_mod_bot\n\nBOTNAME = config['NATALIA_BOT_USERNAME']\nTELEGRAM_BOT_TOKEN = config['NATALIA_BOT_TOKEN']\nFORWARD_PRIVATE_MESSAGES_TO = config['BOT_OWNER_ID']\nADMINS = config['ADMINS']\n\nAFFILIATE_LINK_DETECTOR = r\"\"+config['AFFILIATE_LINK_DETECTOR']\n\nMESSAGES = {}\nMESSAGES['welcome'] = config['MESSAGES']['welcome']\nMESSAGES['goodbye'] = config['MESSAGES']['goodbye']\nMESSAGES['pmme'] = config['MESSAGES']['pmme']\nMESSAGES['start'] = config['MESSAGES']['start']\nMESSAGES['admin_start'] = config['MESSAGES']['admin_start']\nMESSAGES['rules'] = config['MESSAGES']['rules']\nMESSAGES['affiliate_link_warning'] = config['MESSAGES']['affiliate_link_warning']\nMESSAGES['new_user_mute_notice'] = config['MESSAGES']['new_user_mute_notice']\nMESSAGES['affiliate_link_mute_notice'] = config['MESSAGES']['affiliate_link_mute_notice']\n\nADMINS_JSON = config['MESSAGES']['admins_json']\nADMIN_ID = config['ADMIN_ID']\n\nMUTE_PERIOD_H = config['MUTE_PERIOD_HOURS']\n\n# Rooms\nBITFINEX_CHAT_ID = config['BITFINEX_CHAT_ID']\n\nROOM_ID_TO_NAME = {\n\tBITFINEX_CHAT_ID: config['BITFINEX_CHAT_NAME'],\n}\n\n# Rooms where chat/gifs/etc is logged for stats etc\nLOG_ROOMS = [BITFINEX_CHAT_ID]\n\n# Storing last 'welcome' message ids\nPRIOR_WELCOME_MESSAGE_ID = {\n\tBITFINEX_CHAT_ID: 0\n}\n\n# Storing last 'removal' of uncompress images, message ids\nLASTUNCOMPRESSED_IMAGES = {\n\tBITFINEX_CHAT_ID: 0\n}\n\n#################################\n# Begin bot..\nbot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)\n\n# Bot error handler\ndef error(bot, update, error):\n logger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n# Restrict bot functions to admins\ndef restricted(func):\n @wraps(func)\n def wrapped(bot, update, *args, **kwargs):\n user_id = update.effective_user.id\n if user_id not in ADMINS:\n print(\"Unauthorized access denied for {}.\".format(user_id))\n return\n return func(bot, update, *args, **kwargs)\n return wrapped\n\n#################################\n#\t\t\tUTILS\n\n# Resolve message data to a readable name\ndef get_name(update):\n\t\ttry:\n\t\t\t\tname = update.message.from_user.first_name\n\t\texcept (NameError, AttributeError):\n\t\t\t\ttry:\n\t\t\t\t\t\tname = update.message.from_user.username\n\t\t\t\texcept (NameError, AttributeError):\n\t\t\t\t\t\tlogger.info(\"No username or first name.. wtf\")\n\t\t\t\t\t\treturn\t\"\"\n\t\treturn name\n\n#################################\n#\t\tBEGIN BOT COMMANDS\n\n# Returns the user their user id\ndef getid(bot, update):\n\tpprint(update.message.chat.__dict__, indent=4)\n\tupdate.message.reply_text(str(update.message.chat.title)+\" :: \"+str(update.message.chat.id))\n\n# Welcome message\ndef start(bot, update):\n\tuser_id = update.message.from_user.id\n\tchat_id = update.message.chat.id\n\tmessage_id = update.message.message_id\n\tuser_id = update.message.from_user.id\n\tname = get_name(update)\n\n\tlogger.info(\"/start - \"+name)\n\tlogger.info(chat_id)\n\n\tpprint(update.message.chat.type)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1)\n\telse:\n\t\tmsg = MESSAGES['rules']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'start', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tmsg = bot.sendMessage(chat_id=chat_id, text=(MESSAGES['start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\t\tif user_id in ADMINS:\n\t\t\tmsg = bot.sendMessage(chat_id=chat_id, text=(MESSAGES['admin_start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\ndef rules(bot, update):\n\tuser_id = update.message.from_user.id\n\tchat_id = update.message.chat.id\n\tmessage_id = update.message.message_id\n\tname = get_name(update)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1)\n\telse:\n\t\tmsg = MESSAGES['rules']\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'rules', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=chat_id,text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1)\n\ndef admins(bot, update):\n\n\tuser_id = update.message.from_user.id\n\tchat_id = update.message.chat.id\n\tmessage_id = update.message.message_id\n\tname = get_name(update)\n\n\tif (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):\n\t\tmsg = random.choice(MESSAGES['pmme']) % (name)\n\t\tbot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode=\"Markdown\",disable_web_page_preview=1)\n\telse:\n\t\tmsg = \"*Bitfinex TG Admins*\\n\\n\"\n\t\tkeys = list(ADMINS_JSON.keys())\n\t\trandom.shuffle(keys)\n\t\tfor k in keys:\n\t\t\tmsg += \"\"+k+\"\\n\"\n\t\tmsg += \"\\n/start - to go back to home\"\n\n\t\ttimestamp = datetime.datetime.utcnow()\n\t\tinfo = { 'user_id': user_id, 'request': 'admins', 'timestamp': timestamp }\n\t\tdb.pm_requests.insert(info)\n\n\t\tbot.sendMessage(chat_id=chat_id,text=msg,parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n####################################################\n# ADMIN FUNCTIONS\n@restricted\ndef commandstats(bot, update):\n\tchat_id = update.message.chat_id\n\tstart = datetime.datetime.today().replace(day=1,hour=0,minute=0,second=0)\n\t# start = start - relativedelta(days=30)\n\n\tpipe = [\n\t\t{ \"$match\": { 'timestamp': {'$gt': start } } },\n\t\t{ \"$group\": {\n\t\t\t\"_id\": {\n\t\t\t\t\"year\" : { \"$year\" : \"$timestamp\" },\n\t\t\t\t\"month\" : { \"$month\" : \"$timestamp\" },\n\t\t\t\t\"day\" : { \"$dayOfMonth\" : \"$timestamp\" },\n\t\t\t\t\"request\": \"$request\"\n\t\t\t},\n\t\t\t\"total\": { \"$sum\": 1 }\n\t\t\t}\n\t\t},\n\t\t{ \"$sort\": { \"total\": -1 } },\n\t\t# { \"$limit\": 3 }\n\t]\n\tres = list(db.pm_requests.aggregate(pipe))\n\n\toutput = {}\n\ttotals = {}\n\n\tfor r in res:\n\n\t\tkey = r['_id']['day']\n\t\tif not(key in output):\n\t\t\toutput[key] = {}\n\n\t\trequest = r['_id']['request']\n\t\tif not(request in output[key]):\n\t\t\toutput[key][r['_id']['request']] = 0\n\n\t\tif not(request in totals):\n\t\t\ttotals[request] = 0\n\n\t\toutput[key][r['_id']['request']] += r['total']\n\t\ttotals[request] += r['total']\n\n\n\treply = \"*Natalia requests since the start of the month...*\\n\"\n\tfor day in sorted(output.keys()):\n\t\treply += \"--------------------\\n\"\n\t\treply += \"*\"+str(day)+\"*\\n\"\n\n\t\tfor request, count in output[day].items():\n\t\t\treply += request+\" - \"+str(count)+\"\\n\"\n\n\n\treply += \"--------------------\\n\"\n\treply += \"*Totals*\\n\"\n\tfor request in totals:\n\t\treply += request+\" - \"+str(totals[request])+\"\\n\"\n\n\n\tbot.sendMessage(chat_id=chat_id, text=reply, parse_mode=\"Markdown\" )\n\n#################################\n#\t\tBOT EVENT HANDLING\ndef new_chat_member(bot, update):\n\t\"\"\" Welcomes new chat member \"\"\"\n\n\tlogger.info(update)\n\n\tmember = update.message.new_chat_members[0]\n\tuser_id = member.id\n\tmessage_id = update.message.message_id\n\tchat_id = update.message.chat.id\n\tname = member.first_name\n\n\tlogger.info(chat_id)\n\n\tif (chat_id != BITFINEX_CHAT_ID):\n\t\treturn\n\n\t# Check user has a profile pic..\n\t# TODO: Extract\n\ttimestamp = datetime.datetime.utcnow()\n\tinfo = { 'user_id': user_id, 'chat_id': chat_id, 'timestamp': timestamp }\n\tdb.room_joins.insert(info)\n\n\t# try:\n\t# \tif PRIOR_WELCOME_MESSAGE_ID[chat_id] > 0:\n\t# \t\tbot.delete_message(chat_id=chat_id, message_id=PRIOR_WELCOME_MESSAGE_ID[chat_id])\n\t# except:\n\t# \tpass\n\n\t# logger.info(\"welcoming new user - %s\" % (name))\n\n\t# message = bot.sendMessage(\n\t# \tchat_id=chat_id,\n\t# \ttext=MESSAGES['welcome'] % (name),\n\t# \tparse_mode='Markdown'\n\t# )\n\n\t# PRIOR_WELCOME_MESSAGE_ID[chat_id] = int(message.message_id)\n\n\tdb.users.insert({\n\t\t'user_id': user_id,\n\t\t'timestamp': timestamp\n\t})\n\n\tbot.restrict_chat_member(\n\t\tchat_id,\n\t\tuser_id,\n\t\tuntil_date=(datetime.datetime.now() + relativedelta(hours=MUTE_PERIOD_H)),\n\t\tcan_send_messages=False,\n\t\tcan_send_media_messages=False,\n\t\tcan_send_other_messages=False,\n\t\tcan_add_web_page_previews=False\n\t)\n\n# Disabled\ndef left_chat_member(bot, update):\n\tlogger.info(update)\n\n\tname = get_name(update)\n\tmessage = update.message\n\tlogger.info(message.left_chat_member.first_name+' left chat '+message.chat.title)\n\tname = get_name(update)\n\n\tbot.sendMessage(\n\t\tchat_id=update.message.chat.id,\n\t\treply_to_message_id=message.message_id,\n\t\ttext=random.choice(MESSAGES['goodbye']),\n\t\tparse_mode=\"Markdown\",\n\t\tdisable_web_page_preview=1\n\t)\n\n# Just log/handle a normal message\ndef log_message_private(bot, update):\n\tusername = update.message.from_user.username\n\tuser_id = update.message.from_user.id\n\tmessage_id = update.message.message_id\n\tchat_id = update.message.chat.id\n\tname = get_name(update)\n\n\tlogger.info(\"Private Log Message: \"+name+\" said: \"+update.message.text)\n\n\tmsg = bot.forwardMessage(chat_id=FORWARD_PRIVATE_MESSAGES_TO, from_chat_id=chat_id, message_id=message_id)\n\n\tmsg = bot.sendMessage(chat_id=chat_id, text=(MESSAGES['start'] % name),parse_mode=\"Markdown\",disable_web_page_preview=1)\n\n\n# Just log/handle a normal message\ndef echo(bot, update):\n\tusername = update.message.from_user.username\n\tuser_id = update.message.from_user.id\n\tmessage_id = update.message.message_id\n\tchat_id = update.message.chat.id\n\n\tif username == None:\n\t\treturn\n\n\tmessage = username+': '+update.message.text\n\tpprint(str(chat_id)+\" - \"+str(message))\n\n\tname = get_name(update)\n\ttimestamp = datetime.datetime.utcnow()\n\n\tinfo = { 'user_id': user_id, 'chat_id': chat_id, 'message_id':message_id, 'message': message, 'timestamp': timestamp }\n\tdb.natalia_textmessages.insert(info)\n\n\tinfo = { 'user_id': user_id, 'name': name, 'username': username, 'last_seen': timestamp }\n\tdb.users.update_one( { 'user_id': user_id }, { \"$set\": info }, upsert=True)\n\ndef on_delete_message(bot, update):\n\tmessage_id = update.message.message_id\n\tchat_id = update.message.chat.id\n\n\tbot.delete_message(chat_id=chat_id, message_id=message_id)\n\ndef on_link_message(bot, update):\n\tuser_id = update.message.from_user.id\n\tmessage_id = update.message.message_id\n\tchat_id = update.message.chat.id\n\tname = get_name(update)\n\tfind_aff_link = re.findall(AFFILIATE_LINK_DETECTOR, update.message.text)\n\n\tif (len(find_aff_link) == 0):\n\t\treturn\n\n\treply = MESSAGES['affiliate_link_warning']\n\n\tbot.sendMessage(\n\t\tchat_id=ADMIN_ID,\n\t\ttext=(\"%s posted an affiliate link\" % (name)),\n\t\tparse_mode=\"Markdown\",\n\t\tdisable_web_page_preview=1\n\t)\n\n\t# Replace message\n\tbot.delete_message(chat_id=chat_id, message_id=message_id)\n\tbot.sendMessage(\n\t\tchat_id=chat_id,\n\t\ttext=(reply % (name)),\n\t\tparse_mode=\"Markdown\",\n\t\tdisable_web_page_preview=1\n\t)\n\n\t# Silence bad actor\n\tbot.restrict_chat_member(\n\t\tchat_id,\n\t\tuser_id,\n\t\tuntil_date=(datetime.datetime.now() + relativedelta(hours=MUTE_PERIOD_H)),\n\t\tcan_send_messages=False,\n\t\tcan_send_media_messages=False,\n\t\tcan_send_other_messages=False,\n\t\tcan_add_web_page_previews=False\n\t)\n\n#################################\n# Command Handlers\nupdater = Updater(bot=bot,workers=10)\ndp = updater.dispatcher\n\n# Commands\ndp.add_handler(CommandHandler('id', getid))\ndp.add_handler(CommandHandler('start', start))\ndp.add_handler(CommandHandler('rules', rules))\ndp.add_handler(CommandHandler('admins', admins))\ndp.add_handler(CommandHandler('commandstats',commandstats))\ndp.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_chat_member))\ndp.add_handler(MessageHandler(Filters.status_update.left_chat_member, left_chat_member))\ndp.add_handler(MessageHandler(Filters.entity(MessageEntity.URL), on_link_message))\ndp.add_handler(MessageHandler(Filters.private, log_message_private))\ndp.add_handler(MessageHandler(Filters.text, echo))\ndp.add_handler(MessageHandler(Filters.photo, on_delete_message))\ndp.add_handler(MessageHandler(Filters.sticker, on_delete_message))\ndp.add_handler(MessageHandler(Filters.video, on_delete_message))\ndp.add_handler(MessageHandler(Filters.document, on_delete_message))\ndp.add_error_handler(error)\n\n#################################\n# Polling\nupdater.start_polling()\n","sub_path":"natalia.py","file_name":"natalia.py","file_ext":"py","file_size_in_byte":13855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"142572383","text":"# -*- coding: utf-8 -*-\nfrom InstagramAPI import InstagramAPI\nfrom bottle import request, response\nfrom bottle import get, put, post, delete\n\n@get('/external/instagram/feed')\ndef get_instagram_feed():\n\t# api = InstagramAPI(\"Idea10oficial\", \"print102030\")\n\tapi = InstagramAPI(\"idea10tambore\", \"Print102030\")\n\tif (api.login()):\n\t\tapi.getSelfUserFeed()\n\t\treturn api.LastJson\n\telse:\n\t\tresponse.status = 500\n\t\treturn \"Não foi possível efetuar o login, usuário e/ou senha inválidos.\"","sub_path":"controller/business/external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"202730709","text":"import os\nimport sys\nimport shutil\n\n# local imports\nfrom utils import apply_preproc, load_preproc, load_glm_params\n\n# parent dir imports\nsys.path.append('..')\n\nfrom nipy_glm_utils import apply_glm\nfrom datasets_extras import fetch_openfmri\n\nFULL_ID = 'ds000105'\nSHORT_ID = 'ds105'\nNAME = 'Visual object recognition'\nDESCRIPTION = \"\"\"\nNeural responses, as reflected in hemodynamic changes, were measured in\nsix subjects (five female and one male) with gradient echo echoplanar\nimaging on a GE 3T scanner (General Electric, Milwaukee, WI) [repetition\ntime (TR) = 2500 ms, 40 3.5-mm-thick sagittal images, field of view\n(FOV) = 24 cm, echo time (TE) = 30 ms, flip angle = 90] while they\nperformed a one-back repetition detection task. High-resolution\nT1-weighted spoiled gradient recall (SPGR) images were obtained for\neach subject to provide detailed anatomy (124 1.2-mm-thick sagittal\nimages, FOV = 24 cm). Stimuli were gray-scale images of faces,\nhouses, cats, bottles, scissors, shoes, chairs, and nonsense\npatterns. The categories were chosen so that all stimuli from a\ngiven category would have the same base level name. The specific\ncategories were selected to allow comparison with our previous\nstudies (faces, houses, chairs, animals, and tools) or ongoing\nstudies (shoes and bottles). Control nonsense patterns were\nphase-scrambled images of the intact objects. Twelve time series\nwere obtained in each subject. Each time series began and ended\nwith 12 s of rest and contained eight stimulus blocks of 24-s\nduration, one for each category, separated by 12-s intervals of\nrest. Stimuli were presented for 500 ms with an interstimulus\ninterval of 1500 ms. Repetitions of meaningful stimuli were pictures\nof the same face or object photographed from different angles. Stimuli\nfor each meaningful category were four images each of 12 different exemplars.\n\nGet full description <a href=\"https://openfmri.org/dataset/ds000105\">\\\nhere</a>.\\\n\"\"\"\n\nMODEL_ID = 'model001'\n\nignore_list = []\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 4:\n print (\"Usage: python %s <data_root_dir> \"\n \"<preproc_root_dir> <glm_root_dir>\" % sys.argv[0])\n print (\"Example:\\r\\npython %s ~/datasets/raw\"\n \" ~/datasets/preproc ~/datasets/glm\") % sys.argv[0]\n sys.exit(1)\n\n root_dir, preproc_dir, glm_dir = sys.argv[1:]\n\n # download data\n data_dir = fetch_openfmri(FULL_ID, root_dir)\n\n # alternative task_contrasts\n contrasts_file = '%s_task_contrasts.txt' % SHORT_ID\n assert os.path.isfile(contrasts_file), \\\n \"No contrasts file: %s\" % contrasts_file\n dest = os.path.join(data_dir, SHORT_ID,\n 'models', MODEL_ID, 'task_contrasts.txt')\n\n shutil.copy(contrasts_file, dest)\n\n # apply SPM preprocessing\n apply_preproc(SHORT_ID, data_dir, preproc_dir, ignore_list,\n dataset_description=DESCRIPTION)\n\n # prepare GLM (get data and design)\n preproc_data, motion_params = load_preproc(SHORT_ID, preproc_dir)\n\n glm_params = load_glm_params(SHORT_ID, data_dir, MODEL_ID,\n subject_ids=preproc_data.keys(),\n motion_params=motion_params)\n\n apply_glm(SHORT_ID, glm_dir, preproc_data,\n glm_params, resample=True, n_jobs=-1)\n","sub_path":"openfmri/ds105.py","file_name":"ds105.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"442141364","text":"# coding: utf-8\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom main.models import (UserProfile, Contact, Product, Brand, ChargeBasic, ChargeDAC,\n ChargeBasicFixed, ChargeDemand, ChargePeak, Kit, Panel, Investor, Wire, Fuse, ImportedPrice,\n Neighborhood, Tariff, Quote, ProductPrice)\n\nfrom django.contrib.localflavor.mx.forms import MXRFCField\nfrom django.contrib.auth import login, get_backends\n\ndefault_error_messages = {\n 'invalid': 'Intruduce un RFC válido',\n 'invalid_checksum': 'Digito verificador inválido.',\n}\n\nMXRFCField.default_error_messages = default_error_messages\n\nclass ChangeQuoteStatusForm(forms.ModelForm):\n '''\n Form to change quote status\n '''\n\n class Meta:\n model = Quote\n fields = ('status',)\n\nclass ProfileForm(forms.ModelForm):\n '''\n Form to add a profile\n '''\n def __init__(self, *args, **kwargs):\n super(ProfileForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = UserProfile\n exclude = ('user', 'zipcode', 'state', 'municipality', 'neighborhood')\n widgets = {\n 'terms_and_conditions': forms.Textarea(attrs={'cols': 80, 'rows': 3}),\n }\n zipcode = forms.IntegerField(min_value=0, max_value=99999, label=\"Código Postal\")\n rfc = MXRFCField()\n\n def clean(self):\n '''\n Check if the zipcode exists\n '''\n cleaned_data = super(ProfileForm, self).clean()\n requested_zipcode = cleaned_data.get(\"zipcode\")\n zipcode_exist = Neighborhood.objects.filter(zipcode=requested_zipcode)\n if not zipcode_exist:\n self._errors[\"zipcode\"] = self.error_class(['No existe este Código Postal'])\n\n if self._errors:\n self.data['zipcode'] = ''\n\n return cleaned_data\n\nclass DistributorProfileForm(forms.ModelForm):\n '''\n Form to add a profile\n '''\n def __init__(self, *args, **kwargs):\n super(DistributorProfileForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = UserProfile\n exclude = ('user', 'zipcode', 'state', 'municipality', 'neighborhood')\n widgets = {\n 'terms_and_conditions': forms.Textarea(attrs={'cols': 80, 'rows': 3}),\n }\n zipcode = forms.IntegerField(min_value=0, max_value=99999, label=\"Código Postal\")\n rfc = MXRFCField()\n\n def clean(self):\n '''\n Check if the zipcode exists\n '''\n cleaned_data = super(ProfileForm, self).clean()\n requested_zipcode = cleaned_data.get(\"zipcode\")\n zipcode_exist = Neighborhood.objects.filter(zipcode=requested_zipcode)\n if not zipcode_exist:\n self._errors[\"zipcode\"] = self.error_class(['No existe este Código Postal'])\n\n if self._errors:\n self.data['zipcode'] = ''\n\n return cleaned_data\n\nclass ContactForm(forms.ModelForm):\n '''\n Form to add a contact\n '''\n def __init__(self, *args, **kwargs):\n super(ContactForm, self).__init__(*args, **kwargs)\n self.fields['rfc'].required = False\n self.fields['country'].initial = 'México'\n self.fields['country'].widget.attrs['readonly'] = True\n\n class Meta:\n model = Contact\n exclude = ('active', 'owner', 'zipcode', 'state', 'municipality', 'neighborhood', 'is_express')\n widgets = {\n 'notes': forms.Textarea(attrs={'cols': 80, 'rows': 2}),\n }\n zipcode = forms.IntegerField(min_value=0, max_value=99999, label=\"Código Postal\")\n rfc = MXRFCField()\n\n def clean(self):\n '''\n Check if the zipcode exists\n '''\n cleaned_data = super(ContactForm, self).clean()\n requested_zipcode = cleaned_data.get(\"zipcode\")\n zipcode_exist = Neighborhood.objects.filter(zipcode=requested_zipcode)\n if not zipcode_exist:\n self._errors[\"zipcode\"] = self.error_class(['No existe este Código Postal'])\n\n return cleaned_data\n\nclass ReassignContactForm(forms.ModelForm):\n '''\n Form to reassign a contact\n '''\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop(\"request\")\n super(ReassignContactForm, self).__init__(*args, **kwargs)\n profiles = UserProfile.objects.filter(\n user__groups__name='salesman',\n user__belongs_to__distributor=self.request.user\n )\n self.fields['owner'].queryset = profiles\n\n\n class Meta:\n model = Contact\n fields = ('owner',)\n\nclass ProductForm(forms.ModelForm):\n '''\n Form to add a product\n '''\n def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs)\n self.fields['brand'].queryset = Brand.objects.filter(active=True)\n\n class Meta:\n model = Product\n exclude = ('active', 'is_imported', 'cost', 'margin_whole_saler',\n 'price_whole_saler', 'margin_retailer', 'price_retailer', 'margin_suggested',\n 'price'\n )\n widgets = {\n 'description': forms.Textarea(attrs={'cols': 80, 'rows': 2}),\n }\n\n \"\"\"\n def clean(self):\n cleaned_data = super(ProductForm, self).clean()\n margin_whole_saler = cleaned_data.get(\"margin_whole_saler\")\n margin_retailer = cleaned_data.get(\"margin_retailer\")\n margin_suggested = cleaned_data.get(\"margin_suggested\")\n msg = \"El valor debe ser entre 0 y 100\"\n\n if (margin_whole_saler is not None and\n not (margin_whole_saler >= 0 and margin_whole_saler <= 100)):\n self._errors[\"margin_whole_saler\"] = self.error_class([msg])\n del cleaned_data[\"margin_whole_saler\"]\n if (margin_retailer is not None and\n not (margin_retailer >= 0 and margin_retailer <= 100)):\n self._errors[\"margin_retailer\"] = self.error_class([msg])\n del cleaned_data[\"margin_retailer\"]\n if (margin_suggested is not None and\n not (margin_suggested >= 0 and margin_suggested <= 100)):\n self._errors[\"margin_suggested\"] = self.error_class([msg])\n del cleaned_data[\"margin_suggested\"]\n\n return cleaned_data\n\n def save(self, commit=True):\n instance = super(ProductForm, self).save(commit=False)\n instance.price_whole_saler = round(instance.cost / (1 - (self.cleaned_data['margin_whole_saler'] / 100)), 2)\n instance.price_retailer = round(instance.price_whole_saler / (1 - (self.cleaned_data['margin_retailer'] / 100)), 2)\n instance.price_suggested = round(instance.price_retailer / (1 - (self.cleaned_data['margin_suggested'] / 100)), 2)\n if commit:\n instance.save()\n return instance\n \"\"\"\n\nclass AssignPriceProductForm(forms.ModelForm):\n '''\n Form to add a product\n '''\n def __init__(self, *args, **kwargs):\n super(AssignPriceProductForm, self).__init__(*args, **kwargs)\n self.fields['name'].widget.attrs['readonly'] = True\n self.fields['model'].widget.attrs['readonly'] = True\n self.fields['sku'].widget.attrs['readonly'] = True\n self.fields['description'].widget.attrs['readonly'] = True\n self.fields['currency'].widget.attrs['disabled'] = \"disabled\"\n self.fields['uom'].widget.attrs['disabled'] = \"disabled\"\n self.fields['brand'].widget.attrs['disabled'] = \"disabled\"\n self.fields['price_suggested'].widget.attrs['readonly'] = True\n\n class Meta:\n model = Product\n fields = ('name', 'model', 'sku', 'description', 'currency', 'uom', 'brand', 'price_suggested')\n widgets = {\n 'description': forms.Textarea(attrs={'cols': 80, 'rows': 2}),\n }\n\nclass ProductPriceForm(forms.ModelForm):\n '''\n Form to add a product price\n '''\n def __init__(self, *args, **kwargs):\n super(ProductPriceForm, self).__init__(*args, **kwargs)\n self.fields['cost'].widget.attrs['readonly'] = True\n self.fields['margin'].widget.attrs['readonly'] = True\n\n class Meta:\n model = ProductPrice\n exclude = ('product', 'distributor')\n\nclass EditProductForm(forms.ModelForm):\n '''\n Form to add a product\n '''\n def __init__(self, *args, **kwargs):\n super(EditProductForm, self).__init__(*args, **kwargs)\n self.fields['brand'].queryset = Brand.objects.filter(active=True)\n\n class Meta:\n model = Product\n exclude = ('active', 'product_type')\n widgets = {\n 'description': forms.Textarea(attrs={'cols': 80, 'rows': 2}),\n }\n\n def clean(self):\n cleaned_data = super(EditProductForm, self).clean()\n percent_import_taxes = cleaned_data.get(\"percent_import_taxes\")\n return cleaned_data\n\nclass ImportedPriceForm(forms.ModelForm):\n '''\n Form to add a imported price\n '''\n def __init__(self, *args, **kwargs):\n super(ImportedPriceForm, self).__init__(*args, **kwargs)\n self.fields['cost_import'].widget.attrs['readonly'] = True\n self.fields['cost_landed'].widget.attrs['readonly'] = True\n\n class Meta:\n model = ImportedPrice\n exclude = ('product',)\n\n def clean(self):\n cleaned_data = super(ImportedPriceForm, self).clean()\n percent_import_taxes = cleaned_data.get(\"percent_import_taxes\")\n percent_freight = cleaned_data.get(\"percent_freight\")\n msg = \"El valor debe ser entre 0 y 100\"\n\n if (percent_import_taxes is not None and\n not (percent_import_taxes >= 0 and percent_import_taxes <= 100)):\n self._errors[\"percent_import_taxes\"] = self.error_class([msg])\n del cleaned_data[\"percent_import_taxes\"]\n if (percent_freight is not None and\n not (percent_freight >= 0 and percent_freight <= 100)):\n self._errors[\"percent_freight\"] = self.error_class([msg])\n del cleaned_data[\"percent_freight\"]\n\n return cleaned_data\n\n\nclass PanelForm(forms.ModelForm):\n '''\n Form to add a panel\n '''\n def __init__(self, *args, **kwargs):\n super(PanelForm, self).__init__(*args, **kwargs)\n self.fields['panel_watt_price'].widget.attrs['readonly'] = True\n\n class Meta:\n model = Panel\n exclude = ('product')\n\nclass InvestorForm(forms.ModelForm):\n '''\n Form to add a investor\n '''\n def __init__(self, *args, **kwargs):\n super(InvestorForm, self).__init__(*args, **kwargs)\n self.fields['investor_watt_price'].widget.attrs['readonly'] = True\n\n class Meta:\n model = Investor\n exclude = ('product')\n\nclass WireForm(forms.ModelForm):\n '''\n Form to add a wire\n '''\n\n class Meta:\n model = Wire\n exclude = ('product')\n\nclass FuseForm(forms.ModelForm):\n '''\n Form to add a fuse\n '''\n\n class Meta:\n model = Fuse\n exclude = ('product')\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email')\n\nGROUPS = ((2, 'Administrador'), (3, 'Distribuidor'),)\n\nclass CreateUserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('username', 'email', 'first_name', 'last_name')\n\n group = forms.ChoiceField(widget=forms.Select, choices=GROUPS, label=\"Rol\")\n\n def clean(self):\n '''\n Check if the email its given\n '''\n cleaned_data = super(CreateUserForm, self).clean()\n if not cleaned_data.get(\"email\") != '':\n self._errors[\"email\"] = self.error_class(['Este campo es obligatorio.'])\n\n return cleaned_data\n\nclass EditUserForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(EditUserForm, self).__init__(*args, **kwargs)\n self.initial['group'] = self.instance.groups.get().id\n\n class Meta:\n model = User\n fields = ('username', 'email', 'first_name', 'last_name', 'is_active')\n\n group = forms.ChoiceField(widget=forms.Select, choices=GROUPS, label=\"Rol\")\n\nclass BrandForm(forms.ModelForm):\n class Meta:\n model = Brand\n exclude = ('active',)\n\nclass KitForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(KitForm, self).__init__(*args, **kwargs)\n self.fields['products'].queryset = Product.objects.filter(active=True)\n\n class Meta:\n model = Kit\n exclude = ('active',)\n widgets = {\n 'description': forms.Textarea(attrs={'cols': 80, 'rows': 2}),\n }\n\nclass TariffAddForm(forms.ModelForm):\n class Meta:\n model = Tariff\n exclude = ('active',)\n\nclass TariffEditForm(forms.ModelForm):\n class Meta:\n model = Tariff\n exclude = ('active','charge_type')\n\nclass ChargeBasicForm(forms.ModelForm):\n class Meta:\n model = ChargeBasic\n exclude = ('tariff', 'active',)\n\n def __init__(self, *args, **kwargs):\n self.tariff = kwargs.pop('tariff', None)\n super(ChargeBasicForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(ChargeBasicForm, self).clean()\n month = cleaned_data.get(\"month\")\n year = cleaned_data.get(\"year\")\n existing_charge = self.tariff.basic_charges.filter(\n year=year,\n month=month,\n ).exclude(\n id=self.instance.id,\n ).exclude(\n active=False,\n )\n\n if existing_charge:\n msg = \"Ya existe un cargo para este periodo\"\n self._errors[\"month\"] = self.error_class([msg])\n self._errors[\"year\"] = self.error_class([msg])\n\n # These fields are no longer valid. Remove them from the\n # cleaned data.\n del cleaned_data[\"month\"]\n del cleaned_data[\"year\"]\n\n # Always return the full collection of cleaned data.\n return cleaned_data\n\nclass DACForm(forms.ModelForm):\n class Meta:\n model = ChargeDAC\n exclude = ('tariff', 'active',)\n\n def __init__(self, *args, **kwargs):\n self.tariff = kwargs.pop('tariff', None)\n super(DACForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(DACForm, self).clean()\n month = cleaned_data.get(\"month\")\n year = cleaned_data.get(\"year\")\n existing_charge = self.tariff.dac_charges.filter(\n year=year,\n month=month,\n ).exclude(\n id=self.instance.id,\n ).exclude(\n active=False,\n )\n\n if existing_charge:\n msg = \"Ya existe un cargo para este periodo\"\n self._errors[\"month\"] = self.error_class([msg])\n self._errors[\"year\"] = self.error_class([msg])\n\n # These fields are no longer valid. Remove them from the\n # cleaned data.\n del cleaned_data[\"month\"]\n del cleaned_data[\"year\"]\n\n # Always return the full collection of cleaned data.\n return cleaned_data\n\nclass ChargeBasicFixedForm(forms.ModelForm):\n class Meta:\n model = ChargeBasicFixed\n exclude = ('tariff', 'active',)\n\n def __init__(self, *args, **kwargs):\n self.tariff = kwargs.pop('tariff', None)\n super(ChargeBasicFixedForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(ChargeBasicFixedForm, self).clean()\n month = cleaned_data.get(\"month\")\n year = cleaned_data.get(\"year\")\n existing_charge = self.tariff.basic_fixed_charges.filter(\n year=year,\n month=month,\n ).exclude(\n id=self.instance.id,\n ).exclude(\n active=False,\n )\n\n if existing_charge:\n msg = \"Ya existe un cargo para este periodo\"\n self._errors[\"month\"] = self.error_class([msg])\n self._errors[\"year\"] = self.error_class([msg])\n\n # These fields are no longer valid. Remove them from the\n # cleaned data.\n del cleaned_data[\"month\"]\n del cleaned_data[\"year\"]\n\n # Always return the full collection of cleaned data.\n return cleaned_data\n\nclass DemandForm(forms.ModelForm):\n class Meta:\n model = ChargeDemand\n exclude = ('tariff', 'active',)\n\n def __init__(self, *args, **kwargs):\n self.tariff = kwargs.pop('tariff', None)\n super(DemandForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(DemandForm, self).clean()\n month = cleaned_data.get(\"month\")\n year = cleaned_data.get(\"year\")\n existing_charge = self.tariff.demand_charges.filter(\n year=year,\n month=month,\n ).exclude(\n id=self.instance.id,\n ).exclude(\n active=False,\n )\n\n if existing_charge:\n msg = \"Ya existe un cargo para este periodo\"\n self._errors[\"month\"] = self.error_class([msg])\n self._errors[\"year\"] = self.error_class([msg])\n\n # These fields are no longer valid. Remove them from the\n # cleaned data.\n del cleaned_data[\"month\"]\n del cleaned_data[\"year\"]\n\n # Always return the full collection of cleaned data.\n return cleaned_data\n\nclass PeakForm(forms.ModelForm):\n class Meta:\n model = ChargePeak\n exclude = ('tariff', 'active',)\n\n def __init__(self, *args, **kwargs):\n self.tariff = kwargs.pop('tariff', None)\n super(PeakForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(PeakForm, self).clean()\n month = cleaned_data.get(\"month\")\n year = cleaned_data.get(\"year\")\n existing_charge = self.tariff.peak_charges.filter(\n year=year,\n month=month,\n ).exclude(\n id=self.instance.id,\n ).exclude(\n active=False,\n )\n if existing_charge:\n msg = \"Ya existe un cargo para este periodo\"\n self._errors[\"month\"] = self.error_class([msg])\n self._errors[\"year\"] = self.error_class([msg])\n\n # These fields are no longer valid. Remove them from the\n # cleaned data.\n del cleaned_data[\"month\"]\n del cleaned_data[\"year\"]\n\n # Always return the full collection of cleaned data.\n return cleaned_data\n\nclass LoginAsForm(forms.Form):\n \"\"\"\n FROM: http://djangosnippets.org/snippets/1552/\n Sometimes to debug an error you need to login as a specific User.\n This form allows you to log as any user in the system. You can restrict\n the allowed users by passing a User queryset paramter, `qs` when the\n form is instantiated.\n \"\"\"\n user = forms.ModelChoiceField(User.objects.all())\n \n def __init__(self, data=None, files=None, request=None, qs=None, *args,\n **kwargs):\n if request is None:\n raise TypeError(\"Keyword argument 'request' must be supplied\")\n super(LoginAsForm, self).__init__(data=data, files=files, *args, **kwargs)\n self.request = request\n if qs is not None:\n self.fields[\"user\"].queryset = qs\n\n\n def save(self):\n user = self.cleaned_data[\"user\"]\n backend = get_backends()[0]\n user.backend = \"%s.%s\" % (backend.__module__, backend.__class__.__name__)\n login(self.request, user)","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":19319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"585377046","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\pipeline\\variationoperators.py\n# Compiled at: 2019-03-07 15:21:12\nimport collections, numpy as np, loader\nfrom scipy import signal\nimport integration, writer\n\ndef chisquared(data, t, roi):\n current = data[t].astype(float)\n previous = data[(t - 1)].astype(float)\n return np.sum(roi * np.square(current - previous))\n\n\ndef imgmax(data, t, roi):\n current = data[t].astype(float)\n return (roi * current).max()\n\n\ndef qmax(data, t, roi):\n current = data[t]\n q, I = integration.radialintegratepyFAI(current, cut=roi)[:2]\n return q[np.argmax(I)]\n\n\ndef fit_mean(data, t, roi):\n current = data[t]\n q, I = integration.radialintegratepyFAI(current, cut=roi)[:2]\n from astropy.modeling import models, fitting\n qmin = q[(np.array(I) != 0).argmax()]\n qmax = q[(len(I) - 1 - (np.array(I) != 0)[::-1].argmax())]\n g_init = models.Gaussian1D(amplitude=np.array(I).max(), mean=(qmax + qmin) / 2, stddev=(qmax - qmin) / 4)\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, q, I)\n return g.mean.value\n\n\ndef fit_stddev(data, t, roi):\n current = data[t]\n q, I = integration.radialintegratepyFAI(current, cut=roi)[:2]\n from astropy.modeling import models, fitting\n qmin = q[(np.array(I) != 0).argmax()]\n qmax = q[(len(I) - 1 - (np.array(I) != 0)[::-1].argmax())]\n g_init = models.Gaussian1D(amplitude=np.array(I).max(), mean=(qmax + qmin) / 2, stddev=(qmax - qmin) / 4)\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, q, I)\n return g.stddev.value\n\n\ndef gaussian_fit(data, t, roi):\n current = data[t]\n q, I = integration.radialintegratepyFAI(current, cut=roi)[:2]\n from astropy.modeling import models, fitting\n qmin = q[(np.array(I) != 0).argmax()]\n qmax = q[(len(I) - 1 - (np.array(I) != 0)[::-1].argmax())]\n g_init = models.Gaussian1D(amplitude=np.array(I).max(), mean=(qmax + qmin) / 2, stddev=(qmax - qmin) / 4)\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, q, I)\n return collections.OrderedDict([\n (\n 'stddev', g.stddev.value), ('mean', g.mean.value), ('Amplitude', g.amplitude.value),\n (\n 'chi^2', np.average((g(q) - I) ** 2))])\n\n\ndef absdiff(data, t, roi):\n current = data[t].astype(float)\n previous = data[(t - 1)].astype(float)\n return np.sum(roi * np.abs(current - previous))\n\n\ndef normabsdiff(data, t, roi):\n current = data[t].astype(float)\n previous = data[(t - 1)].astype(float)\n return np.sum(roi * np.abs(current - previous) / previous)\n\n\ndef sumintensity(data, t, roi):\n current = data[t].astype(float)\n return np.sum(roi * current)\n\n\ndef normabsdiffderiv(data, t, roi):\n current = data[t].astype(float)\n previous = data[(t - 1)].astype(float)\n next = data[(t + 1)].astype(float)\n return -np.sum(roi * (np.abs(next - current) / current) + np.sum(np.abs(current - previous) / current))\n\n\ndef chisquaredwithfirst(data, t, roi):\n current = data[t].astype(float)\n first = data[0].astype(float)\n return np.sum(roi * np.square(current.astype(float) - first))\n\n\ndef radialintegration(data, t, roi):\n current = data[t]\n return integration.radialintegratepyFAI(current, cut=roi)[:2]\n\n\ndef angularcorrelationwithfirst(data, t, roi):\n experiment.center = (\n experiment.center[0] / 5, experiment.center[1] / 5)\n currentcake, _, _ = integration.cake(data[t], experiment)\n firstcake, _, _ = integration.cake(data[0], experiment)\n currentchi = np.sum(currentcake * roi, axis=0)\n firstchi = np.sum(firstcake * roi, axis=0)\n return signal.convolve(currentchi, firstchi)\n\n\noperations = collections.OrderedDict([('Chi Squared', chisquared),\n (\n 'Max', imgmax),\n (\n 'Absolute Diff.', absdiff),\n (\n 'Norm. Abs. Diff.', normabsdiff),\n (\n 'Sum Intensity', sumintensity),\n (\n 'Norm. Abs. Derivative', normabsdiffderiv),\n (\n 'Chi Squared w/First Frame', chisquaredwithfirst),\n (\n 'Angular autocorrelation w/First Frame', angularcorrelationwithfirst),\n (\n 'Radial Integration', radialintegration),\n (\n 'Q at peak max', qmax),\n (\n 'Q at peak fit max', fit_mean),\n (\n 'Peak Fit Std. Dev.', fit_stddev),\n (\n 'Gaussian Q Fit', gaussian_fit)])\nexperiment = None","sub_path":"pycfiles/xicam-1.2.26-py2.7/variationoperators.py","file_name":"variationoperators.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"645677907","text":"#-----------------------------------------------------------------------------------\n# recommendations.py\n# file is taken from Toby Segaran's \"Programming Collective Intelligence\" First edition\n#-----------------------------------------------------------------------------------\nimport logging\nlogging.basicConfig(filename='log_filename.txt', level = logging.DEBUG,\n format='%(asctime)s - %(levelname)s - %(message)s')\nlogging.debug('This is a log message.')\n \n# A dictionary of movie critics and their ratings of a small set of movies\ncritics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, \n 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0},\n 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5, 'Just My Luck': 1.5, \n 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5, 'The Night Listener': 3.0},\n 'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0, 'Superman Returns': 3.5, 'The Night Listener': 4.0},\n 'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 4.0, 'The Night Listener': 4.5,\n 'You, Me and Dupree': 2.5},\n 'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0, 'Just My Luck': 2.0, \n 'Superman Returns': 3.0, 'You, Me and Dupree': 2.0, 'The Night Listener': 3.0},\n 'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0, 'Superman Returns': 5.0, \n 'You, Me and Dupree': 3.5, 'The Night Listener': 3.0},\n 'Toby': {'Snakes on a Plane': 4.5, 'Superman Returns': 4.0, 'You, Me and Dupree': 1.0}}\n\n#------------------------------------------------------------------------------------------\n# Similarity Functions\n#------------------------------------------------------------------------------------------\nfrom math import sqrt\n\n#------------------------------------------------------------------------------------------\n# function sim_distance\n# arguments: \n# prefs: nested dictionary of preference rating scores\n# person1, person2: strings of names of people whose preferences to compare\n# Returns a Euclidian distance-based similarity score for person1 and person2\n# (returns 0 if person1 and person2 have no ratings in common)\n#------------------------------------------------------------------------------------------\ndef sim_distance(prefs, person1, person2):\n #Get the list of items shared by person1 and person2\n shared_items = {}\n for item in prefs[person1]:\n if item in prefs[person2]:\n shared_items[item] = 1\n \n #if the persons have no ratings in common, return 0\n if len(shared_items) == 0: return 0\n \n #Add up the squares of all the differences\n sum_of_squares = sum( [ pow( prefs[person1][item] - prefs[person2][item], 2 ) for item in shared_items ] )\n \n return 1 / (1 + sqrt(sum_of_squares) )\n \n#------------------------------------------------------------------------------------------\n# function sim_pearson\n# arguments: \n# prefs: nested dictionary of preference rating scores\n# person1, person2: strings of names of people whose preferences to compare\n# Returns a Pearson correlation coefficient for person1 and person2\n# (returns 0 if person1 and person2 have no ratings in common)\n# (returns 0 if ratings are identical (?)\n#------------------------------------------------------------------------------------------\ndef sim_pearson(prefs, person1, person2):\n #Get the list of mutually rated items\n shared_items = {}\n for item in prefs[person1]:\n if item in prefs[person2]: shared_items[item] = 1\n \n #Find the number of shared items\n num_items = len(shared_items)\n \n # if they have no ratings in common, return 0\n if num_items == 0: return 0\n \n #Add up all the preferences\n sum1 = sum([ prefs[person1][item] for item in shared_items])\n sum2 = sum([ prefs[person2][item] for item in shared_items])\n \n #Sum up the squares of preferences\n sum1Sq = sum([ pow(prefs[person1][item], 2) for item in shared_items ])\n sum2Sq = sum([ pow(prefs[person2][item], 2) for item in shared_items ])\n\n # Sum up the products\n pSum = sum([ prefs[person1][item] * prefs[person2][item] for item in shared_items ])\n \n # calculate Pearson score\n num = pSum - (sum1 * sum2 / num_items)\n den = sqrt( ( sum1Sq - pow(sum1, 2) / num_items ) * ( sum2Sq - pow(sum2, 2) / num_items ) )\n if den == 0: return 0\n \n r = num / den\n \n return r\n \n#------------------------------------------------------------------------------------------\n# function topMatches\n# Returns the best matches for person from the prefs dictionary\n# Number of results and similarity function are optional parameters\n#------------------------------------------------------------------------------------------\ndef topMatches(prefs, person, n = 5, similarity = sim_pearson):\n scores = [ (similarity(prefs, person, other), other) for other in prefs if other != person]\n \n #Sort the list so the highest scores appear at the top\n scores.sort()\n scores.reverse()\n return scores[ 0:n ]\n \n#------------------------------------------------------------------------------------------\n# function getRecommendations\n# Gets recommendations for a person by using a weighted average of every other user's ratings\n#------------------------------------------------------------------------------------------\ndef getRecommendations(prefs, person, similarity = sim_pearson):\n logging.debug('running getRecommendations')\n totals = {}\n simSums = {}\n for other in prefs:\n logging.debug( 'comparing {0} to {1}'.format(other, person) )\n\n # don't compare me to myself\n if other == person: continue\n sim = similarity(prefs, person, other)\n \n # ignore scores of zero or lower\n logging.debug( 'sim is {0}'.format(sim) )\n if sim <= 0: continue\n for item in prefs[other]:\n logging.debug( 'comparing item {0}'.format(item) )\n \n # only score movies I haven't seen yet\n if item not in prefs[person] or prefs[person][item] == 0:\n logging.debug( 'item {0} is new'.format(item) )\n # Similarity * Score\n totals.setdefault(item, 0)\n totals[item] += prefs[other][item] * sim\n # Sum of similarities\n simSums.setdefault(item, 0)\n simSums[item] += sim\n \n # Create the normalized list\n rankings = [ (total / simSums[item], item) for item, total in totals.items() ]\n \n # Return the sorted list\n rankings.sort()\n rankings.reverse()\n return rankings\n \n#-------------------------------------------------------------------------------------------\n# function transformPrefs\n# change prefs from a list of lists of films by reviewer to a list of lists of reviewers by films\n#-------------------------------------------------------------------------------------------\ndef transformPrefs(prefs):\n result = {}\n for person in prefs:\n for item in prefs[person]:\n result.setdefault(item, {})\n \n #Flip item and person\n result[item][person] = prefs[person][item]\n \n return result","sub_path":"chapter2/recommendations.py","file_name":"recommendations.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"117269778","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of EMTools\n\n\"\"\"\nIO module for EMTools package\n\n@author: Andrew Herzing\n\"\"\"\n\nfrom scipy.io import savemat, loadmat\nimport numpy as np\nimport hyperspy.api as hs\n\n\ndef save_axsia(s, filename=None):\n \"\"\"\n Save a Hyperspy signal in an AXSIA-ready Matlab file.\n\n Args\n ----------\n s : Hyperspy Signal2D\n filename : string\n Name for output .MAT file\n\n \"\"\"\n if not filename:\n filename = 'matlab.mat'\n savedict = {}\n savedict['nrows'] = np.float64(s.data.shape[1])\n savedict['ncols'] = np.float64(s.data.shape[0])\n savedict['nchannels'] = np.float64(s.data.shape[2])\n savedict['resolution'] = np.float64(s.axes_manager[-1].scale)\n s.unfold()\n savedict['specdata'] = s.data.T\n\n savemat(filename, savedict, format='5')\n\n s.fold()\n\n return\n\n\ndef axsia_to_hspy(filename, calibration_signal=None, im_shape=None):\n \"\"\"\n Load output of MVSA analysis from AXSIA software as a Hyperspy signal.\n\n Args\n ----------\n filename : string\n Name for AXSIA output file to load\n calibration_signal : Hyperspy Signal2D\n Signal from which to get calibration info\n im_shape : tuple\n Number of rows and columns of the original dataset.\n\n \"\"\"\n axsia = {}\n\n axsia_in = loadmat(filename)\n if 'nrows' and 'ncols' in axsia_in.keys():\n nrows = axsia_in['nrows'][0][0]\n ncols = axsia_in['ncols'][0][0]\n elif calibration_signal:\n nrows = calibration_signal.data.shape[0]\n ncols = calibration_signal.data.shape[1]\n elif im_shape:\n nrows = im_shape[0]\n ncols = im_shape[1]\n else:\n raise ValueError(\n 'SVD Decomposition requires definition of image shape')\n\n if 'npures' in axsia_in.keys():\n npures = axsia_in['npures'][0][0]\n else:\n npures = axsia_in['purespectra'].shape[1]\n if 'nchannels' in axsia_in.keys():\n nchannels = axsia_in['nchannels'][0][0]\n else:\n nchannels = axsia_in['purespectra'].shape[0]\n loadings = axsia_in['concentrations']\n factors = axsia_in['purespectra']\n # method = axsia_in['SIparams'][0][0][6][0]\n\n axsia['loadings'] = \\\n hs.signals.Signal2D(loadings.reshape([nrows, ncols, npures]))\n axsia['loadings'] = axsia['loadings'].swap_axes(0, 1).swap_axes(1, 2)\n\n axsia['factors'] = \\\n hs.signals.Signal1D(factors.reshape([nchannels, npures]))\n axsia['factors'] = axsia['factors'].swap_axes(0, 1)\n\n if calibration_signal:\n axsia['factors'].axes_manager[1].name = \\\n calibration_signal.axes_manager[-1].name\n axsia['factors'].axes_manager[1].offset = \\\n calibration_signal.axes_manager[-1].offset\n axsia['factors'].axes_manager[1].scale = \\\n calibration_signal.axes_manager[-1].scale\n axsia['factors'].axes_manager[1].units = \\\n calibration_signal.axes_manager[-1].units\n\n axsia['loadings'].axes_manager[1].name = \\\n calibration_signal.axes_manager[0].name\n axsia['loadings'].axes_manager[1].offset = \\\n calibration_signal.axes_manager[0].offset\n axsia['loadings'].axes_manager[1].scale = \\\n calibration_signal.axes_manager[0].scale\n axsia['loadings'].axes_manager[1].units = \\\n calibration_signal.axes_manager[0].units\n\n axsia['loadings'].axes_manager[2].name = \\\n calibration_signal.axes_manager[1].name\n axsia['loadings'].axes_manager[2].offset = \\\n calibration_signal.axes_manager[1].offset\n axsia['loadings'].axes_manager[2].scale = \\\n calibration_signal.axes_manager[1].scale\n axsia['loadings'].axes_manager[2].units = \\\n calibration_signal.axes_manager[1].units\n\n return axsia\n","sub_path":"emtools/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"416933014","text":"# Create your tasks here\nfrom __future__ import absolute_import, unicode_literals\nfrom celery import shared_task\nfrom analyticsApi.models import Profile, SmAccount, ProfileLike, ProfileMetric, PostVision, Post, ProfileEngagementMetric\nfrom analyticsApi.serializers import ProfileSerializer, PostSerializer, ProfileLikeSerializer, ProfileMetricSerializer\nfrom analyticsApi.simplyMeasured.api.analytics.analytics import ApiAnalytics\nfrom analyticsApi.utility import Utility\nfrom analyticsApi.simplyMeasured.api.token.token import ApiToken\nfrom celery.task.schedules import crontab\nfrom celery.decorators import periodic_task\nfrom datetime import datetime\nfrom analytics.celery import app\nfrom django.db import connection\nimport json\nfrom django.core.mail import EmailMessage\nimport requests\n\n\ndef syncProfiles(is_hourly=False):\n '''\n SyncProfiless will create or update the profiles\n of simply measured associated with the token and account id\n '''\n api_token = ApiToken()\n TOKEN = api_token.get_api_token()\n if (TOKEN):\n obj = ApiAnalytics(TOKEN)\n result = obj.get_profiles()\n if result:\n Profile.objects.all().update(is_active=False)\n\n r = Utility.save_and_update_data(\n ProfileSerializer, result, Profile, 'profile_id', 'profile_id')\n print(r)\n if is_hourly:\n print('In Hourly. saving the Profile Metric')\n ProfileMetric.objects.filter(\n is_latest=True).update(is_latest=False)\n ac = Utility.save_and_update_data(\n ProfileMetricSerializer, result, ProfileMetric)\n print(ac)\n else:\n print('Token Not Found')\n\n\ndef syncAllProfilesPost():\n '''\n SyncPost will create or update the posts\n of simply measured associated with the token and profiles\n '''\n api_token = ApiToken()\n TOKEN = api_token.get_api_token()\n count = 0\n for profile in Profile.objects.filter(is_active=True):\n count = count + 1\n print('Profile Id Sync Starts for ' +\n str(profile.profile_id) + ' at ' + str(datetime.now()))\n syncProfilePosts.apply_async(\n args=[profile.profile_id, profile.sm_account.sm_id, TOKEN])\n print('Profile Id Sync Completed for ' +\n str(profile.profile_id) + ' at ' + str(datetime.now()))\n print('Count is ' + str(count))\n\n\n# def syncAllProfilesLikes():\n# '''\n# SyncPost will create or update the posts\n# of simply measured associated with the token and profiles\n# '''\n\n# for profile in Profile.objects.filter(is_active=True):\n# syncProfileLikes(profile)\n\n\n# def syncProfileLikes(profile):\n# '''\n# syncProfilePosts will create or update the likes\n# of simply measured associated with the token and profile\n# '''\n# params = {'filter': [\n# # 'post.creation_date.gte(2016-01-01)',\n# 'author.id.eq(' + str(profile.profile_id) + ')'],\n# 'dimensions': 'post.creation_date.by(hour)',\n# 'metrics': 'post.likes_count'\n# }\n# api_token = ApiToken()\n# TOKEN = api_token.get_api_token()\n# if TOKEN:\n# obj = ApiAnalytics(TOKEN)\n# ret_data = obj.get_profile_likes(\n# profile.sm_account.sm_id, profile.profile_id, params)\n# r = Utility.save_and_update_data(\n# ProfileLikeSerializer, ret_data, ProfileLike, None, None)\n# print(r)\n# else:\n# print('Token Not Found')\n\n\n@app.task\ndef syncProfilePosts(profile_id, sm_acc_id, TOKEN):\n print(profile_id, sm_acc_id, TOKEN)\n '''\n syncProfilePosts will create or update the posts\n of simply measured associated with the token and profile\n '''\n params = {'filter': [\n 'author.id.eq(' + str(profile_id) + ')'],\n 'limit': 1000,\n 'fields': 'post.url,post.target_url,post.sentiment,post.primary_content_type,post.language,post.province,post.is_brand,post.image_urls,post.distribution_type,post.country,data_source_id,datarank,channel,author.profile_link,author.image_url,author.display_name,post.geo,post.hashtags,post.instagram.image_filter,post.body,post.id,post.content_types,post.creation_date,author.id',\n 'metrics': 'post.replies_count,post.shares_count,post.likes_count,post.engagement_total,post.dislikes_count'\n }\n # api_token = ApiToken()\n # TOKEN = api_token.get_api_token()\n if (TOKEN):\n obj = ApiAnalytics(TOKEN)\n # print(params)\n obj.get_posts(sm_acc_id, params)\n else:\n print('Token Not Found')\n\n\n# def syncSinglePost(post):\n# params = {'filter': [\n# 'post.creation_date.gte(1970-01-01)',\n# 'author.id.eq(' + str(post.profile_id) + ')',\n# 'post.id.eq(' + post.post_id + ')'\n# ]}\n# obj = ApiAnalytics(TOKEN)\n# # obj.get_posts_by_profile(profile, None, params)\n\n\n# @periodic_task(run_every=(crontab(minute=0, hour='*/1')), name=\"syncAllProfileAndPost\", ignore_result=True)\ndef syncAllProfileAndPost():\n syncProfiles(is_hourly=True)\n syncAllProfilesPost()\n email = EmailMessage('syncAllProfileAndPost at (' + str(datetime.now()) + ')',\n 'syncAllProfileAndPost', to=['himanshu@poletus.com', 'niles@poletus.com', 'engineering@poletus.com'])\n email.send()\n\n\n# @periodic_task(run_every=(crontab(minute='*/5')), name=\"syncAudienceCount\", ignore_result=True)\ndef syncAudienceCount():\n syncProfiles()\n\n\n@app.task\ndef syncVisionByPost(post_id, post_image):\n print(\"INTO THE SYNC FOR %s IMAGE(%s)\" % (post_id, post_image))\n from analyticsApi.vision import get_vision_results\n google_vision, aws_vision = get_vision_results(\n post_image)\n post_vision = PostVision(post=Post.objects.get(post_id=post_id))\n try:\n google_image_properties_annotation = google_vision[\n 'responses'][0]['imagePropertiesAnnotation']\n except (KeyError, IndexError):\n google_image_properties_annotation = None\n\n try:\n google_label_annotation = google_vision[\n 'responses'][0]['labelAnnotations']\n except (KeyError, IndexError):\n google_label_annotation = None\n\n try:\n google_face_annotation = google_vision[\n 'responses'][0]['faceAnnotations']\n except (KeyError, IndexError):\n google_face_annotation = None\n\n try:\n aws_detect_faces = aws_vision['detect_faces']\n except (KeyError, IndexError):\n aws_detect_faces = None\n try:\n aws_detect_labels = aws_vision['detect_labels']\n except (KeyError, IndexError):\n aws_detect_labels = None\n\n post_vision.google_face_annotation = google_face_annotation\n post_vision.google_label_annotation = google_label_annotation\n post_vision.google_image_properties_annotation = google_image_properties_annotation\n post_vision.aws_detect_faces = aws_detect_faces\n post_vision.aws_detect_labels = aws_detect_labels\n post_vision.save()\n\n\n@periodic_task(run_every=(crontab(minute=0, hour='*/1')), name=\"syncAllVisionProfiles\", ignore_result=True)\ndef syncVision():\n from analyticsApi.models import Post, PostVision\n already_visioned = PostVision.objects.all().values_list('post_id', flat=True)\n already_visioned = list(already_visioned)\n posts = Post.objects.filter(image_urls__isnull=False).exclude(\n post_id__in=already_visioned)\n for post in posts:\n print(post.id)\n if post.image_urls:\n try:\n syncVisionByPost.apply_async(\n args=[post.post_id, post.image_urls[0]])\n # syncVisionByPost(post, google_vision, aws_vision)\n except Exception:\n import traceback\n print(traceback.print_exc())\n print('ERROR in *****************')\n print(post)\n\n\n@app.task\ndef saveEngagementAverage(profile_id):\n print('Engagement Avg For ' + str(profile_id))\n profile_engagement_metric, created = ProfileEngagementMetric.objects.get_or_create(\n profile_id=profile_id, engagement_type=1)\n sql = '''SELECT pm.engagement_count,\n CASE WHEN post.created_at::time < date_trunc('hour', post.created_at::time) + interval '45 minutes' \n THEN EXTRACT(HOUR FROM post.created_at)::integer ELSE (EXTRACT(HOUR FROM post.created_at) + 1)::integer \n END AS \"HOUR_OF_POSTING\", post.created_at::time, \n EXTRACT(DOW FROM post.created_at)::integer as dayOfWeek FROM public.\"analyticsApi_post\" post \n LEFT JOIN public.\"analyticsApi_postlatestmetric\" pm ON (pm.post_id_id=post.post_id) \n WHERE post.profile_id = %s'''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id])\n arr = []\n for i in range(24):\n for j in range(7):\n arr.append([i, j, 0, 0])\n for row in cursor.fetchall():\n row_zero = row[0]\n if not row_zero:\n row_zero = 0\n tmp_hour = row[1]\n tmp_day = row[3]\n if(tmp_hour == 24):\n tmp_hour = 0\n tmp_day += 1\n if(tmp_day == 7):\n tmp_day = 0\n arr[tmp_hour * 7 + tmp_day][2] += 1\n arr[tmp_hour * 7 + tmp_day][3] += row_zero\n for elem in arr:\n tmp = 0\n if elem[2]:\n tmp = round(elem[3] / elem[2])\n elem.pop()\n elem.pop()\n elem.append(tmp)\n profile_engagement_metric.profile_id = profile_id\n profile_engagement_metric.json_response = arr\n profile_engagement_metric.engagement_type = 1\n profile_engagement_metric.save()\n finally:\n cursor.close()\n\n\n@app.task\ndef saveEngagementFrequency(profile_id):\n print('Engagement Freq For ' + str(profile_id))\n profile_engagement_metric, created = ProfileEngagementMetric.objects.get_or_create(\n profile_id=profile_id, engagement_type=2)\n sql = '''SELECT pm.engagement_count, \n CASE WHEN post.created_at::time < date_trunc('hour', post.created_at::time) + interval '45 minutes' \n THEN EXTRACT(HOUR FROM post.created_at)::integer \n ELSE (EXTRACT(HOUR FROM post.created_at) + 1)::integer \n END AS \"HOUR_OF_POSTING\", post.created_at::time, \n EXTRACT(DOW FROM post.created_at)::integer as dayOfWeek FROM public.\"analyticsApi_post\" post \n LEFT JOIN public.\"analyticsApi_postlatestmetric\" pm ON (pm.post_id_id=post.post_id) \n WHERE post.profile_id = %s '''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id])\n arr = []\n for i in range(24):\n for j in range(7):\n arr.append([i, j, 0])\n\n for row in cursor.fetchall():\n tmp_hour = row[1]\n tmp_day = row[3]\n if(tmp_hour == 24):\n tmp_hour = 0\n tmp_day += 1\n if(tmp_day == 7):\n tmp_day = 0\n arr[tmp_hour * 7 + tmp_day][2] += 1\n profile_engagement_metric.profile_id = profile_id\n profile_engagement_metric.json_response = arr\n profile_engagement_metric.engagement_type = 2\n profile_engagement_metric.save()\n finally:\n cursor.close()\n\n\n@periodic_task(run_every=(crontab(minute=0, hour=0)), name=\"saveProfileEngagementDaily\", ignore_result=True)\ndef saveProfileEngagementDaily():\n for profile in Profile.objects.filter(is_active=True):\n print('Saving Engagement for Profile Id - ' +\n str(profile.profile_id) + ' Starts')\n saveEngagementAverage.apply_async(args=[str(profile.profile_id)])\n saveEngagementFrequency.apply_async(args=[str(profile.profile_id)])\n print('Saving Engagement for Profile Id - ' +\n str(profile.profile_id) + ' Finished')\n\n\n@periodic_task(run_every=(crontab(minute=0, hour='*/2')), name=\"saveProfileCompleteMetric\", ignore_result=True)\ndef saveProfileCompleteMetric():\n for profile in Profile.objects.filter(is_active=True):\n print('Saving saveProfileCompleteMetric for Profile Id - ' +\n str(profile.profile_id) + ' Starts')\n saveProfileCompleteMetricByProfile.apply_async(\n args=[str(profile.profile_id)])\n print('Saving saveProfileCompleteMetric for Profile Id - ' +\n str(profile.profile_id) + ' Finished')\n\n\n@app.task\ndef saveProfileCompleteMetricByProfile(profile_id):\n print('Profile Complete Metric Profile' + str(profile_id))\n profile_engagement_metric, created = ProfileEngagementMetric.objects.get_or_create(\n profile_id=profile_id, engagement_type=3)\n import datetime\n daysago = datetime.datetime.now() + datetime.timedelta(-10)\n daysago = daysago.strftime(\"%Y-%m-%d\")\n result = []\n sql = '''\n SELECT audience_count\n FROM public.\"analyticsApi_profilemetric\"\n WHERE profile_id = %s ORDER BY created_at DESC LIMIT 1\n '''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id])\n query_result = cursor.fetchone()\n if query_result:\n totalFollowerCount = query_result[0]\n else:\n totalFollowerCount = 0\n finally:\n cursor.close()\n\n result.append(totalFollowerCount)\n sql = '''\n SELECT SUM(pm.comment_count) as totalCommentCount,SUM(pm.like_count) as totalLikeCount \n FROM public.\"analyticsApi_postlatestmetric\" pm\n WHERE pm.profile_id = %s\n '''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id])\n query_result = cursor.fetchone()\n totalCommentCount = query_result[0] or 0\n totalLikeCount = query_result[1] or 0\n result.append(totalCommentCount)\n result.append(totalLikeCount)\n finally:\n cursor.close()\n\n sql = '''\n SELECT SUM(a.like_count) as totalLike, SUM(a.comment_count)\n as totalComment, SUM(a.engagement_count) as totalEngage\n FROM (SELECT DISTINCT ON (post_id_id)\n like_count, engagement_count,comment_count\n FROM public.\"analyticsApi_postmetric\"\n WHERE profile_id = %s\n AND created_at::date = %s) a\n '''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id, daysago])\n query_result = cursor.fetchone()\n if not query_result:\n query_result = (0, 0, 0)\n finally:\n cursor.close()\n\n daysAgoLikeCount = query_result[0]\n if not daysAgoLikeCount:\n daysAgoLikeCount = 0\n daysAgoCommentCount = query_result[1]\n if not daysAgoCommentCount:\n daysAgoCommentCount = 0\n daysAgoEngagementCount = query_result[2]\n if not daysAgoEngagementCount:\n daysAgoEngagementCount = 0\n\n like = totalLikeCount - daysAgoLikeCount\n comment = totalCommentCount - daysAgoCommentCount\n result.append(like + comment)\n\n sql = '''\n SELECT DISTINCT ON (created_at::date) audience_count\n FROM public.\"analyticsApi_profilemetric\"\n WHERE profile_id = %s AND created_at::date = %s\n ORDER BY created_at::date DESC\n '''\n cursor = connection.cursor()\n try:\n cursor.execute(sql, [profile_id, daysago])\n query_result = cursor.fetchone()\n if not query_result:\n daysAgoFollowerCount = 0\n else:\n daysAgoFollowerCount = query_result[0]\n if not daysAgoFollowerCount:\n daysAgoFollowerCount = 0\n finally:\n cursor.close()\n result.append(totalFollowerCount - daysAgoFollowerCount)\n result.append(comment)\n result.append(like)\n result = list(map(int, result))\n profile_engagement_metric.profile_id = profile_id\n profile_engagement_metric.json_response = result\n profile_engagement_metric.engagement_type = 3\n profile_engagement_metric.save()\n\n\n@periodic_task(run_every=(crontab(minute=0, hour='*/1')), name=\"cacheAllProfiles\", ignore_result=True)\ndef cacheAllProfiles():\n from analyticsApi.models import Profile\n profiles = Profile.objects.all()\n req_urls = []\n for profile in profiles:\n print(profile.profile_id)\n urls = cacheForSingleProfile(profile.profile_id)\n req_urls = urls + req_urls\n for u in req_urls:\n print('--------------------------------------')\n print(u)\n resp = requests.get(u)\n print(resp)\n print('--------------------------------------')\n # result = [requests.get(u) for u in req_urls]\n # print(result)\n # grequests.map(rs)\n\n\ndef cacheForSingleProfile(profile_id):\n print(\"INTO THE CACHE FOR %s PROFILE\" % (profile_id))\n BASE_URL = 'https://apis.poletusengineering.com'\n BASE_URL = 'http://127.0.0.1:8000'\n BASE_URL = 'http://13.58.148.48'\n urls = [\n BASE_URL + '/analytics/api/' +\n str(profile_id) +\n '/Posts/engagement/ProfileLikeHistory?limit=7&format=json&cache=1',\n BASE_URL + '/analytics/api/' +\n str(profile_id) +\n '/Posts/engagement/ProfileEngagementHistory?limit=7&format=json&cache=1',\n BASE_URL + '/analytics/api/' +\n str(profile_id) + '/Posts/PostGeolocation?format=json&cache=1',\n BASE_URL + '/analytics/api/' +\n str(profile_id) + '/Posts/PostTagRepartition?format=json&cache=1',\n BASE_URL + '/analytics/api/' +\n str(profile_id) + '/Posts/PostDensity?format=json&cache=1',\n BASE_URL + '/analytics/api/' +\n str(profile_id) +\n '/Posts/engagement/ProfileCommentHistory?limit=7&format=json&cache=1',\n ]\n return urls\n","sub_path":"analyticsApi/tasks/analyticsTask.py","file_name":"analyticsTask.py","file_ext":"py","file_size_in_byte":17387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"546510349","text":"var = int(input('Selecione a quantidade de termos da sequencia de Fibonacci: '))\nprint('=='*20)\n\nt1 = 0\nt2 = 1\nprint('{} => {}'.format(t1, t2), end='')\n\nfor x in range(var):\n t3 = t1 + t2\n print(' => {}'.format(t3), end='')\n t1 = t2\n t2 = t3\n\nprint(' => FIM!')","sub_path":"Sequencia de Fibonacci.py","file_name":"Sequencia de Fibonacci.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"210207200","text":"import sys, re, os, importlib\r\nimport julian\r\n\r\nbeginDate = []\r\nendDate = []\r\nseeing = []\r\njulianDate = []\r\ny_vertice = []\r\n\r\n\r\ndef main():\r\n\tos.system('cls')\r\n\tprint(\"\\nScript initializated\")\r\n\ttry:\r\n\t\tfile = sys.argv[1]\r\n\texcept (IndexError) as e:\r\n\t\tprint(\"Error Opening File. Aborting\")\r\n\t\t#file = 'data.txt'\r\n\t\tabort()\r\n\r\n\tif(filterData(file)):\r\n\t\tprint(\"Converting JulianDate to Standard DateTime\", end=\"\", flush=True)\r\n\t\tif (convertJulian(beginDate,endDate)):\r\n\t\t\tprint(\" ..................... [SUCCESS]\")\r\n\t\telse:\r\n\t\t\tprint(\" ..................... [FAIL]\")\r\n\r\n\t\tprint(\"Savind to file\", end=\"\", flush=True)\r\n\r\n\t\tif(1):\r\n\t\t\toutput = open(\"custom.js\", \"w\")\r\n\t\t\toutput.write(\"var data=[{\\nx:[\")\r\n\t\t\tone = 1\r\n\t\t\tfor item in y_vertice:\r\n\t\t\t\tif (one == 1):\r\n\t\t\t\t\toutput.write(\"\\\"%s\\\"\" % item)\r\n\t\t\t\t\tone = 0\r\n\t\t\t\telse:\r\n \t\t\t\t\toutput.write(\",\\\"%s\\\"\" % item)\r\n\t\t\toutput.write(\"], \\ny: [\")\r\n\t\t\tone = 1\r\n\t\t\tfor item in seeing:\r\n\t\t\t\tif (one == 1):\r\n\t\t\t\t\toutput.write(\"\\\"%s\\\", \"% item)\r\n\t\t\t\t\tone = 0\r\n\t\t\t\telse:\r\n\t\t\t\t\toutput.write(\",\\\"%s\\\"\"% item)\r\n\t\t\toutput.write(\"],\")\r\n\t\t\toutput.write(\"\"\"\r\n\t\t\t\ttype: 'scatter',\r\n\t\t\t\tmode: 'lines+markers',\r\n\t\t\t\tmarker: {\r\n\t\t\t\tcolor: 'rgb(55,128,191)',\r\n\t\t\t\twidth: 6\r\n\t\t\t\t},\r\n\t\t\t\tconnectgaps: true\r\n\t\t\t\t}];\r\n\t\t\t\tvar layout = {\r\n\t\t\t\ttitle: 'Seeing (Arcsec)',\r\n\t\t\t\txaxis: {\r\n\t\t\t\t\ttitle: 'Time'\r\n\t\t\t\t},\r\n\t\t\t\tyaxis: {\r\n\t\t\t\t\ttitle: 'Arcsec'\r\n\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t\tPlotly.newPlot('graph', data, layout);\r\n \t\t\t\t\"\"\")\r\n\r\n\t\t\toutput.close()\r\n\r\n\r\n\t\t\tprint(\" ................................................. [SUCCESS]\")\r\n\t\telse:\r\n\t\t\tprint(\" ................................................. [FAIL]\")\r\n\t\tabort()\r\n\r\n\telse:\r\n\t\tprint(\"ERROR: X and Y vertices are different sizes\")\r\n\ta=input()\r\n\r\ndef filterData(file):\r\n\tprint(\"Opening file\", end=\"\", flush=True)\r\n\tpattern = \"(\\d{1,10}\\.\\d{1,10}) ; (\\d{1,10}\\.\\d{1,10}).+;.+.+ (\\d{1}\\.\\d{2}) ; \"\r\n\tfile = open(file)\r\n\r\n\twith file as f:\r\n\t\tfor line in f:\r\n\t\t\tregex = re.match(pattern, line)\r\n\t\t\tif regex:\r\n\t\t\t\tbeginDate.append(regex.group(1))\r\n\t\t\t\tendDate.append(regex.group(2))\r\n\t\t\t\tseeing.append(regex.group(3))\r\n\t\t\telse:\r\n\t\t\t\tcontinue\r\n\r\n\tprint(\".................................................... [SUCCESS]\")\r\n\tsizeBeginDate = len(beginDate)\r\n\tsizeEndDate = len(endDate)\r\n\tsizeSeeing = len(seeing)\r\n\r\n\tdateArraysComp = sizeBeginDate == sizeEndDate\r\n\tdateAndSeeingComp = sizeEndDate == sizeSeeing\r\n\tdateAndSeeingNotNull = sizeSeeing > 1\r\n\r\n\tif dateArraysComp and dateAndSeeingComp and dateAndSeeingNotNull:\r\n\t\tprint(\"Data points captured: [\" + str(sizeSeeing) + \"]\")\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\ndef convertJulian(beginDateJDD, endDateJDD):\r\n\r\n\tif len(beginDateJDD) == len(endDateJDD):\r\n\t\tfor i in range(len(endDateJDD)):\r\n\t\t\tjulianDate.append(float(beginDateJDD[i])+(float(endDateJDD[i])-float(beginDateJDD[i]))/2.0)\r\n\t\t\ty_vertice.append(julian.jd_to_datetime(julianDate[i]))\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\ndef abort():\r\n\tprint(\"\\nNothing to do.\")\r\n\ta = input('Press enter to exit....')\r\n\texit()\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"272882441","text":"#Version history\r\n#0.1: Movement and select color implemented\r\n#0.2: Read and color board implemented\r\n#0.3: Paint on board implemented\r\n#0.4: 2P multiplayer implemented, and start from last sesion state\r\n#0.5: Clear background button with selected color implemented\r\n\r\n\r\n\r\n#Needs Pyxel to be installed, and run this file on shell/terminal with python\r\nimport pyxel\r\nfrom collections import namedtuple\r\n\r\n#Defined constants and variables\r\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\r\n\r\nUP = Point(0, -1)\r\nDOWN = Point(0, 1)\r\nRIGHT = Point(1, 0)\r\nLEFT = Point(-1, 0)\r\nIDLE = Point(0, 0)\r\n\r\n#Read player1 info to start\r\np1 = open(\"Player1.txt\", \"r\") # open file for reading\r\np1info = [] # initialize empty array\r\nfor line in p1:\r\n p1info.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array\r\n # thus creating an array of arrays.\r\np1.close() # close file.\r\nSTART = Point(int(p1info[0][0]), int(p1info[0][1]))\r\nSELECTEDCOL = int(p1info[0][2])\r\n\r\n#Game\r\nclass drawer:\r\n #Runs when booted\r\n def __init__(self):\r\n pyxel.init(32,32,caption=\"JS Draw\", fps=10)\r\n self.reset()\r\n pyxel.run(self.update, self.draw)\r\n \r\n #Runs when indicated by init or update\r\n def reset(self):\r\n self.direction = RIGHT\r\n self.snake = START\r\n \r\n \r\n \r\n \r\n #Runs repeatedly, as indicated by init. Manages game logic\r\n def update(self):\r\n self.update_direction()\r\n self.update_snake()\r\n self.update_color()\r\n\r\n if pyxel.btnp(pyxel.KEY_R):\r\n self.background()\r\n \r\n #Updates direction on button press\r\n def update_direction(self):\r\n \r\n if pyxel.btn(pyxel.KEY_UP):\r\n self.direction = UP\r\n elif pyxel.btn(pyxel.KEY_DOWN):\r\n self.direction = DOWN\r\n elif pyxel.btn(pyxel.KEY_LEFT):\r\n self.direction = LEFT\r\n elif pyxel.btn(pyxel.KEY_RIGHT):\r\n self.direction = RIGHT\r\n else:\r\n self.direction = IDLE\r\n \r\n #Updates position according to direction \r\n def update_snake(self):\r\n \r\n if self.direction is not IDLE: #Avoids update if no button is pressed\r\n #Movement\r\n old_head = self.snake\r\n new_head = Point(old_head.x + self.direction.x, old_head.y + self.direction.y)\r\n #Border control\r\n if new_head.x > 31:\r\n new_head = Point(new_head.x - 32, new_head.y)\r\n elif new_head.x < 0:\r\n new_head = Point(new_head.x + 32, new_head.y)\r\n elif new_head.y > 31:\r\n new_head = Point(new_head.x, new_head.y - 32)\r\n elif new_head.y < 0:\r\n new_head = Point(new_head.x, new_head.y + 32)\r\n #New position \r\n self.snake = new_head\r\n \r\n #Update player1 info\r\n p1 = open(\"Player1.txt\", \"w\")\r\n p1.write(str(self.snake.x) + \" \" + str(self.snake.y) + \" \" + str(SELECTEDCOL))\r\n p1.close\r\n \r\n #Changes selected color on button press\r\n def update_color(self):\r\n global SELECTEDCOL\r\n if pyxel.btn(pyxel.KEY_E):\r\n SELECTEDCOL = SELECTEDCOL + 1\r\n if SELECTEDCOL > 15:\r\n SELECTEDCOL = 0\r\n #Update player1 info\r\n p1 = open(\"Player1.txt\", \"w\")\r\n p1.write(str(self.snake.x) + \" \" + str(self.snake.y) + \" \" + str(SELECTEDCOL))\r\n p1.close\r\n \r\n #Clears and changes background color on button press\r\n def background(self):\r\n if pyxel.btn(pyxel.KEY_R):\r\n file = open(\"Board.txt\", \"r\") # open file for reading\r\n var = [] # initialize empty array\r\n for line in file:\r\n var.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array\r\n # thus creating an array of arrays.\r\n file.close() # close file.\r\n \r\n \r\n for i in range(0,32):\r\n for j in range(0,32):\r\n var[i][j] = str(SELECTEDCOL)\r\n with open(\"Board.txt\", \"w\") as txt_file:\r\n for line in var:\r\n txt_file.write(\" \".join(line) + \"\\n\")\r\n txt_file.close\r\n \r\n \r\n \r\n \r\n\r\n #Runs repeatedly, as indicated by init. Manages game graphics\r\n def draw(self):\r\n pyxel.cls(col=7)\r\n self.draw_snake()\r\n self.draw_board()\r\n \r\n #Shows player position and color\r\n def draw_snake(self):\r\n pyxel.pset(self.snake.x, self.snake.y, col=SELECTEDCOL)\r\n \r\n #Draws board\r\n def draw_board(self):\r\n #Read board\r\n file = open(\"Board.txt\", \"r\") # open file for reading\r\n var = [] # initialize empty array\r\n for line in file:\r\n var.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array\r\n # thus creating an array of arrays.\r\n file.close() # close file.\r\n \r\n #Paint on board\r\n if pyxel.btn(pyxel.KEY_W):\r\n var[self.snake.x][self.snake.y] = str(SELECTEDCOL)\r\n with open(\"Board.txt\", \"w\") as txt_file:\r\n for line in var:\r\n txt_file.write(\" \".join(line) + \"\\n\")\r\n txt_file.close\r\n \r\n #Read player2 info\r\n p2 = open(\"Player2.txt\", \"r\") # open file for reading\r\n p2info = [] # initialize empty array\r\n for line in p2:\r\n p2info.append(line.strip().split(' ')) # split each line on the <space>, and turn it into an array\r\n # thus creating an array of arrays.\r\n p2.close() # close file.\r\n var[int(p2info[0][0])][int(p2info[0][1])] = str(p2info[0][2]) \r\n \r\n #Show board\r\n for i in range(0,32):\r\n for j in range(0,32):\r\n if i is not self.snake.x or j is not self.snake.y:\r\n pyxel.pset(i,j,var[i][j])\r\n \r\n \r\n \r\n \r\ndrawer()","sub_path":"pyxel-port/drawer0.5p1.py","file_name":"drawer0.5p1.py","file_ext":"py","file_size_in_byte":6447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"118585487","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 12 14:42:06 2020\n\n@author: YasmineMnb\n\"\"\"\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport time\nimport datetime\nimport pandas as pd\n\ndef load_simp_file(file_path):\n time_arr = [] ; temp = []; hum = []\n cnt = 0\n with open (file_path,\"r\") as input_file:\n line = input_file.readline().strip().split(\",\")\n currr_t = float(line[2])\n for line in input_file:\n line = line.strip().split(\",\")\n temp.append(float(line[0]))\n hum.append(float(line[1]))\n # if float(line[2])/1000/3600 +11>24:\n # time.append(11+float(line[2])/1000/3600-24)\n # else: time.append(11+float(line[2])/1000/3600)\n if float(line[2])<currr_t:\n # print(cnt)\n currr_t = float(line[2]) + max_t\n else:\n currr_t = float(line[2])\n max_t = currr_t\n time_arr.append(currr_t)\n cnt+=1\n time_arr = np.array(time_arr)\n temp = np.array(temp)\n hum = np.array(hum)\n return time_arr, temp, hum\n\ndef load_simp_file_from_pi(file_path):\n time_arr = [] ; temp = []; hum = []\n with open (file_path,\"r\") as input_file:\n header_line = input_file.readline().strip().split(\",\")\n for line in input_file:\n line = input_file.readline().strip().split(\",\")\n for i in range(len(line)):\n line[i] = line[i].strip(\"\\t\")\n hum.append(float(line[0]))\n temp.append(float(line[1]))\n time_elem = time.mktime(time.strptime(line[2], '%Y/%m/%d-%H:%M'))\n time_arr.append(datetime.datetime.fromtimestamp(time_elem))\n return time_arr; temp; hum\n\n\ndef load_exp_file(file_path, arduino_start_time):\n #%\n file_path_clean = file_path.strip(\".txt\") + \"_cleaned.txt\"\n with open(file_path_clean, \"w\") as out:\n with open(file_path, \"r\") as file:\n for line in file:\n if len(line.split(\",\"))==7:\n out.write(line)\n df = pd.read_csv(file_path_clean)\n df.columns = [\"temp\", \"hum\", \"s1\",\"s2\",\"s3\",\"s4\", \"millis\"]\n #%\n ## add datetime formated time\n time_str_arr = []\n for i, t in enumerate(df[\"millis\"]):\n time_ep = convert_millis_time(arduino_start_time, t)\n time_str_arr.append(datetime.datetime.fromtimestamp(time_ep))\n time_str_arr = np.array(time_str_arr)\n df = df.astype(float)\n df[\"datetime\"] = time_str_arr\n #%\n return df\n\ndef convert_millis_time(arduino_start_time, time_millis):\n \"\"\"\n convert time from arduino-time to time-since-epoch, given a start time\n arduino_start_time format - 20-05-17 10:44\n \"\"\"\n start_time = time.strptime(arduino_start_time, '%y-%m-%d %H:%M')\n epoch_start_time = time.mktime(start_time)\n time_sec = time_millis/1000\n return int(epoch_start_time + time_sec)\n\ndef convert_to_datetime(arduino_start_time, millis_time_array):\n time_str_arr = []\n for i, t in enumerate(millis_time_array):\n time_ep = convert_millis_time(arduino_start_time, t)\n time_str_arr.append(datetime.datetime.fromtimestamp(time_ep))\n return np.array(time_str_arr)\n#%%\ndef load_ophir_log_file(file_path = r\"C:\\Users\\YasmineMnb\\Desktop\\june exp\\ophir_flicker_test\\1(L)\\200618_ophir_testing_flicker_clean_data.txt\"):\n #%%\n with open(file_path, \"r\") as input_file:\n for line in input_file:\n line = line.strip()\n print(line.split(\"\\t\"))\n break\n #%%\n file_path = r\"C:\\Users\\YasmineMnb\\Desktop\\june exp\\200624_contin\\ophir_clean.txt\"\n df = pd.read_csv(file_path, delimiter=\"\\t\")\n plt.plot(df[df.columns[0]], df[df.columns[1]])\n\n#%%\ntime_arr, temp, hum = load_simp_file(file_path = r\"C:\\Users\\YasmineMnb\\Desktop\\logs\\temp_log200525-1204.txt\")\narduino_start_time = \"20-05-20 09:07\"\ndt_time = convert_to_datetime(arduino_start_time, time_arr)\n#%%\narduino_start_time = \"20-06-16 11:28\"\n#170520_0857\nfile_path = r\"C:\\Users\\YasmineMnb\\Desktop\\june exp\\200616_contin\\1606.TXT\"\ndf = load_exp_file(file_path, arduino_start_time)\n\n#%% ploting\n# =============================================================================\n#\n# max_temp = np.where(temp == temp.max())[0]\n# max_temp_clean_indx = np.array([max_temp[0]])\n# for i in range(1, len(max_temp)):\n# if max_temp[i]-max_temp[i-1] >1:\n# max_temp_clean_indx= np.append(max_temp_clean_indx, max_temp[i])\n#\n# min_temp = np.where(temp == temp.min())[0]\n# min_temp_clean_indx = np.array([min_temp[0]])\n# for i in range(1, len(max_temp)):\n# if max_temp[i]-max_temp[i-1] >1:\n# max_temp_clean_indx= np.append(max_temp_clean_indx, max_temp[i])\n#\n# =============================================================================\n\n #[\"temp\", \"hum\", \"s1\",\"s2\",\"s3\",\"s4\", \"millis\", \"datetime\"]\n\n## ploting\nfig = plt.figure()\nax1 = plt.subplot(211)\nax2 = plt.subplot(212)\n\n## add data\nax1.plot(df[\"datetime\"][::10], df[\"s1\"][::10], label = \"sensor1\")#, alpha = 0.9 )\nax1.plot(df[\"datetime\"][::10], df[\"s2\"][::10], label = \"sensor2\")#, alpha = 0.9 )\nax1.plot(df[\"datetime\"][::10], df[\"s3\"][::10], label = \"sensor3\")#, alpha = 0.9 )\nax1.plot(df[\"datetime\"][::10], df[\"s4\"][::10], label = \"sensor4\")#, alpha = 0.9 )\n\nax2.plot(df[\"datetime\"], df[\"temp\"], label = \"temp\")#, alpha = 0.9 )\n#ax1.plot(time, hum, label = \"hum\")#, alpha = 0.9 )\n\n## titles and \"design\"\nplt.xlabel('Time [H]') # $_{[H]}$for subscript\nplt.ylabel('temp [C]')\nplt.title('Temp Vs. Time')\n#plt.legend(loc='upper left', bbox_to_anchor=(1.0, 1.0))\nax1.legend()\n#plt.subplots_adjust(left=0.1, bottom=0.10, right=0.70, top=0.92, wspace=0.2, hspace=0)\nplt.gcf().autofmt_xdate()\nplt.show()\n#%%\n\n\n\n\n\n","sub_path":"temp and sensor plot.py","file_name":"temp and sensor plot.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"633699768","text":"#5.To find reverse of number.\nnum=int(input('Enter number '))\nrev=0\nwhile(num>0):\n digit=num%10\n rev=digit+(rev*10)\n num=num//10\nprint(\"Reverse number : \",rev)\n\n\n","sub_path":"Semester_5/Python/Assignments/PR2_201806100110094/PR2_5.py","file_name":"PR2_5.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"626546831","text":"from Modules import Merger\n\nclass CreateTranslocationPanelOfNormals(Merger):\n def __init__(self, module_id, is_docker=False):\n super(CreateTranslocationPanelOfNormals, self).__init__(module_id, is_docker)\n \n # Add output keys here if needed\n self.output_keys = [\"pon\", \"full_pon\"]\n\n\n def define_input(self):\n self.add_argument(\"all_translocations\", is_required=True)\n self.add_argument(\"merge_distance\", default_value=10)\n self.add_argument(\"min_reads\", default_value=10)\n self.add_argument(\"min_samples\", default_value=5)\n self.add_argument(\"nr_cpus\", default_value=2)\n self.add_argument(\"mem\", default_value=10.0)\n\n def define_output(self):\n # FILE NAME IN ALL MERGERS DEPENDS ON THIS: CHANGE WITH CAUTION\n pon = self.generate_unique_file_name(\"filtered.pon.tsv\")\n full_pon = self.generate_unique_file_name(\"unfiltered.pon.tsv\")\n self.add_output(\"pon\", pon)\n self.add_output(\"full_pon\", full_pon)\n\n\n def define_command(self):\n # Get input\n vcf_list = self.get_argument(\"all_translocations\")\n merge_distance = self.get_argument(\"merge_distance\")\n min_reads = self.get_argument(\"min_reads\")\n min_samples = self.get_argument(\"min_samples\")\n\n # Get output\n filtered_pon = self.get_output(\"pon\")\n unfiltered_pon = self.get_output(\"full_pon\")\n \n \n # Start creating command\n cmd = \"Rscript create_translocation_pon.R\"\n\n # Create a comma-separated list of input files\n if isinstance(vcf_list, list):\n cmd += \" -i {0}\".format(','.join(vcf_list))\n else:\n cmd += \" -i {0}\".format(vcf_list)\n\n # Add arguments and outputs\n cmd += \" -u {0} -f {1} -d {2} -n {3} -r {4}\".format(unfiltered_pon,\n filtered_pon, merge_distance, min_samples, min_reads)\n\n # Add logging\n cmd += \" !LOG3!\"\n\n return cmd\n\n","sub_path":"Modules/Mergers/TranslocationPONMerger.py","file_name":"TranslocationPONMerger.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"490339528","text":"#!/usr/bin/env python3\n\"\"\"\nYou are given coins of different denominations and a total amount of money\namount. Write a function to compute the fewest number of coins that you need to\nmake up that amount. If that amount of money cannot be made up by any\ncombination of the coins, return -1.\n\nEXAMPLES:\n Input: coins = [1, 2, 5], amount = 11\n Output: 3 \n Explanation: 11 = 5 + 5 + 1\n\n Input: coins = [2], amount = 3\n Output: -1\n\nNote:\n - You may assume that you have an infinite number of each kind of coin.\n - It may help to study the coin_change.py problem first.\n\nREFERENCE:\n - https://leetcode.com/problems/coin-change/ (Medium)\n - https://www.geeksforgeeks.org/coin-change-dp-7/\n - https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/?ref=lbp\n\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def coinChange_v1(self, coins: List[int], amount: int) -> int:\n \"\"\"Use a 1-D table to track the status. \n\n This is an improvement over v1.\n Time complexity is the same, O(nm). Yet it uses less space: O(n).\n\n Example (use a 2D table to show how the 1D table evolves with each coin).\n\n Input: coins = [1, 2, 5], amount = 11\n Output: 3 \n Explanation: 11 = 5 + 5 + 1\n\n | 1 2 5\n --+------------->\n 0 | 0 0 0 0\n 1 | -1 1 1 1\n 2 | -1 2 1 1\n 3 | -1 3 2 2\n 4 | -1 4 2 2\n 5 | -1 5 3 1\n 6 | -1 6 3 2\n 7 | -1 7 4 2\n 8 | -1 8 4 3\n 9 | -1 9 5 3\n 10 | -1 10 5 2\n 11 | -1 11 6 3\n V\n\n Input: coins = [2], amount = 2\n Output: -1 \n\n | 2 \n --+--------->\n 0 | 0 0\n 1 | -1 -1\n 2 | -1 1\n 3 | -1 -1\n\n \"\"\"\n\n # Build a table for tracking\n table = [0] + [-1] * amount\n\n # Process one coin at a time\n for j, c in enumerate(coins):\n for i in range(c, amount+1):\n # Increment the table value if this coin can contribute\n # to the current amount.\n x = table[i]\n y = table[i-c] + 1 if table[i-c] >= 0 else -1\n\n if x > 0 and y > 0:\n table[i] = min(x, y)\n elif x > 0:\n table[i] = x\n elif y > 0:\n table[i] = y\n\n return table[-1]\n\n def coinChange_v2(self, coins: List[int], amount: int) -> int:\n \"\"\"Use a 1-D table to track the status. \n\n Similar to v1, yet here we initialize the table to a MAX value.\n \"\"\"\n\n # Build a table for tracking\n MAX = amount + 1\n table = [0] + [MAX] * amount\n\n # Process one coin at a time\n for j, c in enumerate(coins):\n for i in range(c, amount+1):\n x = table[i-c] + 1 if table[i-c] != MAX else MAX\n y = table[i]\n table[i] = min(x, y)\n\n return table[-1] if table[-1] < MAX else -1\n\n def coinChange_v3(self, coins: List[int], amount: int) -> int:\n \"\"\"Get the optimal restul for each amount starting from 1.\n\n This is similar to v2, yet swaps the order of the double loop.\n \"\"\"\n # Build a table for tracking\n MAX = amount + 1\n table = [0] + [MAX] * amount\n\n # Build the optimal results from 1 to amount\n for i in range(1, amount+1):\n # Get the optimal results from each coin\n vals = [table[i-c] + 1 for c in coins if c <= i]\n # Select the best (smallest)\n table[i] = min(vals) if vals else MAX\n\n return table[-1] if table[-1] < MAX else -1\n\n\ndef main():\n test_data = [\n [[1, 2, 5], 11, 3],\n [[1, 2, 5, 9, 10], 18, 2],\n [[2], 3, -1],\n [[1, 2, 5], 17, 4],\n [[1, 2, 5], 100, 20],\n [[88, 227, 216, 96, 209, 172, 259], 6928, 27],\n ]\n\n sol = Solution()\n for coins, amount, ans in test_data:\n print(\"# Input = {}, {}. Ans = {}\".format(coins, amount, ans))\n print(\" Output = {}\".format(sol.coinChange_v1(coins, amount)))\n print(\" Output = {}\".format(sol.coinChange_v2(coins, amount)))\n print(\" Output = {}\".format(sol.coinChange_v3(coins, amount)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3/dynamic_programming/min_coin_change.py","file_name":"min_coin_change.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"437163004","text":"# **************************************** BINARY CODED GENETIC ALGORITHM *******************************************\r\n# *******************************************************************************************************************\r\n# NAME: Suraj Kiran Shah ROLL NO.: 204103334 DEPT.: Mechanical Engineering\r\n# *******************************************************************************************************************\r\nimport numpy as np\r\nimport random as rd\r\nimport math as math\r\nimport matplotlib.pyplot as plot\r\n\r\n# USER INPUT *********************************************************************************************************\r\nN = 100 # Population Size\r\naccuracy_X1 = 0.000001 # Desire accuracy level of x1\r\naccuracy_X2 = 0.000001 # Desire accuracy level of x2\r\nPc = 0.9 # Crossover Probability\r\nPm = 0.3 # Mutation Probability\r\nMax_Generation = 100\r\n\r\n# Geometric Constraints\r\nX1max = 0.5\r\nX1min = 0\r\nX2max = 0.5\r\nX2min = 0\r\n\r\n\r\n# FUNCTIONS **********************************************************************************************************\r\n# Objective Function\r\ndef fitness(x1, x2):\r\n return 1 / (1 + (x1 + x2 - 2 * x1 * x1 - x2 * x2 + x1 * x2))\r\n\r\n\r\n# Single pt and Multi pt Crossover Function\r\ndef single_pt_crossover(A, B, x):\r\n A_new = np.append(A[:x], B[x:])\r\n B_new = np.append(B[:x], A[x:])\r\n return A_new, B_new\r\n\r\n\r\ndef multi_pt_crossover(A, B, X):\r\n for i in X:\r\n A, B = single_pt_crossover(A, B, i)\r\n return A, B\r\n\r\n\r\n# Finding length of string *******************************************************************************************\r\ng = (X1max - X1min) / accuracy_X1\r\nl1 = math.ceil(math.log(g, 2))\r\nh = (X2max - X2min) / accuracy_X2\r\nl2 = math.ceil(math.log(h, 2))\r\nL = l1 + l2\r\n\r\n# Initializing a population of solution at random (Generation=0) *****************************************************\r\nG = []\r\nfor i in range(N):\r\n temp = []\r\n for j in range(L):\r\n temp.append(rd.randint(0, 1))\r\n G.append(temp)\r\n\r\n# *************************************************** MAIN PROGRAM ****************************************************\r\n# Initializing for plotting\r\nAvg_Fitness_List = []\r\nMax_Fitness_List = []\r\nMin_Fitness_List = []\r\nOptimal_Solution_List = []\r\nGeneration_List = []\r\n# Initializing for while loop\r\nGeneration = 0\r\n\r\nwhile Generation < Max_Generation:\r\n # REPRODUCTION ****************************************************************************************************\r\n # Finding Real Value of variables from coded string\r\n decoded = []\r\n real = []\r\n\r\n for i in range(N):\r\n temp = []\r\n for j in range(l1):\r\n temp.append(G[i][j])\r\n a = int(\"\".join(str(x) for x in temp), 2)\r\n temp = []\r\n for j in range(l2):\r\n temp.append(G[i][j + l1])\r\n b = int(\"\".join(str(x) for x in temp), 2)\r\n list1 = [a, b]\r\n decoded.append(list1)\r\n\r\n for i in range(N):\r\n a = X1min + (X1max - X1min) * (decoded[i][0]) / (pow(2, l1) - 1)\r\n b = X2min + (X2max - X2min) * (decoded[i][1]) / (pow(2, l2) - 1)\r\n list1 = [a, b]\r\n real.append(list1)\r\n\r\n # Calculating fitness value of generation\r\n Fitness = [0] * N\r\n for i in range(N):\r\n Fitness[i] = fitness(real[i][0], real[i][1])\r\n\r\n # Finding maximum, minimum and average fitness value of generation\r\n Sum_Fitness = sum(Fitness)\r\n Avg_Fitness = Sum_Fitness / N\r\n Avg_Fitness_List.append(Avg_Fitness)\r\n\r\n Max_Fitness = max(Fitness)\r\n Max_Fitness_List.append(Max_Fitness)\r\n\r\n Min_Fitness = min(Fitness)\r\n Min_Fitness_List.append(Min_Fitness)\r\n\r\n # Finding optimal solution of generation\r\n j = Fitness.index(min(Fitness))\r\n Optimal_Solution = real[j]\r\n Optimal_Solution_List.append(Optimal_Solution)\r\n\r\n # Roulette Wheel: Selection of Mating Pool\r\n Probability = [0] * N\r\n\r\n for i in range(N):\r\n Probability[i] = Fitness[i] / Sum_Fitness\r\n\r\n Cum_Probability = [sum(Probability[0:x:1]) for x in range(0, N + 1)]\r\n\r\n Selection = []\r\n Mating_Pool = []\r\n\r\n for i in range(N):\r\n r = rd.uniform(0, 1)\r\n for j in range(N):\r\n if r > Cum_Probability[j] and r <= Cum_Probability[j+1]:\r\n temp = j\r\n break\r\n Selection.append(temp)\r\n\r\n for i in range(N):\r\n temp = []\r\n temp = G[Selection[i]]\r\n Mating_Pool.append(temp)\r\n\r\n # CROSSOVER *******************************************************************************************************\r\n # Randomly selecting mating pairs for crossover\r\n Mating_Pairs = []\r\n Solution_Number = list(range(0, N))\r\n for i in range(int(N / 2)):\r\n a = rd.choice(Solution_Number)\r\n Solution_Number.remove(a)\r\n b = rd.choice(Solution_Number)\r\n Solution_Number.remove(b)\r\n temp = [a, b]\r\n Mating_Pairs.append(temp)\r\n\r\n # Crossover Process\r\n Children_Solution = []\r\n Crossover_Site = list(range(1, L))\r\n\r\n for i in range(int(N / 2)):\r\n r = rd.uniform(0, 1)\r\n if r <= Pc:\r\n a = rd.sample(Crossover_Site, 2)\r\n a.sort()\r\n M1 = Mating_Pool[Mating_Pairs[i][0]]\r\n M2 = Mating_Pool[Mating_Pairs[i][1]]\r\n A, B = multi_pt_crossover(M1, M2, a)\r\n Mating_Pool[Mating_Pairs[i][0]] = A.tolist()\r\n Mating_Pool[Mating_Pairs[i][1]] = B.tolist()\r\n\r\n Children_Solution = Mating_Pool\r\n\r\n # MUTATION ********************************************************************************************************\r\n for i in range(N):\r\n for j in range(L):\r\n r = rd.uniform(0, 1)\r\n if r <= Pm:\r\n if Children_Solution[i][j] == 0:\r\n Children_Solution[i][j] = 1\r\n else:\r\n Children_Solution[i][j] = 0\r\n\r\n # SURVIVOR OF THE FITTEST *****************************************************************************************\r\n Clubbed_G = G + Children_Solution\r\n\r\n # Finding Real Value of variables from coded string\r\n decoded = []\r\n real1 = []\r\n\r\n for i in range(2 * N):\r\n temp = []\r\n for j in range(l1):\r\n temp.append(Clubbed_G[i][j])\r\n a = int(\"\".join(str(x) for x in temp), 2)\r\n temp = []\r\n for j in range(l2):\r\n temp.append(Clubbed_G[i][j + l1])\r\n b = int(\"\".join(str(x) for x in temp), 2)\r\n list1 = [a, b]\r\n decoded.append(list1)\r\n\r\n for i in range(2 * N):\r\n a = X1min + (X1max - X1min) * (decoded[i][0]) / (pow(2, l1) - 1)\r\n b = X2min + (X2max - X2min) * (decoded[i][1]) / (pow(2, l2) - 1)\r\n list1 = [a, b]\r\n real1.append(list1)\r\n\r\n # Calculating fitness value of Clubbed Generation\r\n Fitness_Clubbed_G = [0] * (2 * N)\r\n for i in range(2 * N):\r\n Fitness_Clubbed_G[i] = fitness(real1[i][0], real1[i][1])\r\n\r\n # Making generation with best fitness value\r\n G_New = [[0] * L] * N\r\n for i in range(N):\r\n j = Fitness_Clubbed_G.index(max(Fitness_Clubbed_G))\r\n G_New[i] = Clubbed_G[j]\r\n Fitness_Clubbed_G[j] = 0\r\n\r\n G = G_New # Assigning new generated population to G for next iteration\r\n\r\n Generation += 1\r\n Generation_List.append(Generation)\r\n print(str(Generation) + \"\\t\" + str(Avg_Fitness))\r\n\r\n# ********************************************** END OF MAIN PROGRAM *************************************************\r\n\r\n# PLOTTING OF GRAPHS *************************************************************************************************\r\n# Plotting of Fitness Value Vs Generation\r\nplot.cla()\r\nplot.plot(Generation_List, Max_Fitness_List, linewidth=2, label='Maximum Fitness')\r\nplot.plot(Generation_List, Avg_Fitness_List, linewidth=2, label='Average Fitness')\r\nplot.plot(Generation_List, Min_Fitness_List, linewidth=2, label='Minimum Fitness')\r\n\r\nplot.title('Fitness value v/s Generation')\r\nplot.xlabel('Generation')\r\nplot.ylabel('Fitness Value')\r\nplot.legend(loc='right')\r\nplot.tight_layout()\r\nplot.show()\r\n\r\n# Plotting of last generation solution\r\nreal = np.asarray(real)\r\nfor i in range(N):\r\n plot.scatter(real[i][0], real[i][1], color='blue')\r\nplot.title('X1 X2 values for last generation')\r\nplot.xlabel('Value of X1')\r\nplot.ylabel('Value of X2')\r\nplot.show()\r\n\r\n# Plotting of Optimal Solution Vs Generation\r\nOptimal_Solution_List = np.asarray(Optimal_Solution_List)\r\nplot.plot(Generation_List, Optimal_Solution_List[:, 0], linewidth=2, label='X1')\r\nplot.plot(Generation_List, Optimal_Solution_List[:, 1], linewidth=2, label='X2')\r\nplot.scatter(Generation_List, Optimal_Solution_List[:, 0], marker=\"o\", linewidth=0)\r\nplot.scatter(Generation_List, Optimal_Solution_List[:, 1], marker=\"o\", linewidth=0)\r\nplot.title('Optimal Solution v/s Generation')\r\nplot.xlabel('Generation')\r\nplot.ylabel('Optimal Solution')\r\nplot.legend(loc='right')\r\nplot.tight_layout()\r\nplot.show()\r\n\r\n# ********************************************************************************************************************","sub_path":"Genetic Algorithm Code.py","file_name":"Genetic Algorithm Code.py","file_ext":"py","file_size_in_byte":9086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"349030289","text":"#! /usr/bin/env python3\n\"\"\"\npfxscan - scan for advertising Bluetooth PFx Bricks\n\"\"\"\nimport argparse\nimport asyncio\nfrom datetime import datetime\n\nfrom rich import print\nfrom rich.console import Console\nfrom rich.table import Table\n\nfrom pfxbrick import *\n\nconsole = Console()\n\n\nasync def brick_session(uuid, timeout=15):\n b = PFxBrickBLE(uuid=uuid)\n await b.open(timeout=timeout)\n icd = await b.get_icd_rev()\n await b.get_status()\n\n if b.status == 0x00:\n name = await b.get_name()\n else:\n name = \"Service Mode\"\n table = Table(show_header=True, header_style=\"bold blue\")\n bid = \"[light_slate_blue]%s [bold cyan]%s\" % (b.product_id, b.product_desc)\n table.add_column(bid, width=72)\n table.add_row(\"Bluetooth UUID : [bold orange3]%s\" % (uuid))\n table.add_row(\"Serial Number : [bold cyan]%s\" % (b.serial_no))\n table.add_row(\"ICD Version : [bold green]%s\" % (icd))\n table.add_row(\n \"Firmware Version : [bold green]%s [reset]build [bold green]%s\"\n % (b.firmware_ver, b.firmware_build)\n )\n table.add_row(\n \"Status : 0x%02X %s\" % (b.status, get_status_str(b.status))\n )\n if b.error:\n table.add_row(\n \"Errors : [red]0x%02X %s\" % (b.error, get_error_str(b.error))\n )\n else:\n table.add_row(\n \"Errors : [green]0x%02X %s\"\n % (b.error, get_error_str(b.error))\n )\n table.add_row(\"Name : [bold yellow]%s\" % (name))\n r = await b.get_rssi()\n table.add_row(\"RSSI : %s dBm\" % (r))\n console.print(table)\n await b.close()\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Scan for PFx Bricks advertising on Bluetooth\"\n )\n parser.add_argument(\n \"-s\",\n \"--scantime\",\n default=10,\n help=\"Time interval (seconds) to scan for advertising PFx Bricks, default=10\",\n )\n parser.add_argument(\n \"-t\",\n \"--timeout\",\n default=15,\n help=\"Timeout interval (seconds) to wait while connecting to a PFx Brick, default=15\",\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"store_true\",\n default=False,\n help=\"Show verbose output from scanning\",\n )\n args = parser.parse_args()\n argsd = vars(args)\n\n loop = asyncio.new_event_loop()\n pfxdevs = []\n with console.status(\"Scanning...\") as status:\n pfxdevs = loop.run_until_complete(\n ble_device_scanner(\n scan_timeout=float(argsd[\"scantime\"]),\n silent=not argsd[\"verbose\"],\n verbose=argsd[\"verbose\"],\n )\n )\n print(\"Found %d PFx Bricks\" % (len(pfxdevs)))\n if len(pfxdevs) > 0:\n for d in pfxdevs:\n with console.status(\n \"Connecting to [bold orange3]%s[/]...\" % (d.address)\n ) as status:\n loop.run_until_complete(\n brick_session(d.address, timeout=float(argsd[\"timeout\"]))\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pfxbrick/scripts/pfxscan.py","file_name":"pfxscan.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"51251870","text":"import shutil\nfrom pathlib import Path\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport collections\n\n\ndef LoadFormantData():\n df = pd.read_csv(input_base_dir / 'normalized.csv')\n return df\n\n\ndef WriteLangWordCsv(df, output_dir, target_lang, target_word):\n matched_rows = []\n for _, row in df.iterrows():\n comps = row['Filename'].split('_')\n lang = comps[0]\n word = comps[3]\n pos = comps[4]\n if lang == target_lang and int(word) == target_word and pos == 'b':\n matched_rows.append(row)\n mdf = pd.DataFrame(matched_rows)\n output_df = mdf[['Filename', 'Annotation', 'breakF1', 'breakF2', 'deltaF1', 'deltaF2', 'delta_barkF1', 'delta_barkF2']]\n filename = target_lang + '_a_' + str(target_word) + '_b'\n output_df_csv = output_dir / (filename + '.CSV')\n print(output_df_csv)\n output_df.to_csv(output_df_csv, index=False)\n\n\ninput_base_dir = Path('./analysis/item_a/output/')\noutput_base_dir = Path('./analysis/output_per_word/')\nshutil.rmtree(output_base_dir, ignore_errors=True)\noutput_base_dir.mkdir(parents=True, exist_ok=True)\n\ndf_formant = LoadFormantData()\nLANGS = ['S', 'M', 'B']\nWORDS = [1,4,5,7,8,9,10,11,14]\nfor lang in LANGS:\n for word in WORDS:\n WriteLangWordCsv(df_formant, output_base_dir, lang, word)","sub_path":"analysis/per_word_delta_break.py","file_name":"per_word_delta_break.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"266028349","text":"# messages statuses\nSTATUS_MESSAGE_CREATED = 'created'\nSTATUS_MESSAGE_ON_MODERATION = 'moderation'\nSTATUS_MESSAGE_BLOCKED = 'spam'\nSTATUS_MESSAGE_APPROVED = 'approve'\nSTATUS_MESSAGE_READ = 'read'\n\n# roles\nUSER = 'user'\nWORKER = 'worker'\n\n# lists\nLIST_ACTION_LOGS = 'actions-logs'\n\n# sets\nONLINE_USERS_Z = 'online'\nBLOCKED_MESSAGES_Z = 'spam'\nAPPROVED_MESSAGES_Z = 'approved'\nACTIVE_SENDERS_Z = 'active'\nSPAMMERS_Z = 'top-spammers'\nDELIVERED_MESSAGES_Z = 'delivered-messages'\nREAD_MESSAGES_Z = 'read-messages'\nINCOMING_MESSAGES_Z = 'incoming_messages'\nWAIT_FOR_MODERATION_MESSAGES_Z = 'wait-for-moderation-messages'\nMESSAGES_ON_MODERATION_Z = 'on-moderation-messages'\nSENT_MESSAGES_Z = 'sent-messages'\n\n# sets\nSET_WAIT_FOR_MODERATION = 'moderation-list'\n\n# storage\nMESSAGES_STORAGE = 'messages'\nUSERS_STORAGE = 'users'\n\n# events\nMESSAGE_CREATED_EVENT = 'msg-created'\nMESSAGE_APPROVED_EVENT = 'message-approved'\nINCOMING_MESSAGE_EVENT = 'incoming-message'\nMESSAGE_BLOCKED_EVENT = 'blocked-message'\nMESSAGE_READ_EVENT = 'read-message'","sub_path":"Lab2_DB/chat/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"110269065","text":"\n\ndef read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1):\n try:\n f = open(filename, 'rb')\n creader = CSVReader(f, delimiter=to_native(delimiter), encoding=encoding)\n for row in creader:\n if (len(row) and (row[0] == key)):\n return row[int(col)]\n except Exception as e:\n raise AnsibleError(('csvfile: %s' % to_native(e)))\n return dflt\n","sub_path":"Data Set/bug-fixing-2/0b3ed626b3157d4dd00b7368acb8fe0d69ac94ec-<read_csv>-fix.py","file_name":"0b3ed626b3157d4dd00b7368acb8fe0d69ac94ec-<read_csv>-fix.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"596461545","text":"from socket import *\nimport pyaes\n\nkey = \"key_is_python_AH\".encode()\n\naes = pyaes.AESModeOfOperationCTR(key)\n\nplain_text = \"this is golden\"\ncipher_text = aes.encrypt(plain_text)\nprint(cipher_text)\n\ns = socket(2,1)\ns.bind((\"127.0.0.1\",4444))\ns.listen(5)\n\nwhile True:\n c,addr = s.accept()\n c.send(cipher_text)\n\n\nc.close()\n","sub_path":"Pentest and Network/Socket/AES/aes_encrypte.py","file_name":"aes_encrypte.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"56764060","text":"import sys\nfrom collections import deque\n\n\ndq=deque()\n\nM,N=map(int,sys.stdin.readline().split())\n\ntomato=[[1 for i in range(N)]for i in range(M)]\n\ndx=[1,-1,0,0]\ndy=[0,0,1,-1]\n\n\ncount=0\ncount_arr=[]\nvisited=[[False for i in range(N)]for i in range(M)]\n\nfor i in range(N):\n temp=list(map(int,sys.stdin.readline().split()))\n for j in range(M):\n tomato[j][i]=temp[j]\n\n\ncount_p=0\ncount_c=0\nday=0\n\nfor i in range(M): #X\n for j in range(N): #Y\n if tomato[i][j]==1:\n count_p+=1\n dq.append((i, j))\n visited[i][j] = True\n\nwhile dq: #영역 전부 지우기\n for i in range(count_p):\n c_x,c_y=dq.popleft()\n for k in range(4):\n x=c_x+dx[k]\n y=c_y+dy[k]\n if 0<=x<M and 0<=y<N:\n if tomato[x][y]!=-1 and visited[x][y]==False: #-1만 아니면 방문\n tomato[x][y]=1\n dq.append((x,y))\n visited[x][y] =True\n count_c+=1\n if count_c!=0:\n day+=1\n count_p=count_c\n count_c=0\n\n\n\nfor i in range(M): #X\n for j in range(N): #Y\n if tomato[i][j]==0:\n print(-1)\n exit()\nprint(day)\n","sub_path":"Sanghyun-Park/baekjoon/7576.py","file_name":"7576.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"419915700","text":"# -*- coding: utf-8 -*-\nif 0:\n from gluon import *\n\nrequired_comment = SPAN('Required', _style='color:orange;')\n\ndb.define_table('workflow_template',\n Field('name', length=64, required=True, notnull=True),\n Field('originator', db.auth_user, requires=[\n IS_NOT_EMPTY(),\n IS_IN_DB(db(), 'auth_user.id',\n '%(first_name)s %(middle_name)s %(last_name)s %(generation)s'),\n ]),\n Field('comment', length=254),\n )\n\ndb.define_table('workflow_task',\n Field('workflow_template_id', db.workflow_template, requires=IS_IN_DB(db,\n 'workflow_template.id', '%(name)s')),\n Field('name', length=64, required=True, notnull=True),\n Field('objective', length=254,),\n Field('past_tense', length=64, required=True, notnull=True),\n Field('max_duration', 'decimal(6,2)',\n requires=IS_EMPTY_OR(IS_DECIMAL_IN_RANGE(0, None)),\n label = 'Maximum duration',\n comment = 'Considered late if takes longer. Optional',\n ),\n Field('max_duration_uom', requires=IS_EMPTY_OR(\n IS_IN_SET(['seconds', 'minutes',\n 'hours', 'days', 'weeks', 'months', 'years'])),\n default='hours'),\n ## allowed values should be dormant, blocked, running, complete,\n ## \n ## Not sure we should carry this here, or calculate via query\n Field('one_at_a_time', 'boolean', default=False, \n comment='Example: only one clothes dryer ' +\\\n 'means drying one load at a time.'\n )\n )\n\ndb.define_table('task_link',\n Field('predecessor_task_id', db.workflow_task, requires=IS_IN_DB(db,\n 'workflow_task.id', '%(name)s')),\n Field('successor_task_id', db.workflow_task, requires=IS_IN_DB(db,\n 'workflow_task.id', '%(name)s')),\n # possible values are trigger, pre-requisite, needed for exit\n Field('entry_or_exit', default='trigger', \n requires=IS_IN_SET([\n 'trigger', 'entry requirement', 'exit requirement'\n ])\n ),\n # possible values are 'not finished', 'not started', 'running',\n # 'failed'\n Field('block_if', default='not finished', \n requires=IS_IN_SET([\n 'not finished', 'not started', 'running', 'failed'\n ])\n ),\n )\n\ndb.define_table('task_user',\n Field('user_id', db.auth_user, 'auth_user.id', requires=IS_IN_DB(\n db, 'auth_user.id', \n '%(first_name)s %(middle_name)s %(last_name)s %(generation)s',\n zero=None,\n ),\n comment=required_comment,\n label='User name',\n ),\n Field('workflow_task_id', db.workflow_task, requires=IS_IN_DB(db,\n 'workflow_task.id', '%(name)s'),\n ),\n Field('user_role', requires=IS_IN_SET([\n 'Performer', 'Approver', 'Reviewer', 'Monitor', \n ], \n zero=None,\n ),\n comment=required_comment,\n ),\n Field('notify_on',\n requires=IS_IN_SET(\n ['Entry', 'Completion', 'Failure',],\n zero=None\n ),\n comment=required_comment,\n ),\n Field('can_edit_item', 'boolean', default=False),\n )\n\ndb.define_table('workflow',\n Field('workflow_template_id', db.workflow_template, \n requires=IS_IN_DB(\n db, 'workflow_template.id', '%(name)s', \n zero = 'Select a template',\n ),\n comment=SPAN('Required', _style='color:orange;'),\n ),\n Field('name', length=64, required=True, notnull=True,\n unique=True,\n requires = [\n IS_NOT_EMPTY(),\n IS_NOT_IN_DB(\n db, 'workflow.name',\n error_message = 'A workflow with this name already exists.'\n ),\n ],\n comment=SPAN('Required', _style='color:orange;'),\n default = '', label='Title',\n ),\n Field('originator', db.auth_user,\n comment=SPAN('Required', _style='color:orange;'),\n ),\n Field('comments', 'text'),\n Field('status', length=16, readable=False, writable=False),\n format = '%(name)s',\n )\ndb.workflow.originator.requires = IS_IN_DB(\n db, 'auth_user.id',\n '%(first_name)s %(middle_name)s %(last_name)s %(generation)s',\n zero = 'Select the originator.'\n)\n\ndb.define_table('workflow_history',\n Field('action', length=16),\n Field('workflow_id', db.workflow, requires=IS_IN_DB(db,\n 'workflow.id', '%(name)s'),),\n Field('user_id', db.auth_user, requires=IS_IN_DB(db,\n 'auth_user.id', \n '%(first_name)s %(middle_name)s %(last_name)s %(generation)s',),\n ),\n Field('workflow_task_id', db.workflow_task, requires=IS_IN_DB(\n db, 'workflow_task.id', '%(name)s',),\n ),\n Field('timestamp', 'datetime', default=request.now,),\n Field('event', length=64,),\n )\n\n\ndb.define_table('workflow_comment',\n Field('workflow_id', db.workflow, requires=IS_IN_DB(db,\n 'workflow.id', '%(name)s'),),\n Field('comment_body', 'text', length=5000,\n comment='Maximum length 5,000 characters.')\n )\n\ndb.define_table('workflow_task_instance',\n Field('workflow_id', db.workflow, requires=IS_IN_DB(\n db, 'workflow.id', '%(name)s'\n )\n ),\n Field('workflow_task_id', db.workflow_task, requires=IS_IN_DB(\n db, 'workflow_task.id', '%(name)s',\n ),\n ),\n Field('status', requires=IS_IN_SET([\n 'blocked', 'running', 'complete', 'failed', 'rejected'\n ]), default='blocked')\n )\n\ndb.define_table('workflow_task_instance_comment',\n Field('workflow_task_instance_id', db.workflow_task_instance,\n requires=IS_IN_DB(\n db, 'workflow_task_instance.id', '%(id)s')\n ),\n Field(\n 'comment', 'text', length=2000, \n comment=SPAN(\n 'Maximum length is 2000 characters.',\n BR(),\n SPAN('Required', _style='color:orange;')\n ),\n requires=IS_NOT_EMPTY(),\n required=True,\n notnull=True,\n )\n )\n \ndb.define_table('workflow_task_instance_history',\n Field('workflow_task_instance_id', db.workflow_task_instance,\n requires=IS_IN_DB(\n db, 'workflow_task_instance.id', '%(id)s')),\n Field('history_entry', length=254),\n )\n\ndb.define_table('workflow_attachment',\n Field('name', length=64, label='Document Title'),\n Field('workflow_id', db.workflow, requires=IS_IN_DB(\n db, 'workflow.id', '%(name)s', zero='Choice required.'\n )),\n Field(\n 'file', 'upload', uploadfield='file_data', required=True,\n requires=IS_NOT_EMPTY(),\n ),\n Field('file_data', 'blob', required=True, requires=IS_NOT_EMPTY()),\n format = '%(name)s'\n )\n \n","sub_path":"models/daaa.py","file_name":"daaa.py","file_ext":"py","file_size_in_byte":7208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"475241106","text":"S = input()\na, b, c = 0, 0, 0\n\nfor s in S:\n if s == \"a\":\n a += 1\n elif s == \"b\":\n b += 1\n else:\n c += 1\n\nmaxi = max(a, b, c)\n\nif maxi==a:\n print('a')\nelif maxi==b:\n print('b')\nelse:\n print('c')","sub_path":"atcoder/2020/Other/0418_PAST/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"256007946","text":"\"\"\"Time utilities\"\"\"\nimport datetime\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\nALLOWED_KEYS = (\n \"days\",\n \"seconds\",\n \"microseconds\",\n \"milliseconds\",\n \"minutes\",\n \"hours\",\n \"weeks\",\n)\n\n\ndef timedelta_string_validator(value: str):\n \"\"\"Validator for Django that checks if value can be parsed with `timedelta_from_string`\"\"\"\n try:\n timedelta_from_string(value)\n except ValueError as exc:\n raise ValidationError(\n _(\"%(value)s is not in the correct format of 'hours=3;minutes=1'.\"),\n params={\"value\": value},\n ) from exc\n\n\ndef timedelta_from_string(expr: str) -> datetime.timedelta:\n \"\"\"Convert a string with the format of 'hours=1;minute=3;seconds=5' to a\n `datetime.timedelta` Object with hours = 1, minutes = 3, seconds = 5\"\"\"\n kwargs = {}\n for duration_pair in expr.split(\";\"):\n key, value = duration_pair.split(\"=\")\n if key.lower() not in ALLOWED_KEYS:\n continue\n kwargs[key.lower()] = float(value)\n return datetime.timedelta(**kwargs)\n","sub_path":"passbook/lib/utils/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"316727775","text":"\nfrom artemis.test_mechanism import dataset, DataSet, set_scenario\nfrom artemis.tests.fixture import ArtemisTestFixture\nimport pytest\n\nxfail = pytest.mark.xfail\nCOVERAGE = \"guichet-unique\"\n\n\n@dataset([DataSet(COVERAGE)])\nclass GuichetUnique(object):\n \"\"\"\n \"\"\"\n def test_guichet_unique_caen_to_marseille(self):\n \"\"\"\n ID artemis v1: 0\n \"\"\"\n self.journey(_from=\"admin:fr:14118\",\n to=\"admin:fr:13055\", datetime=\"20120924T070000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_paris_to_rouen(self):\n \"\"\"\n ID artemis v1: 1\n \"\"\"\n self.journey(_from=\"admin:fr:75056\",\n to=\"admin:fr:76540\", datetime=\"20121012T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_caen_to_brest(self):\n \"\"\"\n ID artemis v1: 2\n \"\"\"\n self.journey(_from=\"admin:fr:14118\",\n to=\"admin:fr:29019\", datetime=\"20121022T054500\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\", count=\"7\", type=\"rapid\")\n\n def test_guichet_unique_reims_to_paris(self):\n \"\"\"\n ID artemis v1: 18\n \"\"\"\n self.journey(_from=\"admin:fr:51454\",\n to=\"admin:fr:75056\", datetime=\"20121020T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_avignon_to_marseille(self):\n \"\"\"\n ID artemis v1: 19\n \"\"\"\n self.journey(_from=\"admin:fr:84007\",\n to=\"admin:fr:13055\", datetime=\"20120928T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_paris_to_avignon(self):\n \"\"\"\n ID artemis v1: 20\n \"\"\"\n self.journey(_from=\"admin:fr:75056\",\n to=\"admin:fr:84007\", datetime=\"20121121T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_paris_to_ay(self):\n \"\"\"\n ID artemis v1: 21\n \"\"\"\n self.journey(_from=\"admin:fr:75056\",\n to=\"admin:fr:51030\", datetime=\"20121121T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"240\")\n\n def test_guichet_unique_paris_to_Avenay_Val_d_Or(self):\n \"\"\"\n ID artemis v1: 22\n \"\"\"\n self.journey(_from=\"admin:fr:75056\",\n to=\"admin:fr:51028\", datetime=\"20121025T120000\",\n walking_speed=\"0.83\", max_duration_to_pt=\"6000\")\n\n def test_too_long_waiting_filter(self):\n \"\"\"\n Test a journey from saint quentin -> saint just in the new_default scenario\n\n The query is late, and without filter we have 2 journeys\n\n * One where the traveller leaves at 20h19, sleeps at Amiens and arrive in the morning (6h22)\n * One where the traveller leaves at 7h22 and arrive at 9h14\n\n We don't want the first journey, so it is filtered and we should only have the second one\n\n linked to http://jira.canaltp.fr/browse/NAVITIAII-2000\n \"\"\"\n self.journey(_from=\"stop_area:OCE:SA:87296004\",\n to=\"stop_area:OCE:SA:87313270\", datetime=\"20121123T2019\",\n _override_scenario=\"new_default\")\n\n \"\"\"\n test RealTime on SNCF (COTS)\n \"\"\"\n def test_kirin_cots_trip_delay(self):\n \"\"\"\n Test delay on a train\n\n Requested departure: 2012/11/20 16:00:00\n From: gare de Strasbourg (Strasbourg)\n To: gare de Marseille-St-Charles (Marseille)\n\n Before the delay, the train travels from 16:12:00 to 21:46:00\n After the delay, the train travels from 16:12:00 to 22:16:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_delay_9580_tgv.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE)\n\n self.journey(_from=\"stop_area:OCE:SA:87212027\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121120T160000\",\n data_freshness=\"realtime\")\n\n self.journey(_from=\"stop_area:OCE:SA:87212027\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121120T160000\",\n data_freshness=\"base_schedule\")\n\n def test_kirin_cots_trip_removal(self):\n \"\"\"\n Test removal of a train\n\n Requested departure: 2012/12/16 17:30:00\n From: gare de Bordeaux-St-Jean (Bordeaux)\n To: gare de Marseille-St-Charles (Marseille)\n\n Before the removal, a train (headsign: 4669) travels on 2012/12/16 from 17:31:00 to 23:46:00\n After the removal, an other train (headsign: 4655) travels on 2012/12/17 from 06:45:00 to 12:59:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_removal_4669_ic.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE) \n\n self.journey(_from=\"stop_area:OCE:SA:87581009\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121216T173000\",\n data_freshness=\"realtime\")\n\n self.journey(_from=\"stop_area:OCE:SA:87581009\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121216T173000\",\n data_freshness=\"base_schedule\")\n\n def test_kirin_cots_trip_deleted_partially(self):\n \"\"\"\n Test removal of some stops of a vj\n\n Requested departure: 2012/11/19 12:36:00\n From: gare de Avignon-TGV (Avignon)\n To: gare de Marseille-St-Charles (Marseille)\n\n Before the removal of the stops, a train (headsign: 5312/5358) travels from 12:39:00 to 13:14:00\n After the removal of the departure stop, an other train (headsign: 5101) travels from 13:11:00 to 13:48:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_partially_deleted_5312_tgv.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE)\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_partially_deleted_5358_tgv.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE) \n\n self.journey(_from=\"stop_area:OCE:SA:87318964\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121119T123600\",\n data_freshness=\"realtime\")\n\n self.journey(_from=\"stop_area:OCE:SA:87318964\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121119T123000\",\n data_freshness=\"base_schedule\") \n\n def test_kirin_cots_trip_observed_delay_passe_minuit(self):\n \"\"\"\n Test delay of a train which arrival is the day after the departure\n\n Requested departure: 2012/12/16 22:30:00\n From: gare de Paris-Nord (Paris)\n To: gare de St Quentin (Saint-Quentin)\n\n Before the delay, the train travels from 2012/12/16 22:37:00 to 2012/12/17 00:16:00\n After the delay, the train travels from 2012/12/16 22:37:00 to 2012/12/17 00:41:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_observed_delay_passe_minuit_847919_ter.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE) \n\n self.journey(_from=\"stop_area:OCE:SA:87271007\",\n to=\"stop_area:OCE:SA:87296004\",\n datetime=\"20121216T223000\",\n data_freshness=\"realtime\")\n\n self.journey(_from=\"stop_area:OCE:SA:87271007\",\n to=\"stop_area:OCE:SA:87296004\",\n datetime=\"20121216T223000\",\n data_freshness=\"base_schedule\") \n\n def test_kirin_cots_trip_departure_delayed_pass_midnight(self):\n \"\"\"\n Test delay of a train with a departure without delay before midnight,\n then a departure after midnight with the delay\n\n Requested departure: 2012/12/16 23:40:00\n From: gare de Noyon (Noyon)\n To: gare de St Quentin (Saint-Quentin)\n\n Before the delay, the train travels from 2012/12/16 23:44:00 to 2012/12/17 00:16:00\n After the delay, the train travels from 2012/12/17 00:09:00 to 2012/12/17 00:41:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_observed_delay_passe_minuit_847919_ter.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE)\n\n self.journey(_from=\"stop_area:OCE:SA:87276782\",\n to=\"stop_area:OCE:SA:87296004\",\n datetime=\"20121216T234000\",\n data_freshness=\"realtime\")\n\n self.journey(_from=\"stop_area:OCE:SA:87276782\",\n to=\"stop_area:OCE:SA:87296004\",\n datetime=\"20121216T234000\",\n data_freshness=\"base_schedule\")\n\n def test_kirin_cots_reload_from_scratch(self):\n \"\"\"\n Test removal of a train\n\n Requested departure: 2012/12/16 17:30:00\n From: gare de Bordeaux-St-Jean (Bordeaux)\n To: gare de Marseille-St-Charles (Marseille)\n\n Before the removal, a train (headsign: 4669) travels on 2012/12/16 from 17:31:00 to 23:46:00\n After the removal, an other train (headsign: 4655) travels on 2012/12/17 from 06:45:00 to 12:59:00\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n self.send_cots('trip_delay_9580_tgv.json')\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE)\n\n self.journey(_from=\"stop_area:OCE:SA:87212027\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121120T160000\",\n data_freshness=\"realtime\")\n\n \"\"\"\n At this point, the COTS feed is saved into the db,\n now the kraken is run from scratch and the previous COTS feed should be taken into account\n \"\"\"\n last_rt_data_loaded = self.get_last_rt_loaded_time(COVERAGE)\n\n self.kill_the_krakens()\n self.pop_krakens()\n\n self.wait_for_rt_reload(last_rt_data_loaded, COVERAGE)\n\n self.journey(_from=\"stop_area:OCE:SA:87212027\",\n to=\"stop_area:OCE:SA:87751008\",\n datetime=\"20121120T160000\",\n data_freshness=\"realtime\")\n\n\n@set_scenario({COVERAGE: {\"scenario\": \"default\"}})\nclass TestGuichetUniqueDefault(GuichetUnique, ArtemisTestFixture):\n pass\n\n\n@set_scenario({COVERAGE: {\"scenario\": \"new_default\"}})\nclass TestGuichetUniqueNewDefault(GuichetUnique, ArtemisTestFixture):\n @xfail(reason=\"Unsupported new_default scenario!\", raises=AssertionError)\n def test_guichet_unique_caen_to_marseille(self):\n super(TestGuichetUniqueNewDefault, self).test_guichet_unique_caen_to_marseille()\n\n\n@set_scenario({COVERAGE: {\"scenario\": \"experimental\"}})\nclass TestGuichetUniqueExperimental(GuichetUnique, ArtemisTestFixture):\n @xfail(reason=\"Unsupported experimental scenario!\", raises=AssertionError)\n def test_guichet_unique_caen_to_marseille(self):\n super(TestGuichetUniqueExperimental, self).test_guichet_unique_caen_to_marseille()\n","sub_path":"artemis/tests/guichet_unique_test.py","file_name":"guichet_unique_test.py","file_ext":"py","file_size_in_byte":11292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"391807807","text":"import urllib.request\r\nimport json\r\nimport os\r\nimport time\r\nfrom api import api, admintoken\r\nimport time, os\r\nimport pickle\r\nme = api()\r\nstart_time = time.time()\r\n#group = input('Группа для парса: ')\r\n\r\n\r\ndef check(x, r):\r\n return x['sex'] == r['sex']\\\r\n and 'city' in x and x['city']['id'] == r['city']\\\r\n and ('bdate' not in x or len(x['bdate']) <= 5 or (int(x['bdate'][-4:]) >= r['maxage'] and int(x['bdate'][-4:]) <= r['minage']))\r\n# if not os.path.exists('girls_%s.pickle' % group):\r\n\r\n\r\ndef find(request):\r\n output = []\r\n my_groups = {x['id']: x['name'] for x in me.users.getSubscriptions(user_id=request['id'], extended=1, count=200)['items'] if x['type'] == 'page'}\r\n count = me.groups.getMembers(group_id=request['group'])['count']\r\n girls = []\r\n for i in range(0, count, 1000):\r\n girls.extend([x for x in me.groups.getMembers(group_id=request['group'], offset=i,\r\n fields=\"sex,photo_max_orig,domain,bdate,city,photo_id\")['items'] if check(x, request)])\r\n for g in range(len(girls)):\r\n subs = me.users.getSubscriptions(user_id=girls[g]['id'], count=200, extended=1)['items']\r\n girls[g]['groups'] = subs\r\n if (g+1) % 50 == 0 or g+1 == len(girls):\r\n print('Получена информация о %d из %d' % (g+1, len(girls)))\r\n print(\"В базе %d девушек\" % len(girls))\r\n index = 0\r\n for g in girls:\r\n appeal = []\r\n for s in g['groups']:\r\n if s['id'] in my_groups:\r\n appeal.append(my_groups[s['id']])\r\n if len(appeal) > 1:\r\n g['appeal'] = appeal\r\n output.append(g)\r\n index += 1\r\n if index % 10 == 0 or index == len(girls):\r\n print('Обработано %d из %d' % (index, len(girls)))\r\n output = sorted(output, key=lambda x: len(x['appeal']), reverse=True)\r\n return output\r\n\r\n\r\nif __name__ == \"__main__\":\r\n output = []\r\n target_link = input('Введите ссылку на свою страницу вида id*** или короткий адрес БЕЗ VK.COM: ')\r\n target = me.users.get(user_ids=target_link, fields='city')[0]\r\n for g in me.users.getSubscriptions(extended=1, count=200, user_id=target['id'])['items'][:20]:\r\n if g['type'] == 'page' and g['is_closed'] == 0:\r\n got = False\r\n try:\r\n o = find({'id': target['id'], 'sex': 1, 'minage': 2001, 'maxage': 1990, 'group': g['id'], 'city': target['city']['id']})\r\n got = True\r\n for gurl in o:\r\n if gurl not in output:\r\n output.append(gurl)\r\n except:\r\n print('Ошибка при проверке паблика')\r\n output = sorted(output, key=lambda x: len(x['appeal']), reverse=True)\r\n f = open('girls_%s.html' % 'all', 'w')\r\n for o in output:\r\n a = ', '.join(o['appeal'])\r\n try:\r\n f.write(\r\n \"\"\"\r\n <h1><a href=%s>%s %s</a></h1>\r\n <img src=%s /><br>\r\n Совпадения (%d): %s<br>\r\n \"\"\" % ('http://vk.com/'+o['domain'], o['first_name'], o['last_name'], o['photo_max_orig'], len(o['appeal']), a)\r\n )\r\n except:\r\n pass\r\n f.close()","sub_path":"gf.py","file_name":"gf.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"277746353","text":"import scrapy\nfrom scrapy import Request\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.utils.project import get_project_settings\nfrom lxml import etree\n\n\n\n# class QuotesSpider(scrapy.Spider):\n# name = 'quotes'\n# start_urls = ['http://quotes.toscrape.com/page/1/',]\n#\n# def parse(self, response):\n# for quote in response.css('div.quote'):\n# yield {\n# #'text': quote.css('span.text::text').extract_first(),\n# 'author': quote.css('span small::text').extract_first(),\n# #'tags': quote.css('div.tags a.tag::text').extract(),\n# }\n#\n# next_page = response.css('li.next a::attr(href)').extract_first()\n# if next_page is not None:\n# print(type(next_page))\n# print(next_page)\n# yield response.follow(next_page, callback=self.parse)\n\n\n\n# if name == '__main__':\n# process = CrawlerProcess(get_project_settings())\n# process.crawl(QuotesSpider)\n# process.start()\n\nclass HostadviceSpider(scrapy.Spider):\n name = 'Hostadvice'\n allowed_domains = ['hostadvice.com']\n start_urls = ['https://hostadvice.com/hosting-company/godaddy-reviews/page/2/']\n\n def parse(self, response):\n authors = response.xpath(\"//div[@class='review-author']\").extract()\n for content in authors:\n root = etree.fromstring(content)\n for element in root:\n for i in (element.xpath(\"//strong\")):\n print (i.text().encode(\"utf-8\"))\n\nif __name__ == '__main__':\n process = CrawlerProcess(get_project_settings())\n process.crawl(HostadviceSpider)\n process.start()","sub_path":"services/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"486958676","text":"from os import path, walk\n\nfrom syllin import application\n\n# run the app.\nif __name__ == \"__main__\":\n # This allows for better reboot behavior when Jinja2 templates are being edited (by default, not all edits trigger\n # a server reboot)\n extra_dirs = ['syllin/templates', 'syllin/static']\n extra_files = extra_dirs[:]\n for extra_dir in extra_dirs:\n for dirname, dirs, files in walk(extra_dir):\n for filename in files:\n filename = path.join(dirname, filename)\n if path.isfile(filename):\n extra_files.append(filename)\n\n # Setting debug to True enables debug output. This line should be\n # removed before deploying a production app.\n application.debug = True\n application.run(extra_files=extra_files)\n","sub_path":"syllin/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"72947977","text":"#-*- coding: utf-8 -*-\r\nimport os\r\n\r\ndef nombre():\r\n\r\n # tab = [100, 200, 500, 50, 10, 25, 10, 55, 10]\r\n #\r\n nbre = int(input(\" DONNEZ LE NOMBRE A INSERER \"))\r\n compteur=0\r\n\r\n resultat = nbre\r\n\r\n while resultat>=500:\r\n resultat=nbre//500\r\n compteur = compteur+1\r\n print(resultat,\" billets de 500 \")\r\n # resultat = resultat - (compteur*500)\r\n\r\n\r\n\r\n compteur=0\r\n while resultat>=100:\r\n resultat=nbre//100\r\n compteur = compteur+1\r\n print(resultat,\" billets de 100 \")\r\n #resultat = nbre - (resultat*compteur)\r\n\r\n compteur=0\r\n\r\n while resultat>=50:\r\n resultat=nbre//50\r\n compteur = compteur+1\r\n print(resultat,\" billets de 50 \")\r\n # resultat = nbre - (resultat*compteur)\r\n\r\n compteur=0\r\n while resultat>=10:\r\n resultat=nbre//10\r\n compteur = compteur+1\r\n print(resultat, \" billets de 10 \")\r\n resultat = nbre - (resultat*compteur)\r\n\r\n\r\n\r\ndef liste_monotone():\r\n tab = [10, 15, 50, 60, 40]\r\n if tab.sort() is not None:\r\n print(' La liste est Monotone')\r\n else:\r\n print(' La liste n est pas Monotone')\r\n\r\n\r\n\r\n\r\n\r\n\r\nrep = \"a\"\r\n\r\nwhile rep != \"Q\" and rep != \"q\":\r\n print(\" APPUYER SUR -->> \")\r\n print(\" A --> AJOUT DE NOMBRE \")\r\n print(\" B --> LISTE MONOTONE \")\r\n print(\" Q --> POUR QUITTER \")\r\n rep = input(\" APPUYER -->> \")\r\n if rep == \"A\":\r\n nombre()\r\n if rep == \"B\":\r\n liste_monotone()\r\n\r\n\r\n\r\n\r\nos.system(\"Pause\")\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Devoir Python/devoir/module2.py","file_name":"module2.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"634402110","text":"from model import SingleReactionSolution\nimport numpy as np\nimport pints\nfrom data import ECTimeData\nimport pickle\n\n\ndef inference(model, values, times):\n\n # Create an object with links to the model and time series\n problem = pints.SingleOutputProblem(model, times, values)\n\n # Create a log-likelihood function (adds an extra parameter!)\n log_likelihood = pints.GaussianLogLikelihood(problem)\n\n # Create a uniform prior over both the parameters and the new noise variable\n lower_bounds = np.array([1e-3, 0.0, 0.4, 0.1, 1e-6, 8.0, 1e-4])\n upper_bounds = np.array([10.0, 0.4, 0.6, 100.0, 100e-6, 10.0, 0.2])\n log_prior = pints.UniformLogPrior(lower_bounds, upper_bounds)\n\n # Create a posterior log-likelihood (log(likelihood * prior))\n log_posterior = pints.LogPosterior(log_likelihood, log_prior)\n\n # Choose starting points for 3 mcmc chains\n # params = ['k0', 'E0', 'a', 'Ru', 'Cdl', 'freq', 'sigma']\n start_parameters = np.array([0.0101, 0.214, 0.53, 8.0, 20.0e-6, 9.0152, 0.01])\n\n transform = pints.ComposedTransformation(\n pints.LogTransformation(1),\n pints.RectangularBoundariesTransformation(\n lower_bounds[1:], upper_bounds[1:]\n ),\n )\n sigma0 = [0.1 * (h - l) for l, h in zip(lower_bounds, upper_bounds)]\n boundaries = pints.RectangularBoundaries(lower_bounds, upper_bounds)\n found_parameters, found_value = pints.optimise(\n log_posterior,\n start_parameters,\n sigma0,\n boundaries,\n transform=transform,\n method=pints.CMAES\n )\n xs = [\n found_parameters * 1.001,\n found_parameters * 1.002,\n found_parameters * 1.003,\n ]\n for x in xs:\n x[5] = found_parameters[5]\n\n print('start_parameters', start_parameters)\n print('found_parameters', found_parameters)\n print('lower_bounds', lower_bounds)\n print('upper_bounds', upper_bounds)\n\n\n\n # Create mcmc routine with four chains\n mcmc = pints.MCMCController(log_posterior, 3, xs, method=pints.HaarioBardenetACMC,\n transform=transform)\n\n # Add stopping criterion\n mcmc.set_max_iterations(10000)\n\n # Run!\n chains = mcmc.run()\n\n # Save chains for plotting and analysis\n pickle.dump((xs, pints.GaussianLogLikelihood, log_prior,\n chains, 'HaarioBardenetACMC'), open('results.pickle', 'wb'))\n\n\nif __name__ == '__main__':\n model = SingleReactionSolution()\n data = ECTimeData('GC01_FeIII-1mM_1M-KCl_02_009Hz.txt', model,\n ignore_begin_samples=5, ignore_end_samples=0, samples_per_period=200)\n inference(model, data.current, data.times)\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"251757767","text":"# queries.py\n\"\"\" Collection of commonly-used queries \"\"\"\n\nfrom __future__ import absolute_import, with_statement\n\nimport arrow\nfrom pony import orm\n\nfrom . import model, utils\n\n\ndef where_entry_visible(query, date=None):\n \"\"\" Generate a where clause for currently-visible entries\n\n Arguments:\n\n date -- The date to generate it relative to (defaults to right now)\n \"\"\"\n\n return orm.select(\n e for e in query\n if e.status == model.PublishStatus.PUBLISHED.value or\n (e.status == model.PublishStatus.SCHEDULED.value and\n (e.utc_date <= (date or arrow.utcnow().datetime))\n )\n )\n\n\ndef where_entry_visible_future(query):\n \"\"\" Generate a where clause for entries that are visible now or in the future \"\"\"\n\n return orm.select(\n e for e in query\n if e.status in (model.PublishStatus.PUBLISHED.value,\n model.PublishStatus.SCHEDULED.value))\n\n\ndef where_entry_deleted(query):\n \"\"\" Generate a where clause for entries that have been deleted \"\"\"\n return orm.select(\n e for e in query\n if e.status == model.PublishStatus.GONE.value)\n\n\ndef where_entry_category(query, category, recurse=False):\n \"\"\" Generate a where clause for a particular category \"\"\"\n\n category = str(category)\n if category and recurse:\n # We're recursing and aren't in /, so add the prefix clause\n return orm.select(\n e for e in query\n if e.category == category or e.category.startswith(category + '/')\n )\n\n if not recurse:\n # We're not recursing, so we need an exact match on a possibly-empty\n # category\n return orm.select(e for e in query if e.category == category)\n\n # We're recursing and have no category, which means we're doing nothing\n return query\n\n\ndef where_before_entry(query, ref):\n \"\"\" Generate a where clause for prior entries\n\n ref -- The entry of reference\n \"\"\"\n return orm.select(\n e for e in query\n if e.local_date < ref.local_date or\n (e.local_date == ref.local_date and e.id < ref.id)\n )\n\n\ndef where_after_entry(query, ref):\n \"\"\" Generate a where clause for later entries\n\n ref -- the entry of reference\n \"\"\"\n return orm.select(\n e for e in query\n if e.local_date > ref.local_date or\n (e.local_date == ref.local_date and\n e.id > ref.id\n )\n )\n\n\ndef where_entry_last(query, ref):\n \"\"\" Generate a where clause where this is the last entry\n\n ref -- the entry of reference\n \"\"\"\n return orm.select(\n e for e in query\n if e.local_date < ref.local_date or\n (e.local_date == ref.local_date and\n e.id <= ref.id\n )\n )\n\n\ndef where_entry_first(query, ref):\n \"\"\" Generate a where clause where this is the first entry\n\n ref -- the entry of reference\n \"\"\"\n return orm.select(\n e for e in query\n if e.local_date > ref.local_date or\n (e.local_date == ref.local_date and\n e.id >= ref.id\n )\n )\n\n\ndef where_entry_type(query, entry_type):\n \"\"\" Generate a where clause for entries of certain types\n\n entry_type -- one or more entries to check against\n \"\"\"\n if isinstance(entry_type, list):\n return orm.select(e for e in query if e.entry_type in entry_type)\n return orm.select(e for e in query if e.entry_type == entry_type)\n\n\ndef where_entry_type_not(query, entry_type):\n \"\"\" Generate a where clause for entries that aren't of certain types\n\n entry_type -- one or more entries to check against\n \"\"\"\n if isinstance(entry_type, list):\n return orm.select(e for e in query if e.entry_type not in entry_type)\n return orm.select(e for e in query if e.entry_type != entry_type)\n\n\ndef where_entry_date(query, datespec):\n \"\"\" Where clause for entries which match a textual date spec\n\n datespec -- The date spec to check for, in YYYY[[-]MM[[-]DD]] format\n \"\"\"\n date, interval, _ = utils.parse_date(datespec)\n start_date, end_date = date.span(interval)\n\n return orm.select(\n e for e in query if\n e.local_date >= start_date.naive and\n e.local_date <= end_date.naive\n )\n\n\ndef get_entry(entry):\n \"\"\" Helper function to get an entry by ID or by object \"\"\"\n\n if hasattr(entry, 'id'):\n return entry\n\n if isinstance(entry, (int, str)):\n return model.Entry.get(id=int(entry))\n raise ValueError(\"entry is of unknown type {}\".format(type(entry)))\n\n\ndef build_query(spec):\n \"\"\" build the where clause based on a view specification\n\n spec -- The view specification. Contains the following possible values:\n future -- Boolean; whether to include entries from the future\n category -- Which category to limit to\n recurse -- Whether to include subcategories\n entry_type -- one or more entry types to include\n entry_type_not -- one or more entry types to exclude\n date -- a date spec\n last -- the last entry to end a view on\n first -- the first entry to start a view on\n before -- get entries from before this one\n after -- get entries from after this one\n \"\"\"\n\n query = model.Entry.select()\n\n # primarily restrict by publication status\n if spec.get('_deleted', False):\n query = where_entry_deleted(query)\n elif spec.get('future', False):\n query = where_entry_visible_future(query)\n else:\n query = where_entry_visible(query)\n\n # restrict by category\n if spec.get('category') is not None or spec.get('recurse'):\n path = str(spec.get('category', ''))\n recurse = spec.get('recurse', False)\n query = where_entry_category(query, path, recurse)\n\n if spec.get('entry_type'):\n query = where_entry_type(query, spec['entry_type'])\n\n if spec.get('entry_type_not'):\n query = where_entry_type_not(query, spec['entry_type_not'])\n\n if spec.get('date'):\n query = where_entry_date(query, spec['date'])\n\n if spec.get('last'):\n query = where_entry_last(query, get_entry(spec['last']))\n\n if spec.get('first'):\n query = where_entry_first(query, get_entry(spec['first']))\n\n if spec.get('before'):\n query = where_before_entry(query, get_entry(spec['before']))\n\n if spec.get('after'):\n query = where_after_entry(query, get_entry(spec['after']))\n\n return query\n","sub_path":"publ/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"207851324","text":"from pywinauto.win32structures import RECT\nfrom pyautogui import click\nfrom pyautogui import moveTo, press, typewrite, hotkey, position\n\nfrom pywinauto import Application\nfrom pywinauto import handleprops\n\nfrom win32api import GetKeyState\n\nimport win32gui\nfrom win32con import SWP_SHOWWINDOW\n\nfrom tkinter import Button, Tk, Label, Entry, Text\n\nfrom sys import argv\n\nfrom os import listdir\nfrom openpyxl import load_workbook\nfrom openpyxl.styles.fills import FILL_NONE\nfrom _datetime import date, timedelta, datetime\n\nimport sys\n\nfrom time import sleep, strptime\nfrom openpyxl.styles.colors import Color, RGB\n\n\n# normal resolution\nSHIPPERCODELOC = (48,301)\nCONSIGNEECODELOC = (301,301)\nCUSTOMERCODELOC = (564,301)\n \n \nDESCRIPTIONLOC = (20,354)\n# 30, 432\n \nEQUIPMENTLOC = (327, 900)\nDIRECTIONLOC = (400,922)\nDIVISIONLOC = (550,944)\nLANECODELOC = (568, 967)\n \nHOUSELOC = (1807, 1000)\n \nOKLOC = (1857, 127)\n# 1859, 155\nDUPLICATELOC = (1845, 273)\n \nROUTINGTABLOC = (688, 96)\n# 695, 115\nDRIVERPAYOUTLOC = (132, 858)\n# 76, 800\n \nRATINGTABLOC = (1153, 98)\nCUSTOMERCHARGELOC = (49,144)\n \nNEWLOC = (1850,100)\n \nHELPLOC = (328, 33)\n# (386, 40)\nFINDLOC = (382, 284)\n# (424, 330)\nMAXIMIZELOC = (1859, 102)\n# 1851, 118)\nPUDATELOC = (544, 901)\n# 687, 859\nDODATELOC = (538, 928)\n# 700, 890\nDRIVERNAMELOC = (1526, 680)\n# 1487, 590\nDRIVERNUMLOC = (1519, 728) \n# 1448, 644\nPRINTLOC = (1848, 199)\nCARRIERLOC = (1822, 312)\nPRINTCARRIERLOC = (1604, 317)\n\n\n\n# CUSTOMERCODELOC = (732, 372)\n# DESCRIPTIONLOC = (30, 432)\n# # \n# \n# # EQUIPMENTLOC = (327, 900)\n# # DIRECTIONLOC = (400,922)\n# # DIVISIONLOC = (550,944)\n# # LANECODELOC = (568, 967)\n# \n# # HOUSELOC = (1807, 1000)\n# \n# OKLOC = (1859, 155)\n# \n# ROUTINGTABLOC = (695, 115)\n# DRIVERPAYOUTLOC = (76, 800)\n# \n# CUSTOMERCHARGELOC = (49,144)\n# \n# NEWLOC = (1850,100)\n# \n# HELPLOC = (386, 40)\n# FINDLOC = (424, 330)\n# MAXIMIZELOC =(1851, 118) \n# PUDATELOC = (687, 859)\n# DODATELOC = (700, 890)\n# DRIVERNAMELOC = (1487, 590)\n# DRIVERNUMLOC = (1448, 644) \n# \n# PRINTLOC = (1830, 243)\n# CARRIERLOC = (1763, 372)\n# PRINTCARRIERLOC = (1530, 372)\n\n\nclass Driver(object):\n driver = \"\"\n name = \"\"\n PARS = \"\"\n containerNumber = \"\"\n payout = \"\"\n sunrise = False\n bareframe = False\n \ndef popUp(top, top2 = \"\", w=300, h=90, widget=\"\"):\n if not top2==\"\":\n top2.lift()\n top2.attributes('-topmost',True)\n top2.after_idle(top2.attributes,'-topmost',False)\n \n # get screen width and height\n ws = top2.winfo_screenwidth() # width of the screen\n hs = top2.winfo_screenheight() # height of the screen\n \n # calculate x and y coordinates for the Tk root window\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n \n # set the dimensions of the screen \n # and where it is placed\n top2.geometry('%dx%d+%d+%d' % (w, h, x, y))\n \n if widget !=\"\":\n top2.wait_visibility(widget)\n click(widget.winfo_rootx()+widget.winfo_width()/2, widget.winfo_rooty()+5+widget.winfo_height()/2)\n top.wait_window(top2)\n else:\n top.lift()\n top.attributes('-topmost',True)\n top.after_idle(top.attributes,'-topmost',False)\n \n # get screen width and height\n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n \n # calculate x and y coordinates for the Tk root window\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n \n # set the dimensions of the screen \n # and where it is placed\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n if widget !=\"\":\n top.wait_visibility(widget)\n moveTo(widget.winfo_rootx()+widget.winfo_width()/2, widget.winfo_rooty()+5+widget.winfo_height()/2)\n top.mainloop()\n\ndef setupDM(drivers, date, sunriseRate):\n# app = Application(backend=\"win32\").connect(path = r\"C:\\DM54_W16\\DM54_W16.exe\")\n# \n# # top_windows = []\n# # EnumWindows(windowEnumerationHandler, top_windows)\n# # for i in top_windows:\n# # if 'Dispatch-Mate' in i[1]:\n# # SetWindowPos(i[0], None, 0, 0, 1920, 1080, SWP_SHOWWINDOW)\n# # SetForegroundWindow(i[0])\n# \n# \n# winChildren = \"\"\n# \n# dialogs = app.windows()\n# \n# for x in dialogs:\n# if handleprops.classname(x) == \"WinDevObject\":\n# winChildren = handleprops.children(x)\n# topWindow = x\n# break\n clickTuple = False\n \n click(DESCRIPTIONLOC)\n fore = win32gui.GetForegroundWindow()\n DMFore = \"Dispatch-Mate\" in win32gui.GetWindowText(fore)\n while not DMFore:\n top = Tk()\n L1 = Label(top, text=\"Please maximize DispatchMate and the PB in the left monitor\")\n L1.grid(row=0, column=0)\n \n def callbackDM():\n top.destroy()\n \n MyButton4 = Button(top, text=\"OK\", width=10, command=callbackDM)\n MyButton4.grid(row=1, column=0)\n \n popUp(top, w=350, h=50, widget = MyButton4)\n \n click(DESCRIPTIONLOC)\n fore = win32gui.GetForegroundWindow()\n DMFore = \"Dispatch-Mate\" in win32gui.GetWindowText(fore)\n \n# i=0\n for driver in drivers:\n# if i<3: \n# i+=1\n\n\n\n click(HELPLOC)\n \n sleep(1)\n \n click(FINDLOC)\n \n if driver.PARS[-1]==\"A\" or driver.PARS[-1]==\"B\" or driver.PARS[-1]==\"C\":\n typewrite(driver.PARS[-7:-1])\n else:\n typewrite(driver.PARS[-6:])\n \n press(\"enter\")\n \n sleep(5)\n \n click(MAXIMIZELOC)\n \n sleep(0.5)\n \n click(DESCRIPTIONLOC)\n press(\"tab\", 9)\n hotkey('ctrl', 'a')\n hotkey('ctrl', 'c')\n \n# print(driver.containerNumber[:3])\n# print(Tk().clipboard_get()[:3])\n# print(driver.containerNumber[4:8])\n# print(Tk().clipboard_get()[5:9])\n tk=False\n \n clipTk = Tk()\n \n if not str(driver.containerNumber[:4])==clipTk.clipboard_get()[:4] or not str(driver.containerNumber[4:10])==clipTk.clipboard_get()[5:11]:\n tk=True\n contPB = clipTk.clipboard_get()[:4] + clipTk.clipboard_get()[5:11]\n clipTk.destroy()\n if tk:\n top = Tk()\n L1 = Label(top, text=\"Container numbers \" + contPB + \" (PB) and \" + driver.containerNumber[:10] + \" (spreadsheet) do not match.\" +\n \"\\n Please navigate to the correct PB and hit \\\"CONTINUE\\\"\")\n L1.grid(row=0, column=0, columnspan=2)\n \n def callbackDM():\n top.destroy()\n \n def callbackDMSTOP():\n sys.exit()\n \n MyButton4 = Button(top, text=\"CONTINUE\", width=10, command=callbackDM)\n MyButton4.grid(row=1, column=0)\n \n MyButton4 = Button(top, text=\"STOP\", width=10, command=callbackDMSTOP)\n MyButton4.grid(row=1, column=1)\n popUp(top, w=700, h=100, widget = MyButton4)\n \n \n# \n# click(CUSTOMERCODELOC)\n# hotkey('ctrl', 'c')\n# \n# # print(driver.containerNumber[:3])\n# # print(Tk().clipboard_get()[:3])\n# # print(driver.containerNumber[4:8])\n# # print(Tk().clipboard_get()[5:9])\n# tk=False\n# \n# clipTk = Tk()\n# \n# if clipTk.clipboard_get()==\"1779\" and driver.bareframe:\n# press(\"tab\")\n# press(\"end\")\n# typewrite(\" HOLD RT\")\n# clipTk.destroy()\n# \n# sleep(0.1)\n \n\n click(PUDATELOC)\n \n month = str(date.month)\n if len(month)<2:\n month = \"0\" + month\n typewrite(month)\n day = str(date.day)\n if len(day)<2:\n day = \"0\" + day\n typewrite(day)\n typewrite(str(date.year))\n \n# typewrite(str(date.month))\n# typewrite(str(date.day))\n# typewrite(str(date.year))\n \n click(DODATELOC)\n \n month = str(date.month)\n if len(month)<2:\n month = \"0\" + month\n typewrite(month)\n day = str(date.day)\n if len(day)<2:\n day = \"0\" + day\n typewrite(day)\n typewrite(str(date.year))\n \n click(ROUTINGTABLOC)\n \n sleep(0.1)\n \n# click(300, 144)\n \n\n click(DRIVERNUMLOC)\n \n typewrite(str(driver.driver))\n \n press('enter') \n \n sleep(0.5)\n \n if str(driver.driver)[:3]!=\"801\":\n click(DRIVERNAMELOC)\n \n typewrite(driver.name)\n \n press('enter')\n \n sleep(1) \n \n click(DRIVERPAYOUTLOC)\n sleep(0.2)\n click(DRIVERPAYOUTLOC)\n hotkey('ctrl', 'a')\n \n hotkey('ctrl', 'c')\n \n clickheight = 17\n clipTk = Tk()\n if clipTk.clipboard_get()==\"HAZARDOUS COST\":\n clickheight+=19\n click(DRIVERPAYOUTLOC[0], DRIVERPAYOUTLOC[1]+17)\n clipTk.destroy()\n \n if str(driver.driver)[:3]!=\"801\": \n typewrite(\"TRUCK\")\n else:\n typewrite(\"DRAY\")\n \n press('tab')\n typewrite(\"1\")\n press('tab')\n press('delete')\n press('tab')\n typewrite(driver.payout)\n \n if driver.sunrise:\n click(DRIVERPAYOUTLOC[0], DRIVERPAYOUTLOC[0]+clickheight)\n hotkey('ctrl', 'a')\n typewrite(\"STOP OFF\")\n press('tab')\n typewrite(\"3\")\n press('tab')\n press('delete')\n press('tab')\n typewrite(sunriseRate)\n \n sleep(0.5)\n \n if GetKeyState(145) < 0:\n exit() \n \n click(OKLOC[0], OKLOC[1], 2)\n# click(1859, 155)\n \n sleep(2)\n\n click(PRINTLOC, button=\"right\")\n \n sleep(1)\n \n click(CARRIERLOC)\n \n sleep(0.3)\n\n# PRINT: \n click(PRINTCARRIERLOC)\n \n sleep(7)\n \n# exit()\n \n\n#EMAIL:\n# click(1539, 442)\n# sleep(0.3)\n# click(1735, 190)\n# \n# # sleep(5)\n# # sleep(5)\n# done=False\n# while not done:\n# try:\n# app = Application(backend=\"win32\").connect(path = r\"C:\\Program Files\\Microsoft Office 15\\root\\office15\\outlook.exe\")\n# done=True\n# except:\n# pass\n# # top_windows = []\n# # EnumWindows(windowEnumerationHandler, top_windows)\n# # for i in top_windows:\n# # if 'Dispatch-Mate' in i[1]:\n# # SetWindowPos(i[0], None, 0, 0, 1920, 1080, SWP_SHOWWINDOW)\n# # SetForegroundWindow(i[0])\n# \n# winChildren = \"\"\n# \n# done = False\n# \n# while not done:\n# dialogs = app.windows()\n# topWindow = None\n# for x in dialogs:\n# if isinstance(handleprops.text(x), str) and not handleprops.text(x)==None:\n# try:\n# if \"Carrier Confirmation\" in handleprops.text(x):\n# winChildren = handleprops.children(x)\n# topWindow = x\n# break\n# except:\n# pass\n# \n# send = \"\"\n# if topWindow==None:\n# continue\n# \n# topWindowWrap = app.window(handle=topWindow)\n# \n# for x in winChildren:\n# # print(handleprops.text(x) + \" \" + handleprops.classname(x))\n# if handleprops.text(x)==\"&Send\":\n# send = x\n# if handleprops.text(x)==\"Fro&m\":\n# buttonWrap = topWindowWrap.child_window(handle=x).wrapper_object()\n# buttonWrap.click()\n# \n# done = True\n# \n# if not clickTuple:\n# moveTo(114, 221)\n# \n# while not GetKeyState(145)<0:\n# True\n# \n# clickTuple = position()\n# \n# # else: \n# click(clickTuple)\n# \n# if done==True: \n# buttonWrap = topWindowWrap.child_window(handle=send).wrapper_object()\n# buttonWrap.click()\n# \n# \n# \n# \n# if GetKeyState(145) < 0:\n# exit() \n# \n# \n# sleep(1)\n# \n# # 1530, 443\n# \n# if GetKeyState(145) < 0:\n# exit() \n \n \n# sleep(1)\n \n# i = i+1\n \n \n\ndef loadinfo(folderPath):\n CSXMOVES = load_workbook(folderPath)\n activeSheet = CSXMOVES['CSX MOVES']\n driverSheet = CSXMOVES['Drivers']\n rateSheet = CSXMOVES['Rates']\n colorSheet = CSXMOVES['COLOUR KEY']\n \n drivers = []\n #RGB 173,216,230\n# activeColor = RGB(\"add8e6\")\n \n# print('aaa')\n# print(colorSheet.max_row)\n colors = [\"\",\"\",\"\",\"\",\"\",\"\"]\n for xRow in colorSheet.rows:\n for xCell in xRow:\n if xCell.value==\"MONDAY\":\n colors[0]=xCell.fill\n break\n elif xCell.value==\"TUESDAY\":\n colors[1]=xCell.fill\n break\n elif xCell.value==\"WEDNESDAY\":\n colors[2]=xCell.fill\n break\n elif xCell.value==\"THURSDAY\":\n colors[3]=xCell.fill\n break\n elif xCell.value==\"FRIDAY\":\n colors[4]=xCell.fill\n break\n elif xCell.value==\"SATURDAY\":\n colors[5]=xCell.fill\n break\n \n dayOfTheWeek = [-1]\n startAt = [\"\"]\n top = Tk()\n L1 = Label(top, text=\"Please select which driver to start at (optional) \\n as well as which day of the week to run on \\n \")\n L1.config(font=(\"Courier\", 16))\n L1.grid(row=0, column=0, columnspan=6)\n L2 = Label(top, text=\"Start at driver #:\")\n L2.config(font=(\"Courier\", 10))\n L2.grid(row=1, column=0, columnspan = 2)\n E1 = Entry(top, bd = 5, width = 39)\n E1.grid(row=1, column=2, columnspan = 2)\n L3 = Label(top, text=\"OR\")\n L3.grid(row=2, column=1, columnspan=2)\n L3.config(font=(\"Courier\", 20))\n top.lift()\n top.attributes('-topmost',True)\n top.after_idle(top.attributes,'-topmost',False)\n \n def callbackDay(day):\n startAt[0]=E1.get().strip()\n dayOfTheWeek[0] = day\n top.destroy()\n \n \n MyButton5 = Button(top, text=\"MONDAY\", command=lambda: callbackDay(0))\n MyButton5.grid(row=4, column=0)\n MyButton5.config(font=(\"Courier\", 16))\n MyButton6 = Button(top, text=\"TUESDAY\", command=lambda: callbackDay(1))\n MyButton6.grid(row=4, column=1)\n MyButton6.config(font=(\"Courier\", 16))\n MyButton7 = Button(top, text=\"WEDNESDAY\", command=lambda: callbackDay(2))\n MyButton7.grid(row=4, column=2)\n MyButton7.config(font=(\"Courier\", 16))\n MyButton8 = Button(top, text=\"THURSDAY\", command=lambda: callbackDay(3))\n MyButton8.grid(row=4, column=3)\n MyButton8.config(font=(\"Courier\", 16))\n MyButton9 = Button(top, text=\"FRIDAY\", command=lambda: callbackDay(4))\n MyButton9.grid(row=4, column=4)\n MyButton9.config(font=(\"Courier\", 16))\n MyButton10 = Button(top, text=\"SATURDAY\", command=lambda: callbackDay(5))\n MyButton10.grid(row=4, column=5)\n MyButton10.config(font=(\"Courier\", 16)) \n \n w = 900 # width for the Tk root\n h = 260 # height for the Tk root\n \n # get screen width and height\n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n \n # calculate x and y coordinates for the Tk root window\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n \n # set the dimensions of the screen \n # and where it is placed\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n \n top.mainloop()\n \n todaysFill = colors[dayOfTheWeek[0]]\n \n year = folderPath.split(\"\\\\\")[-2]\n week = folderPath.split(\"\\\\\")[-1].split(\" \")[3]\n pickupDate = date(int(year), 1, 1)\n \n oneDay = timedelta(1)\n oneWeek = timedelta(7)\n \n while pickupDate.weekday() != 0:\n pickupDate = pickupDate+oneDay\n \n pickupDate = pickupDate + (int(week)-1)*oneWeek\n \n pickupDate = pickupDate + (dayOfTheWeek[0])*oneDay\n \n containerNumberCol = \"\"\n containerNumber2Col = \"\"\n parsCol = \"\"\n pars2Col = \"\"\n driverCol = \"\"\n notesCol = \"\"\n notes2Col=\"\"\n \n \n for cell in next(activeSheet.rows):\n if cell.value == \"PB\":\n parsCol = cell.col_idx - 1\n elif cell.value == \"Container\":\n containerNumberCol = cell.col_idx - 1\n elif cell.value == \"EX BP\":\n notesCol = cell.col_idx - 1\n elif cell.value == \"NOTES\":\n notes2Col = cell.col_idx - 1\n elif cell.value == \"DRIVER\":\n driverCol = cell.col_idx - 1\n elif cell.value == \"Container IMPORT\":\n containerNumber2Col = cell.col_idx - 1\n elif cell.value == \"IM BP\":\n pars2Col = cell.col_idx - 1\n \n rates=[] \n \n matchWords = [\"Owner Operator\",\n \"Owner Operator BAREFRAME\",\n \"Owner Operator 2 containers roundtrip\",\n \"Owner Operator 3 containers roundtrip\",\n \"Owner Operator 4 containers roundtrip\",\n \"Owner Operator Round trip 5/6 containers\",\n \n \"Company Driver\",\n \"Company Driver BAREFRAME\",\n \"Company Driver Round trip 2 Containers\",\n \"Company Driver Round trip 3 Containers\",\n \"Company Driver Round trip 4 Containers\",\n \"Company Driver Round trip +4 CONTAINERS\",\n \n \"Sunrise Stop-off (x3)\"\n ]\n match = 0\n for row in rateSheet:\n for cell in row:\n if str(cell.value)==matchWords[match] or (matchWords[match]==\"Company Driver Round trip 5/6 containers\" and str(cell.value)==\"Company Driver Round trip +4 CONTAINERS\"):\n rates.append(str(row[cell.col_idx+1].value))\n match+=1\n break\n \n print(rates)\n startFound= False\n if startAt[0] != \"\":\n for row in activeSheet.rows:\n if row[0].fill.fgColor == todaysFill.fgColor:\n print(row[0].row)\n if (not row[driverCol].value == None) and (not row[driverCol].value == \"\") and row[0].row>2 and (not startFound) and str(row[driverCol].value)==startAt[0]:\n startFound = True\n if startFound:\n if (not row[driverCol].value == None) and (not row[driverCol].value == \"\") and row[0].row>2:\n driver1 = None\n driver2 = None\n if not \"BAREFRAME\" in row[containerNumberCol].value:\n driver1 = Driver()\n driver1.driver = str(row[driverCol].value).strip()\n if not \"BAREFRAME\" in row[containerNumber2Col].value:\n driver2 = Driver()\n driver2.driver = str(row[driverCol].value).strip()\n \n numberOfMoves = 0\n \n currentRow = row[0].row\n # print(currentRow)\n for i in range(-2,3):\n # print(i)\n if not i==0:\n # print(\"here\")\n # print(str(activeSheet[currentRow+i][driverCol].value))\n if str(activeSheet[currentRow+i][driverCol].value)==str(row[driverCol].value):\n # print(activeSheet[containerNumberCol][currentRow+i].value)\n # print(activeSheet[containerNumber2Col][currentRow+i].value)\n if \"BAREFRAME\" in str(activeSheet[currentRow+i][containerNumberCol].value) or \"BAREFRAME\" in str(activeSheet[currentRow+i][containerNumber2Col].value):\n numberOfMoves+=1\n # print(\"+1\")\n else:\n # print(\"+2\") \n numberOfMoves+=2\n \n if numberOfMoves>0:\n if \"BAREFRAME\" in row[containerNumber2Col].value or \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves+=1\n else:\n numberOfMoves+=2\n \n # print(numberOfMoves)\n if numberOfMoves==6:\n numberOfMoves=5\n \n if driver1 != None:\n driver1.PARS = str(row[parsCol].value)\n \n if \"BAREFRAME\" in row[containerNumber2Col].value:\n driver1.bareframe=True\n \n numberOfMoves1=numberOfMoves\n numberOfMoves2=numberOfMoves+6 \n if driver1.driver[:3]==\"801\":\n if numberOfMoves1==0 and \"BAREFRAME\" in row[containerNumber2Col].value:\n numberOfMoves1+=1\n driver1.payout=rates[numberOfMoves1]\n else:\n if numberOfMoves2==6 and \"BAREFRAME\" in row[containerNumber2Col].value:\n numberOfMoves2+=1\n driver1.payout=rates[numberOfMoves2]\n \n if len(driver1.driver) < 6:\n prefix = \"801\"\n while len(prefix)+len(driver1.driver)<6:\n prefix+=\"0\"\n driver1.driver = prefix+driver1.driver\n \n driver1.containerNumber = str(row[containerNumberCol].value).strip()\n if row[notesCol].value == \"SUNRISE METALS\":\n driver1.sunrise=True\n drivers.append(driver1)\n \n if driver2 != None:\n driver2.PARS = str(row[pars2Col].value)\n \n if \"BAREFRAME\" in row[containerNumberCol].value:\n driver2.bareframe=True\n \n numberOfMoves1=numberOfMoves\n numberOfMoves2=numberOfMoves+6 \n if driver2.driver[:3]==\"801\":\n if numberOfMoves1==0 and \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves1+=1\n driver2.payout=rates[numberOfMoves1]\n else:\n if numberOfMoves2==6 and \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves2+=1\n driver2.payout=rates[numberOfMoves2]\n \n if len(driver2.driver) < 6:\n prefix = \"801\"\n while len(prefix)+len(driver2.driver)<6:\n prefix+=\"0\"\n driver2.driver = prefix+driver2.driver\n \n driver2.containerNumber = str(row[containerNumber2Col].value).strip()\n if row[notes2Col].value == \"SUNRISE METALS\":\n driver2.sunrise=True\n drivers.append(driver2)\n else:\n for row in activeSheet.rows:\n if row[0].fill.fgColor == todaysFill.fgColor:\n print(row[0].row)\n if (not row[driverCol].value == None) and (not row[driverCol].value == \"\") and row[0].row>2:\n driver1 = None\n driver2 = None\n if not \"BAREFRAME\" in row[containerNumberCol].value:\n driver1 = Driver()\n driver1.driver = str(row[driverCol].value).strip()\n if not \"BAREFRAME\" in row[containerNumber2Col].value:\n driver2 = Driver()\n driver2.driver = str(row[driverCol].value).strip()\n \n numberOfMoves = 0\n \n currentRow = row[0].row\n # print(currentRow)\n for i in range(-2,3):\n # print(i)\n if not i==0:\n # print(\"here\")\n # print(str(activeSheet[currentRow+i][driverCol].value))\n if str(activeSheet[currentRow+i][driverCol].value)==str(row[driverCol].value):\n # print(activeSheet[containerNumberCol][currentRow+i].value)\n # print(activeSheet[containerNumber2Col][currentRow+i].value)\n if \"BAREFRAME\" in str(activeSheet[currentRow+i][containerNumberCol].value) or \"BAREFRAME\" in str(activeSheet[currentRow+i][containerNumber2Col].value):\n numberOfMoves+=1\n # print(\"+1\")\n else:\n # print(\"+2\") \n numberOfMoves+=2\n \n if numberOfMoves>0:\n if \"BAREFRAME\" in row[containerNumber2Col].value or \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves+=1\n else:\n numberOfMoves+=2\n \n # print(numberOfMoves)\n if numberOfMoves==6:\n numberOfMoves=5\n \n if driver1 != None:\n driver1.PARS = str(row[parsCol].value)\n \n if \"BAREFRAME\" in row[containerNumber2Col].value:\n driver1.bareframe=True\n \n numberOfMoves1=numberOfMoves\n numberOfMoves2=numberOfMoves+6 \n if driver1.driver[:3]==\"801\":\n if numberOfMoves1==0 and \"BAREFRAME\" in row[containerNumber2Col].value:\n numberOfMoves1+=1\n driver1.payout=rates[numberOfMoves1]\n else:\n if numberOfMoves2==6 and \"BAREFRAME\" in row[containerNumber2Col].value:\n numberOfMoves2+=1\n driver1.payout=rates[numberOfMoves2]\n \n \n if len(driver1.driver) < 6:\n prefix = \"801\"\n while len(prefix)+len(driver1.driver)<6:\n prefix+=\"0\"\n driver1.driver = prefix+driver1.driver\n \n driver1.containerNumber = str(row[containerNumberCol].value).strip()\n if row[notesCol].value == \"SUNRISE METALS\":\n driver1.sunrise=True\n drivers.append(driver1)\n \n if driver2 != None:\n driver2.PARS = str(row[pars2Col].value)\n \n if \"BAREFRAME\" in row[containerNumberCol].value:\n driver2.bareframe=True\n \n numberOfMoves1=numberOfMoves\n numberOfMoves2=numberOfMoves+6 \n if driver2.driver[:3]==\"801\":\n if numberOfMoves1==0 and \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves1+=1\n driver2.payout=rates[numberOfMoves1]\n else:\n if numberOfMoves2==6 and \"BAREFRAME\" in row[containerNumberCol].value:\n numberOfMoves2+=1\n# print(numberOfMoves2)\n# print(driver2.containerNumber)\n driver2.payout=rates[numberOfMoves2]\n \n if len(driver2.driver) < 6:\n prefix = \"801\"\n while len(prefix)+len(driver2.driver)<6:\n prefix+=\"0\"\n driver2.driver = prefix+driver2.driver\n \n driver2.containerNumber = str(row[containerNumber2Col].value).strip()\n if row[notes2Col].value == \"SUNRISE METALS\":\n driver2.sunrise=True\n drivers.append(driver2)\n \n nameDict = {}\n \n for row in driverSheet:\n if not row[0].value==None:\n nameDict[str(row[0].value)] = str(row[2].value)\n# driverNameSorted = list(nameDict.keys())\n# driverNameSorted.sort()\n# print(driverNameSorted)\n noName = \"\"\n noNameCount=1\n noPARS=\"\"\n noPARSCount=1\n badDate = \"\"\n badDateCount = 1\n for driver in drivers:\n if not str(driver.driver)[:3]==\"801\":\n# print(driver.name)\n if not driver.driver in nameDict:\n noNameCount=noNameCount+1\n if noNameCount%6==0:\n noName += \"\\n\"\n noName += str(driver.driver) + \", \"\n if driver.PARS==None or driver.PARS==\"\" or len(driver.PARS)<6:\n noPARS += str(driver.containerNumber) + \", \"\n noPARSCount+=1\n if noPARSCount%4==0:\n noPARS += \"\\n\"\n \n try:\n pickupDate.day\n pickupDate.month\n pickupDate.year\n# driver.pickupDate.day\n# driver.pickupDate.month\n# driver.pickupDate.year\n except:\n badDate += str(driver.containerNumber) + \", \"\n badDateCount+=1\n if badDateCount%4==0:\n badDate += \"\\n\"\n# if not driver.pickupDate:\n \n# if driver.PARS==None or driver.PARS==\"\":\n# noPARS += str(driver.containerNumber) + \", \"\n# noPARSCount+=1\n# if noPARSCount%4==0:\n# noPARS += \"\\n\"\n \n \n if not noName ==\"\":\n top = Tk()\n L1 = Label()\n L1 = Label(top, text=\"No driver name for \\\"\" + noName + \"\\\". \\nPlease fill out the driver columns and start again. \\nAlso ensure that the \\\"Drivers\\\" tab is filled out\")\n L1.config(font=(\"Courier\", 16))\n L1.grid(row=0, column=0)\n \n def callbackOK():\n sys.exit()\n top.destroy()\n \n MyButton = Button(top, text=\"OK\", command=callbackOK, width=40)\n MyButton.grid(row=1, column=0)\n \n w = 750 # width for the Tk root\n h = 300 # height for the Tk root\n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n \n top.mainloop()\n\n if not noPARS==\"\":\n top = Tk()\n L1 = Label()\n L1 = Label(top, text=\"Invalid PARS for \\\"\" + noPARS + \"\\\". \\nPlease fill out the PARS column and start again.\")\n L1.config(font=(\"Courier\", 16))\n L1.grid(row=0, column=0)\n \n def callbackOK():\n sys.exit()\n top.destroy()\n \n MyButton = Button(top, text=\"OK\", command=callbackOK, width=40)\n MyButton.grid(row=1, column=0)\n \n w = 700 # width for the Tk root\n h = 300 # height for the Tk root\n \n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n top.mainloop()\n \n if not badDate==\"\":\n top = Tk()\n L1 = Label()\n L1 = Label(top, text=\"Invalid date. Make sure the spreadsheet is named\\n\\\"Word Word Week X ...\\\"\\n and is in a folder named the year\")\n L1.config(font=(\"Courier\", 16))\n L1.grid(row=0, column=0)\n \n def callbackOK():\n sys.exit()\n top.destroy()\n \n MyButton = Button(top, text=\"OK\", command=callbackOK, width=40)\n MyButton.grid(row=1, column=0)\n \n w = 700 # width for the Tk root\n h = 300 # height for the Tk root\n \n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n top.mainloop()\n\n \n for driver in drivers:\n if not str(driver.driver)[:3]==\"801\":\n driver.name = nameDict[driver.driver]\n \n return drivers, pickupDate, rates[-1]\n\n\nif __name__ == '__main__':\n \n# folderPath = r\"C:\\Users\\ssleep\\Documents\\Programming\\2018\\CSX Moves WEEK 46 NOVEMBER 11 TO NOVEMBER 17.xlsx\"\n \n argv = r\"a J:\\Buffalo Weekly Reports\\2018\\CSX Moves WEEK 49 DECEMBER 2 TO TO DECEMBER 8.xlsx\".split(\" \")\n \n folderPath = ''\n for i in range(len(argv)):\n if i!=0:\n folderPath+=argv[i]\n if i != len(argv) - 1:\n folderPath+=\" \"\n# \n# print(folderPath)\n drivers, date, sunriseRate = loadinfo(folderPath)\n# print(date)\n# for driver in drivers:\n# print(driver.PARS)\n# print(driver.driver)\n# print(driver.name)\n# print(driver.payout)\n# \n# \n# for driver in drivers:\n# print(driver.containerNumber)\n setupDM(drivers, date, sunriseRate)\n \n top = Tk()\n L1 = Label(top, text=\"DONE\")\n L1.config(font=(\"Courier\", 60))\n L1.grid(row=0, column=0)\n \n def callbackOK():\n sys.exit()\n top.destroy()\n \n MyButton = Button(top, text=\"OK\", command=callbackOK, width=30)\n MyButton.grid(row=1, column=0)\n \n w = 250 # width for the Tk root\n h = 148 # height for the Tk root\n \n ws = top.winfo_screenwidth() # width of the screen\n hs = top.winfo_screenheight() # height of the screen\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n top.geometry('%dx%d+%d+%d' % (w, h, x, y))\n top.mainloop()\n \n# pyinstaller \"C:\\Users\\ssleep\\workspace\\Buffalo Drivers on PBs\\Automator\\__init__.py\" --distpath \"J:\\Spencer\\Buffalo Drivers on PBs\" --noconsole -y\n# pyinstaller \"C:\\Users\\ssleep\\workspace\\Buffalo Drivers on PBs\\Automator\\__init__.py\" --distpath \"J:\\Spencer\\Buffalo Drivers on PBS - Magnified\" --noconsole -y","sub_path":"Buffalo Drivers on PBs/Automator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":36505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"491235669","text":"from __future__ import with_statement\n\nfrom fabric.api import cd, run\nfrom fabric.decorators import task\n\nfrom fabfile.util import require_deb_packages, split_packages, install_tarball\nfrom fabtools import require\nfrom fabtools.system import get_arch\nfrom fabtools.utils import run_as_root\n\n\nVERSION = 'luna'\nSR = 'SR1'\nPACKAGE = 'standard'\nPLATFORM = 'linux-gtk'\nNAME = 'eclipse'\n\n\ndef install_eclipse_plugins(\n plugins,\n bin_path,\n install_path,\n repository=None,\n version=VERSION,\n package=PACKAGE,\n):\n if not repository:\n repository = 'http://download.eclipse.org/releases/%(version)s/' % locals(\n )\n\n home_dir = install_path\n cmd = '''%(bin_path)s -nosplash \\\n -application org.eclipse.equinox.p2.director \\\n -repository %(repository)s \\\n -profile SDKProfile \\\n -destination %(home_dir)s ''' % locals()\n cmd += ' '.join([' -installIU %s ' % x for x in plugins])\n run_as_root(cmd)\n\n\ndef install_eclipse(\n version=VERSION,\n sr=SR,\n package=PACKAGE,\n):\n require_deb_packages(\n '''\n default-jre\n '''\n )\n arch64 = get_arch() == 'x86_64'\n platform = PLATFORM\n arch = '-x86_64' if arch64 else ''\n\n url_template = 'http://www.mirrorservice.org/sites/download.eclipse.org/eclipseMirror/technology/epp/downloads/release/%(version)s/%(sr)s/'\n download_url = url_template % locals()\n\n tarball = 'eclipse-%(package)s-%(version)s-%(sr)s-%(platform)s%(arch)s.tar.gz' % locals()\n\n url = '%(download_url)s%(tarball)s' % locals()\n templ = \"\"\"#!/bin/sh\n export ECLIPSE_HOME=%(install_path)s\n $ECLIPSE_HOME/eclipse $*\"\"\"\n\n return install_tarball(url=url,\n tarball=tarball,\n name=NAME,\n version='%(version)s-%(sr)s' % locals(),\n bin_template=templ,\n root_directory=NAME\n )\n\n\n@task\ndef eclipse():\n version = VERSION\n sr = SR\n install_path, bin_path = install_eclipse(\n version=version,\n sr=sr,\n )\n'''\n # 'PyDev for Eclipse 2.7.4.2013051601 org.python.pydev.feature.feature.group Aptana'\n install_eclipse_plugins(\n ['org.python.pydev.feature.feature.group'],\n bin_path=bin_path,\n install_path=install_path,\n repository='http://pydev.org/updates/',\n version=version,\n )\n install_eclipse_plugins(\n [\n# 'org.eclipse.cdt',\n 'org.eclipse.cdt.feature.group',\n# 'org.eclipse.cdt.sdk.feature.group',\n# 'org.eclipse.cdt.platform.feature.group' ,\n# 'org.eclipse.cdt.debug.ui.memory.feature.group' ,\n# 'org.eclipse.cdt.debug.edc.feature.group' ,\n# 'org.eclipse.cdt.util.feature.group' ,\n ],\n version=version,\n )\n\n\n'''\n","sub_path":"fabfile/eclipse.py","file_name":"eclipse.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"83910660","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 24 20:05:22 2014\n\n@author: rkmaddox\n\"\"\"\n\nimport pyglet\nimport numpy as np\nfrom pyglet.window import key\n\ncontrol_target = False\nvol_base = 0.01\nvol_max = vol_base * 10 ** (30 / 20.)\nvol_min = vol_base * 10 ** (-30 / 20.)\n\nvol_joy = lambda j: (j.x + 1) / 2 * (vol_max - vol_min) + vol_min\n\njoysticks = pyglet.input.get_joysticks()\nif joysticks:\n use_joystick = True\nelse:\n use_joystick = False\nassert joysticks, 'No joystick device is connected'\njoystick = joysticks[0]\njoystick.open()\n\n\n#==============================================================================\n# Make this a classy party\n#==============================================================================\nclass Maskers(object):\n def __init__(self, files=['maskers/NW_F_C.wav',\n 'maskers/NW_F_S.wav',\n 'maskers/NW_M_C.wav',\n 'maskers/NW_M_S.wav'], vol_base=0.01):\n self.files = files\n self.sources = [pyglet.media.load(f, streaming=False)\n for f in self.files]\n self.duration = np.max([s.duration for s in self.sources])\n self.players = [pyglet.media.Player()\n for _ in range(len(self.files))]\n self.mask_vol = vol_base\n self.location = 0\n self.gender = 0\n self.set_vols()\n\n def loop(self, dt=None):\n for player, source in zip(self.players, self.sources):\n player.eos_action = 'loop'\n player.queue(source)\n for player in self.players:\n player.play()\n self.set_vols()\n\n def stop(self):\n for player in self.players:\n player.next()\n player.pause()\n\n def set_gender(self, gender):\n self.gender = gender\n self.set_vols()\n\n def set_location(self, location):\n self.location = location\n self.set_vols()\n\n def set_mask_vol(self, vol):\n self.mask_vol = vol\n self.set_vols()\n\n def set_vols(self):\n self.play_ind = 2*self.gender + self.location\n self.vols = [0 for _ in range(len(self.files))]\n self.vols[self.play_ind] = self.mask_vol\n for p, v in zip(self.players, self.vols):\n p.volume = v\n #print([int(v > 0) for v in [p.volume for p in self.players]])\n #print([v for v in [p.volume for p in self.players]])\n\n def get_volume(self):\n return self.mask_vol\n\n def get_volume_db(self):\n return 20 * np.log10(self.get_volume())\n\n def set_volume(self, vol):\n self.mask_vol = vol\n self.set_vols()\n\n\nclass Target(object):\n def __init__(self, screen, file_name='targets/kix.mpeg',\n max_vol=1.9952623149688795, show_label=True, vol_base=0.01):\n self._screen = screen\n self.file = file_name\n self.source = pyglet.media.load(self.file, streaming=True)\n self.player = pyglet.media.Player()\n self.duration = self.source.duration\n self.player.volume = vol_base\n self.max_vol = max_vol\n self.show = False\n self.show_label = show_label\n\n def loop(self, dt=None):\n self.player.eos_action = 'loop'\n self.player.queue(self.source)\n self.player.play()\n self.player.volume = self.player.volume\n\n tex = self.player.get_texture()\n tex.anchor_x = int(tex.width / 2)\n tex.anchor_y = int(tex.height / 2)\n\n self.label_str = 'Level: %i'\n self.label = None\n self.update_label()\n\n def stop(self):\n self.player.next()\n self.player.pause()\n\n def set_volume(self, vol):\n self.player.volume = np.minimum(vol, self.max_vol)\n print(np.round(20 * np.log10(self.player.volume), 1))\n self.update_label()\n\n def get_volume(self):\n return self.player.volume\n\n def get_volume_db(self):\n return 20 * np.log10(self.get_volume())\n\n def update_label(self):\n if self.label is None:\n x = self._screen.width / 2\n y = self._screen.height / 2 - self.player.get_texture().height / 2\n self.label = pyglet.text.Label(text='X', x=x, y=y,\n anchor_x='center',\n anchor_y='top')\n self.label.text = self.label_str % np.round(self.get_volume_db() + 25)\n\n def draw(self):\n if self.show:\n self.player.get_texture().blit(screen.width / 2, screen.height / 2)\n if self.show_label:\n self.label.draw()\n\n\n#==============================================================================\n# Initialize everything\n#==============================================================================\n# Set up the window and event handlers\ndisplay = pyglet.canvas.get_display()\nscreen = display.get_default_screen()\nwin_kwargs = dict(width=screen.width, height=screen.height,\n caption='Maskers', fullscreen=True,\n screen=0, style='borderless', visible=True)\nwindow = pyglet.window.Window(**win_kwargs)\nkeys = key.KeyStateHandler()\nwindow.push_handlers(keys)\nwindow.push_handlers(joystick)\nwindow.set_exclusive_mouse()\n\n# Get the party started\nmaskers = Maskers(vol_base=vol_base)\ntarget = Target(screen, show_label=False, vol_base=vol_base)\n\n# Set some parameters\nvol_inc = 10. ** (1./20)\nkey_vis = key._1\nkey_location = key._2\nkey_gender = key._3\n\n\n#==============================================================================\n# Begin callback functions\n#==============================================================================\n@window.event\ndef on_key_press(symbol, modifiers):\n if not use_joystick:\n if symbol == key_location:\n maskers.set_location(1)\n elif symbol == key_gender:\n maskers.set_gender(1)\n elif symbol == key_vis:\n target.show = True\n elif symbol == key.UP:\n if control_target:\n target.set_volume(target.get_volume() * vol_inc)\n else:\n maskers.set_volume(maskers.get_volume() * vol_inc)\n elif symbol == key.DOWN:\n if control_target:\n target.set_volume(target.get_volume() / vol_inc)\n else:\n maskers.set_volume(maskers.get_volume() / vol_inc)\n if symbol == key.ESCAPE:\n target.stop()\n maskers.stop()\n window.has_exit = True\n\n\n#@window.event\n#def on_key_release(symbol, modifiers):\n# if symbol == key_location:\n# maskers.set_location(0)\n# if symbol == key_gender:\n# maskers.set_gender(0)\n# elif symbol == key_vis:\n# target.show = False\n\n\n#def on_joybutton_press():\n# target.show = 1 - joystick.buttons[0]\n# maskers.set_location(1 - joystick.buttons[1])\n# maskers.set_gender(1 - joystick.buttons[2])\n\n\n@window.event\ndef on_draw():\n maskers.set_volume(vol_joy(joystick))\n target.show = joystick.buttons[0]\n maskers.set_location(joystick.buttons[1])\n maskers.set_gender(joystick.buttons[2])\n if target.show:\n target.draw()\n else:\n window.clear()\n\n\n#==============================================================================\n# Finish up and get it going\n#==============================================================================\n# Keep the party going\npyglet.clock.schedule_once(maskers.loop, 0)\npyglet.clock.schedule_once(target.loop, 0)\n\npyglet.app.run()\n","sub_path":"masking_demo3.py","file_name":"masking_demo3.py","file_ext":"py","file_size_in_byte":7432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"558863166","text":"from ctypes import *\r\nfrom ctypes.wintypes import *\r\n\r\n\"\"\"Flags controlling what is included in the device information set built by SetupDiGetClassDevs\"\"\"\r\nDIGCF_DEFAULT = 0x00000001\r\nDIGCF_PRESENT = 0x00000002\r\nDIGCF_ALLCLASSES = 0x00000004\r\nDIGCF_PROFILE = 0x00000008\r\nDIGCF_DEVICE_INTERFACE = 0x00000010\r\n\r\n\"\"\"Flags controlling File acccess\"\"\"\r\nGENERIC_WRITE = (1073741824)\r\nGENERIC_READ = (-2147483648)\r\nFILE_SHARE_READ = 1\r\nFILE_SHARE_WRITE = 2\r\nOPEN_EXISTING = 3\r\nOPEN_ALWAYS = 4\r\nFILE_ATTRIBUTE_NORMAL = 128\r\nFILE_FLAG_OVERLAPPED = 1073741824\r\n\r\nINVALID_HANDLE_VALUE = HANDLE(-1)\r\n\r\n\"\"\" USB PIPE TYPE \"\"\"\r\nPIPE_TYPE_CONTROL = 0\r\nPIPE_TYPE_ISO = 1\r\nPIPE_TYPE_BULK = 2\r\nPIPE_TYPE_INTERRUPT = 3\r\n\r\n\r\nclass UsbSetupPacket(Structure):\r\n _fields_ = [(\"request_type\", c_ubyte), (\"request\", c_ubyte),\r\n (\"value\", c_ushort), (\"index\", c_ushort), (\"length\", c_ushort)]\r\n\r\n\r\n\"\"\" LPOVERLAPPED still not defined. It will be NULL \"\"\"\r\n\r\n\r\nclass LpOverlapped(Structure):\r\n _fields_ = []\r\n\r\n\r\nclass UsbInterfaceDescriptor(Structure):\r\n _fields_ = [(\"b_length\", c_ubyte), (\"b_descriptor_type\", c_ubyte),\r\n (\"b_interface_number\", c_ubyte), (\"b_alternate_setting\", c_ubyte),\r\n (\"b_num_endpoints\", c_ubyte), (\"b_interface_class\", c_ubyte),\r\n (\"b_interface_sub_class\", c_ubyte), (\"b_interface_protocol\", c_ubyte),\r\n (\"i_interface\", c_ubyte)]\r\n\r\n\r\nclass PipeInfo(Structure):\r\n _fields_ = [(\"pipe_type\", c_ulong,), (\"pipe_id\", c_ubyte),\r\n (\"maximum_packet_size\", c_ushort), (\"interval\", c_ubyte)]\r\n\r\n\r\nclass LpSecurityAttributes(Structure):\r\n _fields_ = [(\"n_length\", DWORD), (\"lp_security_descriptor\", c_void_p),\r\n (\"b_Inherit_handle\", BOOL)]\r\n\r\n\r\nclass GUID(Structure):\r\n _fields_ = [(\"data1\", DWORD), (\"data2\", WORD),\r\n (\"data3\", WORD), (\"data4\", c_byte * 8)]\r\n\r\n\r\nclass SpDevinfoData(Structure):\r\n _fields_ = [(\"cb_size\", DWORD), (\"class_guid\", GUID),\r\n (\"dev_inst\", DWORD), (\"reserved\", POINTER(c_ulong))]\r\n\r\n\r\nclass SpDeviceInterfaceData(Structure):\r\n _fields_ = [(\"cb_size\", DWORD), (\"interface_class_guid\", GUID),\r\n (\"flags\", DWORD), (\"reserved\", POINTER(c_ulong))]\r\n\r\n\r\nclass SpDeviceInterfaceDetailData(Structure):\r\n _fields_ = [(\"cb_size\", DWORD), (\"device_path\", WCHAR * 1)] # devicePath array!!!\r\n","sub_path":"winusbpy/winusbclasses.py","file_name":"winusbclasses.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"646201558","text":"import os\nimport shutil\nimport time\nfrom time import sleep\nfrom tkinter import *\nfrom tkinter import filedialog\n\nfrom Scripts.Aruco_Marker_Input import enter_array\nfrom Scripts.BuildCPPFiles import buildCPP\nfrom Scripts.CopyImagesFromSrc import copyUniqueImages\nfrom Scripts.ExecuteTemplate import execute_template_method\n\nfolder_path = '/hri/localdisk/ThesisProject/Kaushik/Kaushik/Testing_Sample_Script/'\nimage_format = '.jpg'\ntrain_the_data = 'train'\ntest_the_data = 'test'\nsource_path_train = ''\nsource_co_ord_path_train = ''\nsource_path_test = ''\nsource_co_ord_path_test = ''\ntrain_coordinates = []\ntest_coordinates = []\nis_train = False\nis_test = False\nis_train_test_data_distinct = False\n\n\ndef m_folder_open_train():\n global source_path_train\n source_path_train = filedialog.askdirectory(\n initialdir=\"/hri/localdisk/ThesisProject/Kaushik/Kaushik/Experiment_10_2/Training_Images/Path_1/\",\n title=\"Select Training Images\")\n source_path_train = source_path_train + '/'\n\n global source_co_ord_path_train\n\n source_co_ord_path_train = filedialog.askopenfilename(initialdir=\"/hri/localdisk/ThesisProject/Kaushik/Kaushik\"\n \"/Experiment_10_2/Training_Images\"\n \"/\",\n filetypes=((\"Text File\", \"*.txt\"), (\"All Files\", \"*.*\")),\n title=\"Choose a file.\"\n )\n\n\ndef m_folder_open_test():\n global source_path_test\n source_path_test = filedialog.askdirectory(\n initialdir=\"/hri/localdisk/ThesisProject/Kaushik/Kaushik/Experiment_10_2/Testing_Images/Path_1/\",\n title=\"Select Testing Images\")\n source_path_test = source_path_test + '/'\n\n global source_co_ord_path_test\n\n source_co_ord_path_test = filedialog.askopenfilename(initialdir=\"/hri/localdisk/ThesisProject/Kaushik/Kaushik\"\n \"/Experiment_10_2/Testing_Images/\",\n filetypes=((\"Text File\", \"*.txt\"), (\"All Files\", \"*.*\")),\n title=\"Choose a file.\"\n )\n\n\ndef move_coordinates_files(filepath, source_train, source_test):\n dest = filepath\n coordinates_path_array = []\n shutil.copy(source_train, dest)\n os.chdir(filepath)\n old_name_train = 'coordinates_wp0_Kodak.txt'\n new_name_train = 'coordinates_train.txt'\n shutil.move(old_name_train, new_name_train)\n coordinates_path_array.append(dest + '/' + new_name_train)\n if is_train_test_data_distinct:\n shutil.copy(source_test, dest)\n old_name_test = 'coordinates_wp0_Kodak.txt'\n new_name_test = 'coordinates_test.txt'\n shutil.move(old_name_test, new_name_test)\n coordinates_path_array.append(dest + '/' + new_name_test)\n return coordinates_path_array\n\n\ndef create_folder_structure(aruco_marker_array):\n time_string = time.strftime(\"%d%m%Y-%H%M%S\")\n directory_items = []\n extracted_folder_items = []\n if not os.path.exists(folder_path + time_string):\n current_working_folder = folder_path + time_string\n os.makedirs(current_working_folder)\n os.makedirs(current_working_folder + '/Training_Data')\n # os.makedirs(current_working_folder + '/Extracted_Train_Data')\n # os.makedirs(current_working_folder + '/Extracted_Test_Data')\n\n # print(\"---\" + current_working_folder)\n directory_items.append(current_working_folder)\n detection_build_utils = os.getcwd().replace('Scripts', 'MarkerDetection/build/utils/')\n directory_items.append(detection_build_utils)\n training_folder = current_working_folder + '/Training_Data/'\n directory_items.append(training_folder)\n # training_extract = current_working_folder + '/Extracted_Train_Data/'\n # directory_items.append(training_extract)\n run_train_detection = os.getcwd() + '/run_train_detection.sh'\n directory_items.append(run_train_detection)\n train_xml = current_working_folder + '/trainList.xml'\n directory_items.append(train_xml)\n train_csv = current_working_folder + '/result_train.csv'\n directory_items.append(train_csv)\n\n if is_train_test_data_distinct:\n os.makedirs(current_working_folder + '/Testing_Data')\n testing_folder = current_working_folder + '/Testing_Data/'\n directory_items.append(testing_folder)\n # testing_extract = current_working_folder + '/Extracted_Test_Data/'\n # directory_items.append(testing_extract)\n run_test_detection = os.getcwd() + '/run_test_detection.sh'\n directory_items.append(run_test_detection)\n test_xml = current_working_folder + '/testList.xml'\n directory_items.append(test_xml)\n test_csv = current_working_folder + '/result_test.csv'\n directory_items.append(test_csv)\n\n for var in range(len(aruco_marker_array)):\n training_extract_folder = current_working_folder + '/Extracted_Train_Data_'+aruco_marker_array[var]+'/'\n os.makedirs(training_extract_folder)\n extracted_folder_items.append(training_extract_folder)\n\n if is_train_test_data_distinct:\n for var in range(len(aruco_marker_array)):\n testing_extract_folder = current_working_folder + '/Extracted_Test_Data_'+aruco_marker_array[var]+'/'\n os.makedirs(testing_extract_folder)\n extracted_folder_items.append(testing_extract_folder)\n\n return directory_items,extracted_folder_items\n\n\ndef count_of_images(file__path):\n path, dirs, files = next(os.walk(file__path))\n file_count = len(files)\n return file_count\n\n\nif __name__ == \"__main__\":\n num_data_sets = input(\"Are there two separate data sets to Train & Test ? [y/n]\")\n if num_data_sets == 'y':\n is_train_test_data_distinct = True\n print(\"Choose Training Data and its Co-Ordinates File, Please browse\")\n browseBox = Tk()\n Button(text=\"open Folder\", width=30, command=m_folder_open_train()).pack()\n browseBox.destroy()\n browseBox.mainloop()\n\n if is_train_test_data_distinct:\n print(\"Choose Testing Data and its Co-Ordinates File, Please browse\")\n browseBox = Tk()\n Button(text=\"open Folder\", width=30, command=m_folder_open_test()).pack()\n browseBox.destroy()\n browseBox.mainloop()\n\n print(\"source_path_train : \", source_path_train)\n print(\"source_co_ord_path_train : \", source_co_ord_path_train)\n print(\"source_path_test : \", source_path_test)\n print(\"source_co_ord_path_test : \", source_co_ord_path_test)\n\n question = input(\"Do you wanna re-build [y / n]\")\n dir_path = os.getcwd()\n\n if question == 'y':\n file_path = dir_path + '/SetEnvironmentForAruco.sh'\n build_path = dir_path.replace('Scripts', 'MarkerDetection/')\n # buildCPP(build_path, file_path)\n buildCPP(file_path)\n\n aruco_marker_id = enter_array()\n # id_1 = aruco_marker_id[0]\n\n print(\"Process starting\", end='')\n for i in range(25):\n print(\".\", end='')\n sleep(0.1)\n\n items_in_dir,extraction_folders = create_folder_structure(aruco_marker_id)\n '''\n print(\"items in dir are : \")\n print(items_in_dir)\n print(\"#####################################################\")\n print(\"Extraction Folders are : \")\n print(extraction_folders)\n '''\n coordinates_path = move_coordinates_files(items_in_dir[0], source_co_ord_path_train, source_co_ord_path_test)\n \n copyUniqueImages(coordinates_path[0], source_path_train, items_in_dir[2])\n train_img_count = count_of_images(items_in_dir[2])\n train_set_items = [items_in_dir[0],\n items_in_dir[1],\n items_in_dir[2],\n items_in_dir[3],\n items_in_dir[4],\n items_in_dir[5],\n source_path_train,\n coordinates_path[0],\n image_format,\n train_img_count,\n train_the_data,\n is_train_test_data_distinct,\n extraction_folders,\n aruco_marker_id]\n test_set_items = []\n\n if is_train_test_data_distinct:\n copyUniqueImages(coordinates_path[1], source_path_test, items_in_dir[6])\n test_img_count = count_of_images(items_in_dir[6])\n test_set_items = [items_in_dir[0],\n items_in_dir[1],\n items_in_dir[6],\n items_in_dir[7],\n items_in_dir[8],\n items_in_dir[9],\n source_path_test,\n coordinates_path[1],\n image_format,\n test_img_count,\n test_the_data,\n is_train_test_data_distinct,\n extraction_folders,\n aruco_marker_id]\n\n if is_train_test_data_distinct:\n execute_template_method(train_set_items, test_set_items)\n else:\n execute_template_method(train_set_items, [])\n","sub_path":"Localization_v_1_0/Scripts/InitiateExecution.py","file_name":"InitiateExecution.py","file_ext":"py","file_size_in_byte":9484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"253307653","text":"import os\nimport numpy as np\nfrom keras.models import load_model\n\ndirname = 'test'\nbbs_model_name = '2019_10_14_22_16_22'\nbase_path = '../cat-dataset/data/clean/%s' % dirname\n\nimg_size = 224\nfile_list = sorted(os.listdir(base_path))\n\ndataset = {\n 'bbs': []\n}\n\ndata_bbs = np.load('dataset/%s.npy' % dirname, allow_pickle=True)\nx_bbs = np.array(data_bbs.item().get('imgs')).astype('float32') / 255.\nbbs_model = load_model('models/%s.h5' % bbs_model_name)\npred_bbs = bbs_model.predict(x_bbs, verbose=1)\n\ndataset['bbs'] = [pred_bb.flatten() for pred_bb in pred_bbs]\n\nnp.save('dataset/predicted_bbox_%s_%s.npy' % (bbs_model_name, dirname), np.array(dataset))\n","sub_path":"preprocess_predict_bbox.py","file_name":"preprocess_predict_bbox.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"560092709","text":"from GUI import *\r\nimport Backend as core\r\n\r\napp = None\r\napp = Gui()\r\n\r\ndef view_command():\r\n rows = core.view()\r\n app.listPacientes.delete(0, END)\r\n for r in rows:\r\n app.listPacientes.insert(END, r)\r\n\r\ndef search_command():\r\n app.listPacientes.delete(0, END)\r\n rows = core.search(app.txtNome.get(), app.txtCodigo.get(), app.txtEndereco.get(), app.txtCPF.get(), app.txtObservacao.get())\r\n for r in rows:\r\n app.listClientes.insert(END, r)\r\n\r\ndef insert_command():\r\n core.insert(app.txtNome.get(), app.txtCodigo.get(), app.txtEndereco.get(), app.txtCPF.get(), app.txtObservacao.get())\r\n view_command()\r\n\r\ndef getSelectedRow(event):\r\n global selected\r\n index = app.listPacientes.curselection()[0]\r\n selected = app.listPacientes.get(index)\r\n app.entNome.delete(0, END)\r\n app.entNome.insert(END, selected[1])\r\n app.entCodigo.delete(0, END)\r\n app.entCodigo.insert(END, selected[2])\r\n app.entEndereco.delete(0, END)\r\n app.entEndereco.insert(END, selected[3])\r\n app.entCPF.delete(0, END)\r\n app.entCPF.insert(END, selected[4])\r\n app.entObservacao.delete(0, END)\r\n app.entObservacao.insert(END, selected[5])\r\n\r\ndef update_command():\r\n core.update(selected[0], app.txtNome.get(), app.txtCodigo.get(), app.txtEndereco.get(), app.txtCPF.get(), app.txtObservacao.get())\r\n view_command()\r\n\r\ndef del_command():\r\n codigo = selected[2]\r\n core.delete(codigo)\r\n view_command()\r\n\r\napp.btnVerTodos.configure(command=view_command)\r\napp.btnBuscar.configure(command=search_command)\r\napp.btnInserir.configure(command=insert_command)\r\napp.btnAtualizar.configure(command=update_command)\r\napp.btnDelete.configure(command=del_command)\r\napp.btnFechar.configure(command=app.window.destroy)\r\n\r\napp.listPacientes.bind('<<ListboxSelect>>', getSelectedRow)\r\n\r\n\r\napp.run()\r\n","sub_path":"Aplicacao.py","file_name":"Aplicacao.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"306927427","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport os\n\n# ========== UTILS ========== \ndef get_unique_colors(img):\n return (np.unique(img.reshape(-1, img.shape[2]), axis=0))\n\ndef getNextNewColor(usedColors):\n newColor = (np.random.choice(range(256), size=3))\n while np.any([np.all(uc == newColor) for uc in usedColors]): # if newColor matches any of the oldColors\n newColor = (np.random.choice(range(256), size=3))\n return newColor\n\ndef gen_color_key(color):\n return \"_\".join(str(channel) for channel in color)\n\ndef pretty_print_obj(obj):\n for (k,v) in obj.items():\n print(k,\":\",v)\n\n# ========== Connected Components ========== \ndef floodfill(surface, x, y, oldColors, usedColors):\n if surface[x][y] not in oldColors: # Has new color already. No need to look.\n return surface, usedColors\n\n colorOfFocus = surface[x][y].copy()\n newColor = getNextNewColor(usedColors) \n usedColors = np.vstack([usedColors, newColor])\n\n # Add first coord into stack\n theStack = [(x, y)]\n \n while len(theStack) > 0:\n x, y = theStack.pop()\n \n if x < 0 or x > surface.shape[0]-1 or y < 0 or y > surface.shape[1]-1: # Out of Bounds\n continue\n \n if np.all(surface[x][y] == colorOfFocus):\n surface[x][y] = newColor\n theStack.append((x+1, y)) # right\n theStack.append((x-1, y)) # left\n theStack.append((x, y+1)) # down\n theStack.append((x, y-1)) # up\n\n return surface, usedColors\n\ndef flood_fill_multi(img, debug=False):\n oldColors = get_unique_colors(img)\n usedColors = get_unique_colors(img)\n \n if debug:\n print(\"Used Colors\")\n plt.imshow(usedColors)\n plt.show()\n\n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n img, usedColors = floodfill(img, i, j, oldColors, usedColors)\n\n return img, usedColors\n\ndef get_largest_components(img, usedColors, n=2):\n h = {} \n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n color = img[i][j]\n color_key = gen_color_key(color)\n if color_key in h.keys():\n h[color_key] += 1\n else:\n h[color_key] = 1\n\n h_desc = [item[0] for item in sorted(h.items(), key = lambda kv:(kv[1], kv[0]))]\n h_desc_rev_filt = list(reversed(h_desc))[:n]\n top_n_components = [[int(ck) for ck in colorkey.split('_')] for colorkey in h_desc_rev_filt]\n return top_n_components\n\ndef filter_out_colors(img, colors, bgColor):\n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n curr_color = img[i][j]\n if not np.any([np.all(c == curr_color) for c in colors]):\n img[i][j] = bgColor\n return img\n\ndef img_preprocess_0(img):\n kernel_10x10 = np.ones((10,10),np.uint8)\n img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel_10x10) # Open. Fill in any holes.\n img = cv2.GaussianBlur(img, (5,5), 0)\n img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel_10x10) # Open. Fill in any holes.\n img = cv2.GaussianBlur(img, (5,5), 0)\n\n _, img = cv2.threshold(img,250,255,cv2.THRESH_BINARY)\n return img\n\ndef img_preprocess_1(img):\n kernel_2x2 = np.ones((2,2),np.uint8)\n img = cv2.erode(img, kernel_2x2, iterations=1)\n img = cv2.GaussianBlur(img, (5,5), 0) \n img = cv2.dilate(img, kernel_2x2, iterations=1)\n _, img = cv2.threshold(img,175,255,cv2.THRESH_BINARY)\n return img\n\ndef img_preprocess_2(img):\n kernel_5x5 = np.ones((5,5),np.uint8)\n kernel_3x3 = np.ones((3,3),np.uint8)\n\n img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel_5x5) # Open. Fill in any holes.\n img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_3x3) # Close. Remove small blob\n _, img = cv2.threshold(img,100,255,cv2.THRESH_BINARY)\n return img\n\ndef img_preprocess_3(img):\n kernel_10x10 = np.ones((10,10),np.uint8)\n kernel_7x7 = np.ones((7,7),np.uint8)\n kernel_3x3 = np.ones((3,3),np.uint8)\n \n img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_10x10) # Close. Remove small blob \n img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_10x10) # Close. Remove small blob\n img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_7x7) # Close. Remove small blob\n img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel_3x3) # Close. Remove small blob\n _, img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)\n return img\n\ndef get_connected_components(img, preprocess_mode, n=2, debug=False, output_res=False):\n if debug:\n print(\"Original\")\n plt.imshow(img)\n plt.show()\n\n if preprocess_mode == 0:\n img = img_preprocess_0(img)\n if preprocess_mode == 1:\n img = img_preprocess_1(img)\n elif preprocess_mode == 2:\n img = img_preprocess_2(img)\n else:\n img = img_preprocess_3(img)\n\n img, usedColors, = flood_fill_multi(img, debug=debug)\n \n if debug:\n print(\"After preprocess and floodfill multi\")\n plt.imshow(img)\n plt.show()\n\n largest_colors = get_largest_components(img, usedColors, n=n)\n if debug:\n print(\"Largest_colors\", largest_colors)\n plt.imshow(np.array([largest_colors]))\n plt.show()\n \n if n > 1:\n largest_colors = largest_colors[1:]\n \n img = filter_out_colors(img, largest_colors, [255, 255, 255])\n if debug or output_res:\n print(\"After filter out smallest colors\")\n plt.imshow(img)\n plt.show()\n \n return img, largest_colors\n\n# ========== Boundary Tracing ========== \n\ndef get_next_cw_pos(center, curr): # TODO, p = center, b = current pos\n# '''\n# C is left of center. \n# [[...],\n# [C center X]]\n# '''\n if curr[1] == center[1] and curr[0]+1 == center[0]: \n return [curr[0], curr[1]-1]\n# '''\n# C is left-top of center. \n# [[C X X],\n# [X center X]]\n# '''\n elif curr[1]+1 == center[1] and curr[0]+1 == center[0]: \n return [curr[0]+1, curr[1]]\n# '''\n# C is top of center. \n# [[X C X],\n# [X center X]]\n# '''\n elif curr[1]+1 == center[1] and curr[0] == center[0]: \n return [curr[0]+1, curr[1]]\n# '''\n# C is top-right of center. \n# [[X X C],\n# [X center X]]\n# '''\n elif curr[1]+1 == center[1] and curr[0]-1 == center[0]: \n return [curr[0], curr[1]+1]\n# '''\n# C is right of center. \n# [[X X X],\n# [X center C]]\n# '''\n elif curr[1] == center[1] and curr[0]-1 == center[0]: \n return [curr[0], curr[1]+1]\n# '''\n# C is right-bot of center. \n# [[X X X],\n# [X center X],\n# [X X C]]\n# '''\n elif curr[1]-1 == center[1] and curr[0]-1 == center[0]: \n return [curr[0]-1, curr[1]]\n# '''\n# C is bot of center. \n# [[X X X],\n# [X center X],\n# [X C X]]\n# '''\n elif curr[1]-1 == center[1] and curr[0] == center[0]: \n return [curr[0]-1, curr[1]]\n# '''\n# C is left-bot of center. \n# [[X X X],\n# [X center X],\n# [C X X]]\n# '''\n elif curr[1]-1 == center[1] and curr[0]+1 == center[0]: \n return [curr[0], curr[1]-1]\n# '''\n# C is left of center. \n# [[X X X],\n# [C center X],\n# [X X X]]\n# '''\n elif curr[1] == center[1] and curr[0]+1 == center[0]: \n return [curr[0], curr[1]-1]\n else:\n print(\"ERROR\") \n\ndef boundary_tracing(img, target_colors, boundary_draw_color, debug=False): \n B = []\n ptColor = [255,255,255]\n start = None\n \n# print(\"shape:\", img.shape)\n\n # From bottom to top and left to right scan the cells of T until a black pixel, s, of P is found.\n for j in range(img.shape[0]):\n if start is not None:\n break\n for i in range(img.shape[1]):\n\n if start is not None:\n break\n \n if np.any([np.all(img[j][i] == tc) for tc in target_colors]): # is ptColor\n start = [i,j]\n if debug:\n print(\"Found first black pixel (i,j) = ({})\".format(start))\n\n if start is None:\n print(\"ERROR | Start is None\")\n return None, None\n\n B.append(start)\n p = start\n b = [start[0]-1, start[1]] # TODO: border handle cases.\n c = get_next_cw_pos(p, b)\n if debug:\n print(\"About to start. Next move is c={}, b={}\".format(c,b))\n\n while not np.all(c == start): # while c != start\n if c[0] < 0 or c[0] > img.shape[1]-1 or c[1] < 0 or c[1] > img.shape[0]-1: # Out of bounds\n b = c\n c = get_next_cw_pos(p, b)\n if debug:\n print(\"out of bounds. Continue . Next move is c={}, b={}\".format(c,b))\n elif np.any([np.all(img[c[1]][c[0]] == tc) for tc in target_colors]): # color at c is pointColor\n B.append(c)\n p = c\n c = get_next_cw_pos(p, b)\n if debug:\n print(\"Add c into B. Next move is B={}, c={}, b={}.\".format(B,c,b))\n else:\n b = c\n c = get_next_cw_pos(p, b)\n if debug:\n print(\"No find black pixel. Next move is c={}, b={}\".format(c,b))\n \n \n # Draw Boundary with orig\n boundary_overlay_img = img.copy()\n for b_coord in B:\n boundary_overlay_img[b_coord[1]][b_coord[0]] = boundary_draw_color\n \n # Draw just boundary\n boundary_img = np.ones(img.shape) * 255\n for boundary in B:\n boundary_img[boundary[1], boundary[0]] = (0,0,0)\n\n return B, boundary_overlay_img, boundary_img\n\n# ========== Skeletonize ========== \ndef skeletonize(img, gray_then_thres=False, debug=False):\n \"\"\" OpenCV function to return a skeletonized version of img, a Mat object\"\"\"\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n if gray_then_thres:\n _, img = cv2.threshold(img,250,255,cv2.THRESH_BINARY)\n img = cv2.bitwise_not(img)\n\n # hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/\n ret,img = cv2.threshold(img,10,255,0)\n\n img = img.copy() # don't clobber original\n skel = img.copy()\n\n skel[:,:] = 0\n kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))\n \n count = 0\n while True:\n eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)\n temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)\n temp = cv2.subtract(img, temp) \n skel = cv2.bitwise_or(skel, temp)\n\n img[:,:] = eroded[:,:]\n count += 1\n if debug:\n print(\"count=\", count)\n if cv2.countNonZero(img) == 0:\n break\n\n\n return skel\n\n# ========== Image Moments ========== \n# For each relevant region/object, compute the area, \n# orientation, and circularity (Emin/Emax). Also, identify \n# and count the boundary pixels of each region, and compute \n# compactness, the ratio of the area to the perimeter.\ndef calc_center_of_mass(img, obj_color):\n x_bar = 0\n y_bar = 0\n area = 0\n \n for i in range(img.shape[1]):\n for j in range(img.shape[0]):\n if np.any(np.all(img[j][i] == obj_color)):\n area += 1\n x_bar += i\n y_bar += j\n \n x_bar = x_bar/area\n y_bar = y_bar/area\n \n return area, x_bar, y_bar\n\ndef calc_perimeter(boundary_img, boundary_color=[0,0,0]):\n perimeter = 0\n\n for i in range(boundary_img.shape[1]):\n for j in range(boundary_img.shape[0]):\n if np.any(np.all(boundary_img[j][i] == boundary_color)):\n perimeter += 1\n return perimeter\n\ndef calc_second_moment(img, obj_color,x_bar, y_bar, area):\n a,b,c = 0,0,0\n m_11, m_20, m_02 = 0,0,0\n\n for i in range(img.shape[1]): # x\n for j in range(img.shape[0]): # y\n if np.any(np.all(img[j][i] == obj_color)):\n a += pow((i - x_bar), 2)\n b += 2 * (i-x_bar) * (j-y_bar)\n c += pow((j - y_bar), 2)\n m_20 += pow(i, 2)\n m_02 += pow(j, 2)\n m_11 += (i * j)\n\n h = pow(pow((a-c), 2) + pow(b,2), 0.5)\n \n E_min = (a+c)/2 - pow((a-c),2)/(2*h) - pow(b,2)/(2*h) if h>0 else (a+c)/2\n E_max = (a+c)/2 + pow((a-c),2)/(2*h) + pow(b,2)/(2*h) if h>0 else (a+c)/2\n circularity = E_min/E_max if (E_min > 0 and E_max > 0) else 0\n\n # Orientation\n\n # orientation = 0.5 * np.arctan((2*b)/(a+c)) if (a+c) > 0 else 0 # 1\n # arctan_num = (2 * (b - x_bar * y_bar)) # 2\n # arctan_denum = ((a - pow(x_bar, 2)) - (c - pow(y_bar, 2))) # 2\n # orientation = np.rad2deg(0.5 * np.arctan(arctan_num/arctan_denum)) #2\n\n mu_bar_20 = (m_20/area) - pow(x_bar, 2)\n mu_bar_02 = (m_02/area) - pow(y_bar, 2)\n mu_bar_11 = (m_11/area) - (x_bar * y_bar)\n arctan_in = (2 * mu_bar_11) / (mu_bar_20 - mu_bar_02)\n orientation = np.rad2deg(0.5 * np.arctan(arctan_in))\n\n return a,b,c,h,E_min,E_max,circularity,orientation\n\n# In: x,y + rgb channel image\ndef calc_moment_numbers(img, obj_color, boundary_img, debug=False):\n perimeter = calc_perimeter(boundary_img, boundary_color=[0,0,0])\n area, x_bar, y_bar = calc_center_of_mass(img, obj_color)\n compactness = pow(perimeter, 2)/area\n ratio_area_perim = area/perimeter\n a,b,c,h,E_min,E_max,circularity,orientation = calc_second_moment(img, obj_color, x_bar, y_bar, area)\n\n if debug:\n print(\"a={},b={},c={},h={},E_min={},E_max={}\".format(a,b,c,h,E_min,E_max))\n print(\"x_bar={}, y_bar={}\".format(x_bar, y_bar))\n print(\"Circularity={},orientation={}\".format(circularity,orientation))\n print(\"Compactness={}, Ratio(area,perim)={}\".format(compactness, ratio_area_perim))\n \n moment_res = {\n 'area': area,\n 'perimeter': perimeter,\n 'ratio_area_perim': ratio_area_perim,\n 'compactness': compactness,\n 'orientation': orientation,\n 'circularity': circularity\n }\n return moment_res\n","sub_path":"hw3/hw3_submit/src/hw3_p1_utils.py","file_name":"hw3_p1_utils.py","file_ext":"py","file_size_in_byte":13914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"257355072","text":"from django.conf.urls import url,include\nfrom . import views,feed\napp_name='boke'\nurlpatterns = [\n url(r'^$',views.index,name='index'),\n url(r'^archives/(\\d+)/(\\d+)/$',views.archives,name='archives'),\n url(r'^category/(\\d+)/$',views.category,name='category'),\n url(r'^catetag/(\\d+)/$',views.catetag,name='catetag'),\n url(r'^rss/$',feed.BlogFeed(),name='rss'),\n url(r'contactus/$',views.contactus,name='contactus'),\n url(r'^addimg/$',views.addimg.as_view(),name='addimg'),\n url(r'^single/(\\d+)/$',views.single,name='single'),\n]","sub_path":"demo1/boke/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"476153437","text":"#!/usr/bin/python3\n\nimport requests\nimport binascii\nimport os\nimport sys\n\n\ndef searchcover(rom):\n baseurl = \"https://art.gametdb.com/ds/coverS/\"\n langList = ['EN/', 'US/', 'JA/', 'DE/', 'KO/']\n filename = tid + '.png'\n for lang in langList:\n if not nds_rom:\n baseurl = 'https://github.com/DefKorns/rom-cover-generator/raw/master/boxart/'\n lang = ''\n\n url = baseurl + lang + filename\n\n r = requests.get(url)\n if r.status_code == 200:\n if not nds_rom:\n filename = rom_title + rom_extension + '.png'\n\n with open(filename, 'wb') as f:\n f.write(r.content)\n if not nds_rom:\n continue\n else:\n break\n\n\ndef gettid(romfile):\n if os.path.isfile(romfile):\n with open(romfile, 'rb') as f:\n f.seek(12)\n return f.read(4).decode(\"utf-8\")\n\n\ndef romCRC32(romfile):\n with open(romfile, \"rb\") as f:\n buf = (binascii.crc32(f.read()) & 0xFFFFFFFF)\n return \"%08X\" % buf\n\n\ndef rename(old_file, new_file):\n if os.path.isfile(old_file):\n os.rename(old_file, new_file)\n\n\ndef remove(filetodelete):\n if os.path.isfile(filetodelete):\n os.remove(filetodelete)\n\n\ndef valid_arg(arg, multilist):\n isValid = any(arg in sublist for sublist in multilist)\n return isValid\n\n\ndef help():\n print(\"\\nUsage: \\n python \", os.path.basename(\n __file__), \"titleID | ndsfile [titleID] | ndsfile | files | [options]...\")\n print(\"\\nFiles: \\n Rom files of type: \\\"nes\\\", \\\"snes\\\", \\\"gb\\\", \\\"gbc\\\", \\\"sms\\\", \\\"gen\\\", \\\"gg\\\", \\\"md\\\", \\\"nds\\\"\")\n print(\"\\nOptions: \\n -?, -h, -help\t\t\tThis information screen\")\n print(\" md Convert Mega Drive roms \\\".md\\\" to nds compatible roms \\\".gen\\\" and gets it's artwork\")\n print(\" -png Optimize png files\")\n print(\"\\nExamples: \\n python \", os.path.basename(\n __file__), \".nes Rename matching title \\\"png\\\" files to the rom CRC\")\n print(\" python \", os.path.basename(\n __file__), \"-? Display help info\")\n print(\" python \", os.path.basename(\n __file__), \"-png Compress \\\"png\\\" files\")\n sys.exit()\n\n\nif len(sys.argv) == 1:\n help()\n\nfor arg in sys.argv:\n helpArgs = ['help', '-h', '-?']\n romArgs = ['snes', 'gbc', 'nes', 'gb', 'sms', 'gen', 'gg', 'md']\n allRoms = ['all', '-a', '*.*']\n arg_list = [helpArgs, romArgs, 'nds', allRoms]\n\nif not valid_arg(arg, arg_list):\n help()\n\nif arg in helpArgs:\n help()\n\nif arg == 'nds':\n nds_rom = True\n for romfile in os.listdir(\".\"):\n if romfile.endswith('.'+arg):\n tid = gettid(romfile)\n searchcover(tid)\n\nif arg in romArgs:\n nds_rom = False\n for romfile in os.listdir(\".\"):\n if romfile.endswith('.' + arg):\n tid = romCRC32(romfile)\n rom_title, rom_extension = os.path.splitext(romfile)\n if arg == 'md':\n rom_extension = 'gen'\n rename(romfile, rom_title + rom_extension)\n searchcover(tid)\n\nif arg in allRoms:\n print('soon')\n sys.exit()\n","sub_path":"getcover.py","file_name":"getcover.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"53352976","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\nlink = \"http://suninjuly.github.io/registration1.html\"\n\ntry:\n driver = webdriver.Chrome()\n driver.get(link)\n\n first_name = driver.find_element(By.CSS_SELECTOR, \".first_block .form-control.first\").send_keys(\"Katya\")\n last_name = driver.find_element(By.CSS_SELECTOR, \".first_block .form-control.second\").send_keys(\"Makey\")\n email = driver.find_element(By.CSS_SELECTOR, \".first_block .form-control.third\").send_keys(\"katya@mail.ru\")\n submit_btn = driver.find_element(By.CSS_SELECTOR, \"button.btn\").click()\n\n time.sleep(2)\n\n welcome_txt_el = driver.find_element(By.TAG_NAME, \"h1\")\n welcome_txt = welcome_txt_el.text\n assert \"Congratulations! You have successfully registered!\" == welcome_txt\n\nfinally:\n time.sleep(10)\n print(welcome_txt)\n driver.quit()\n","sub_path":"test_lesson1_6_step10.py","file_name":"test_lesson1_6_step10.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"120727109","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.urls import reverse\nfrom django.views import generic\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom .models import Document, Field, CompiledDoc, CompiledField\nfrom .forms import *\nfrom xhtml2pdf import pisa\nfrom io import BytesIO\nimport os\nimport re\nimport datetime\nimport xlsxwriter\nimport csv\nimport xlwt\n\n\ndef index(request):\n template = 'form/index.html'\n for document in Document.objects.all():\n if document.date is None:\n document.delete()\n if request.method == 'GET':\n ricerca = request.GET.get('search', '')\n ordine = request.GET.get('order', '')\n if 'nameup' == ordine:\n documents_list = Document.objects.filter(titolo__contains=ricerca).order_by('-titolo', '-date')\n elif 'namedown' == ordine:\n documents_list = Document.objects.filter(titolo__contains=ricerca).order_by('titolo', '-date')\n elif 'dataup' == ordine:\n documents_list = Document.objects.filter(titolo__contains=ricerca).order_by('-date', 'titolo')\n elif 'datadown' == ordine:\n documents_list = Document.objects.filter(titolo__contains=ricerca).order_by('date', 'titolo')\n else:\n documents_list = Document.objects.filter(titolo__contains=ricerca).order_by('titolo', '-date')\n paginator = Paginator(documents_list, 15, allow_empty_first_page=True)\n page = request.GET.get('page')\n documents = paginator.get_page(page)\n page_list = [i for i in range(1, paginator.num_pages + 1)]\n context = {'documents': documents, 'page_list': page_list}\n return render(request, template, context)\n else:\n return HttpResponseRedirect(reverse('form:index'))\n\n\ndef detail(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n if request.method == 'POST':\n compiled_doc = CompiledDoc(document=document, date=datetime.datetime.now())\n compiled_doc.save()\n fields = Field.objects.filter(document=document)\n for field in fields:\n comp_field = CompiledField(field=field, content=request.POST.get(field.name, 'off'),\n compiled_doc=compiled_doc, name=field.name)\n comp_field.save()\n return HttpResponseRedirect(reverse('form:submit', args=(document_id,)))\n template = 'form/detail.html'\n namelist = []\n create_input(document, 'textarea', 80, namelist, True)\n create_input(document, 'field', 7, namelist, True)\n find_input(document, namelist, 'checkbox', '<input.*?type=\"checkbox\".*?/>')\n find_input(document, namelist, 'radiobutton', '<input.*?type=\"radio\".*?/>')\n find_input(document, namelist, 'select', '<select.*?</select>')\n context = {'document': document}\n return render(request, template, context)\n\n\ndef create_input(document, fieldtype, us, namelist=None, save=False):\n if namelist is None:\n namelist = []\n name = ''\n n = 1\n field_match = re.search(r'_{' + str(us) + '}_*', str(document.content))\n while field_match is not None:\n inputtype = 'text'\n\n # Trova e/o assegna nome\n name_match = re.search(r'\\[.*?\\]', str(document.content)[field_match.end():])\n if name_match is not None and name_match.start() == 0:\n name = findname(name_match)\n inputtype = findtype(name_match)\n document.content = re.sub(r'\\[.*?\\]', \"\", str(document.content), 1)\n if not checkname(name, namelist):\n if save is True:\n name = fieldtype + str(n)\n namelist.append(name)\n n = n + 1\n else:\n name = fieldtype\n\n # crea field\n if save:\n try:\n field = Field.objects.get(document=document, name=name)\n except ObjectDoesNotExist:\n field = Field(document=document, name=name)\n field.save()\n\n if fieldtype == 'textarea':\n document.content = re.sub(r'_{80}_*', '<textarea name=\"' + str(name) +\n '\" class=\"form-control\" rows=\"5\" cols=\"100\" /></textarea>', str(document.content),\n 1)\n else:\n if inputtype == 'testo':\n document.content = re.sub(r'_{7}_*', '<input type=\"text\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" />', str(document.content), 1)\n elif inputtype == 'obbligatorio':\n document.content = re.sub(r'_{7}_*', '<input type=\"text\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" required />', str(document.content), 1\n )\n elif inputtype == 'numero':\n document.content = re.sub(r'_{7}_*', '<input type=\"number\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" />', str(document.content), 1)\n elif inputtype == 'data':\n document.content = re.sub(r'_{7}_*', '<input type=\"date\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" />', str(document.content), 1)\n elif inputtype == 'email':\n document.content = re.sub(r'_{7}_*', '<input type=\"email\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" />', str(document.content), 1)\n else:\n document.content = re.sub(r'_{7}_*', '<input type=\"text\" name=\"' + str(name) +\n '\" maxlength=\"100\" class=\"form-control\" />', str(document.content), 1)\n\n # nuova ricerca\n field_match = re.search(r'_{' + str(us) + '}_*', str(document.content))\n return document\n\n\ndef findname(match):\n virgola_match = re.search(r',', match.group())\n if virgola_match is None:\n return match.group()[1:-1]\n name_match = re.search(r'\\[.*?,', match.group())\n if name_match is not None:\n return name_match.group()[1:-1]\n return \"\"\n\n\ndef findtype(match):\n virgola_match = re.search(r',', match.group())\n if virgola_match is None:\n return \"\"\n type_match = re.search(r',.*?\\]', match.group())\n if type_match is not None:\n return type_match.group()[1:-1]\n return \"\"\n\n\ndef find_input(document, namelist, typename, match):\n name = ''\n n = 1\n new_content = str(document.content)\n field_match = re.search(match, new_content)\n while field_match is not None:\n\n # Trova e/o assegna nome\n name_match = re.search(r'name=\".*?\"', field_match.group())\n if name_match is not None:\n name = name_match.group()[6:-1]\n if not checkname(name, namelist):\n name = typename + str(n)\n namelist.append(name)\n n = n + 1\n\n # crea field\n try:\n field = Field.objects.get(document=document, name=name)\n except ObjectDoesNotExist:\n field = Field(document=document, name=name)\n field.save()\n\n # nuova ricerca\n new_content = re.sub(match, '', new_content, 1)\n field_match = re.search(match, new_content)\n return document\n\n\ndef checkname(new_name, namelist):\n if str(new_name) == '':\n return False\n if not str(new_name).isalnum():\n return False\n for name in namelist:\n if str(name) == str(new_name):\n return False\n namelist.append(new_name)\n return True\n\n\n@login_required\ndef edit(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n if request.method == 'POST':\n form = DocumentForm(request.POST)\n if form.is_valid():\n document.titolo = form.cleaned_data['titolo']\n document.date = datetime.datetime.now()\n document.content = form.cleaned_data['content']\n document.save()\n return HttpResponseRedirect(reverse('form:edit', args=(document_id,)))\n form = DocumentForm(initial={'titolo': document.titolo, 'content': document.content})\n create_input(document, 'textarea', 80)\n create_input(document, 'field', 7)\n template = 'form/edit.html'\n context = {'document': document, 'form': form}\n return render(request, template, context)\n\n\n@login_required\ndef new(request):\n document = Document()\n document.titolo = 'Nuovo documento'\n document.content = ''\n document.save()\n return HttpResponseRedirect(reverse('form:edit', args=(document.id,)))\n\n\ndef create_pdf(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n name = str(document.titolo).replace(' ', '_')\n response = HttpResponse(content_type='form/pdf')\n response['Content-Disposition'] = \"filename=\" + str(name) + \".pdf\"\n myhtml = document.content\n myhtml = re.sub(r'\\[.*?\\]', \"\", myhtml)\n myhtml = re.sub(r'<input.*?type=\"checkbox\".*?/>', \"[ ]\", myhtml)\n myhtml = re.sub(r'<input.*?type=\"radio\".*?/>', \"O\", myhtml)\n myhtml = re.sub(r'<select.*?</select>', \"__________\", myhtml)\n pdf = pisa.CreatePDF(myhtml, dest=response, link_callback=link_callback)\n if pdf.err:\n return render(request, 'We had some errors <pre>' + myhtml + '</pre>')\n return response\n\n\ndef link_callback(uri):\n # Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources\n surl = settings.STATIC_URL\n sroot = settings.STATIC_ROOT\n murl = settings.MEDIA_URL\n mroot = settings.MEDIA_ROOT\n if uri.startswith(murl):\n path = os.path.join(mroot, uri.replace(murl, \"\"))\n elif uri.startswith(surl):\n path = os.path.join(sroot, uri.replace(surl, \"\"))\n else:\n return uri\n if not os.path.isfile(path):\n raise Exception('media URI must start with %s or %s' % (surl, murl))\n return path\n\n\n@login_required\ndef registrations(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n compiled_docs = CompiledDoc.objects.filter(document=document).order_by('date')\n template = 'form/registrations.html'\n context = {'document': document, 'compiled_docs': compiled_docs}\n return render(request, template, context)\n\n\n@login_required\ndef export_xlsx(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n name = str(document.titolo).replace(' ', '_')\n compiled_docs = CompiledDoc.objects.filter(document=document).order_by('date')\n\n output = BytesIO()\n workbook = xlsxwriter.Workbook(output)\n worksheet = workbook.add_worksheet(str(name)[:30])\n\n bold = workbook.add_format({'bold': True})\n\n r = 1\n for comp_doc in compiled_docs:\n comp_fields = CompiledField.objects.filter(compiled_doc=comp_doc)\n if compiled_docs[compiled_docs.count() - 1] is comp_doc:\n i = 0\n for comp_filed in comp_fields:\n worksheet.write(0, i, str(comp_filed.name), bold)\n i = i + 1\n c = 0\n for comp_filed in comp_fields:\n worksheet.write(r, c, str(comp_filed.content))\n c = c + 1\n r = r + 1\n\n workbook.close()\n\n output.seek(0)\n response = HttpResponse(output.read(), content_type='application/vnd.ms-excel')\n response['Content-Disposition'] = 'attachment; ' + 'filename=' + str(name)[:30] + '.xlsx'\n return response\n\n\n@login_required\ndef export_csv(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n name = str(document.titolo).replace(' ', '_')\n compiled_docs = CompiledDoc.objects.filter(document=document).order_by('date')\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; ' + 'filename=' + str(name)[:30] + '.csv'\n writer = csv.writer(response)\n\n for comp_doc in compiled_docs:\n if compiled_docs[compiled_docs.count() - 1] is comp_doc:\n comp_fields = CompiledField.objects.filter(compiled_doc=comp_doc)\n lista = [comp_filed.name for comp_filed in comp_fields]\n writer.writerow(lista)\n writer.writerow([])\n for comp_doc in compiled_docs:\n comp_fields = CompiledField.objects.filter(compiled_doc=comp_doc)\n lista = [comp_filed.content for comp_filed in comp_fields]\n writer.writerow(lista)\n\n return response\n\n\n@login_required\ndef export_xls(request, document_id):\n document = get_object_or_404(Document, pk=document_id)\n name = str(document.titolo).replace(' ', '_')\n compiled_docs = CompiledDoc.objects.filter(document=document).order_by('date')\n\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; ' + 'filename=' + str(name)[:30] + '.xls'\n\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet(str(name)[:30])\n\n bold = xlwt.XFStyle()\n bold.font.bold = True\n\n font_style = xlwt.XFStyle()\n\n r = 1\n for comp_doc in compiled_docs:\n comp_fields = CompiledField.objects.filter(compiled_doc=comp_doc)\n if compiled_docs[compiled_docs.count() - 1] is comp_doc:\n i = 0\n for comp_filed in comp_fields:\n ws.write(0, i, str(comp_filed.name), bold)\n i = i + 1\n c = 0\n for comp_filed in comp_fields:\n ws.write(r, c, str(comp_filed.content), font_style)\n c = c + 1\n r = r + 1\n\n wb.save(response)\n\n return response\n\n\nclass SubmitView(generic.DetailView):\n model = Document\n template_name = 'form/submit.html'\n","sub_path":"tesina/form/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"609904718","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom math import log, sqrt\nfrom kivy.logger import Logger\nfrom kivy.lang import Builder\nfrom kivy.config import Config\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.label import Label\nfrom kivy.clock import Clock\n\nfrom vendor.pygeoj import pygeoj as pygeoj\nfrom vendor.kivygardenmapview import MapMarkerPopup, GeoJsonMapLayer, MapMarkerLabel\nfrom lib.mapTools import SourceArcGIS\nimport pglogdatabase as pgdb\nimport gui.layout as SIZE\nimport gui.colours as Color\n\n\n\n_geojson = pygeoj.new()\n\n\ndef wpts_to_geojson(waypoints):\n json = _geojson\n track = [(wpt[1], wpt[0]) for wpt in waypoints]\n _geojson.add_feature(geometry={'type': 'LineString',\n 'coordinates': track},\n properties={\"stroke\": Color.as_hex_str(Color.YELLOW),\n \"stroke_width\": 1})\n\n\nclass MyMapPage(BoxLayout):\n def __init__(self, **kwargs):\n Builder.load_file(os.path.join('gui', 'pages', 'MyMap.kv'))\n self.map_source = SourceArcGIS\n super(MyMapPage, self).__init__(**kwargs)\n\n def on_parent(self, widget, parent):\n self.add_my_takeoffs()\n self.add_my_tracklogs()\n\n def refresh(self):\n self.reload()\n\n def reload(self):\n for l in self.ids.map_view._layers:\n try:\n for m in l.markers:\n self.ids.map_view.remove_marker(m)\n except AttributeError:\n pass\n self.ids.map_view.remove_layer(l)\n self.ids.map_view._default_marker_layer = None\n self.on_parent(self, self.parent)\n\n def add_my_takeoffs(self):\n sites = pgdb.database.get_user_sites()\n map_view = self.ids.map_view\n lat_ext = [90, -90]\n lon_ext = [180, -180]\n lat_momentum = lon_momentum = count_momentum = 0\n for site in sites:\n if 'coordinates' in site.keys():\n coord = site['coordinates']\n lat_ext[0] = min(coord['lat'], lat_ext[0])\n lat_ext[1] = max(coord['lat'], lat_ext[1])\n lon_ext[0] = min(coord['long'], lon_ext[0])\n lon_ext[1] = max(coord['long'], lon_ext[1])\n lat_momentum += coord['lat']\n lon_momentum += coord['long']\n count_momentum += 1\n takeoff_marker = MapMarkerPopup(lat=coord['lat'], lon=coord['long'])\n takeoff_marker.add_widget(MapMarkerLabel(text=site['name'], width=2 * SIZE.MapMarkerPopup.width))\n takeoff_marker.is_open = True\n map_view.add_marker(takeoff_marker)\n\n self.ids.map_view.center_on(lat_momentum / max(count_momentum, 1),\n lon_momentum / max(count_momentum, 1))\n lat_dist = abs(lat_ext[0] - lat_ext[1])\n lon_dist = abs(lon_ext[0] - lon_ext[1])\n dist = sqrt(lat_dist**2 + lon_dist**2)\n zoom = int(abs(log(max(dist, 0.1)) / log(2) - 10))\n self.ids.map_view.zoom = zoom\n\n def add_my_tracklogs(self):\n map_view = self.ids.map_view\n flights = pgdb.database.get_all_flights()\n\n for flight in flights:\n try:\n wpts_to_geojson(flight['xctrack'])\n except KeyError:\n pass\n if flights:\n json = _geojson.as_dict()\n geojson_layer = GeoJsonMapLayer(geojson=json)\n map_view.add_layer(geojson_layer)\n","sub_path":"gui/pages/mymap.py","file_name":"mymap.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"461304785","text":"from db.models import Cv, Cvterm, Cvtermprop, Feature, Featureloc, Featureprop\nfrom db.models import Organism\nimport gzip\nimport re\nimport sys\n\n\nclass GFFManager:\n ''' GFF loader management '''\n\n def create_gff_disease_region_features(self, **options):\n ''' Create disease region features '''\n if options['org']:\n org = options['org']\n else:\n org = 'human'\n\n disease = None\n disease_short = None\n organism = Organism.objects.get(common_name=org)\n if options['gff'].endswith('.gz'):\n f = gzip.open(options['gff'], 'rb')\n else:\n f = open(options['gff'], 'rb')\n\n for line in f:\n line = line.decode(\"utf-8\")\n if(line.startswith(\"##\")):\n if(line.startswith(\"##Key Disease:\")):\n disease = line[14:].strip()\n\n # lookup disease short name\n cv = Cv.objects.get(name='disease')\n cvterm = Cvterm.objects.get(cv=cv, name=disease)\n termtype = Cvterm.objects.get(name='disease short name')\n cvtermprop = Cvtermprop.objects.get(cvterm=cvterm,\n type=termtype)\n disease_short = cvtermprop.value\n print('disease... '+disease)\n continue\n\n parts = re.split('\\t', line)\n if(len(parts) != 9):\n continue\n\n name = self._get_name(parts[8])\n uniquename = (parts[0] + \"_\" + name + \"_\" + parts[3] + \"_\" +\n parts[4] + \"_\" + disease_short)\n feature = self._get_feature(name, uniquename, 'sequence',\n parts[2], organism)\n srcfeature = (Feature.objects\n .filter(organism=organism) # @UndefinedVariable\n .get(uniquename=parts[0])) # @UndefinedVariable\n print('get srcfeature... '+parts[0])\n fmin = int(parts[3])-1\n feature.save()\n featureloc = Featureloc(feature=feature, srcfeature=srcfeature,\n fmin=fmin, fmax=parts[4],\n locgroup=0, rank=0)\n featureloc.save()\n print('loaded feature... ' + feature.uniquename + ' on ' +\n srcfeature.uniquename)\n\n if disease:\n cv = Cv.objects.get(name='disease')\n cvterm = Cvterm.objects.get(cv=cv, name=disease)\n feaureprop = Featureprop(feature=feature, type=cvterm, rank=0)\n feaureprop.save()\n print('loaded featureprop... '+disease)\n return\n\n def _get_name(self, attributes):\n parts = re.split(';', attributes)\n for part in parts:\n if(part.startswith('Name=')):\n return part[5:]\n return \"\"\n\n def _get_feature(self, name, uniquename, cvName, cvtermName, organism):\n cv = Cv.objects.get(name=cvName)\n termtype = Cvterm.objects.get(cv=cv, name=cvtermName)\n return Feature(organism=organism, name=name, uniquename=uniquename,\n type=termtype, is_analysis=0, is_obsolete=0)\n\n\nclass GFF:\n ''' GFF file object - based on GFF3 specifications '''\n\n def __init__(self, line='dummy\\tdummy\\tregion\\t' + str(sys.maxsize) +\n '\\t-1\\t.\\t.\\t.\\t\\t', field_delim=';', key_value_delim='='):\n parts = re.split('\\t', line)\n if(len(parts) != 9):\n raise GFFError(\"GFF error: wrong number of columns\")\n self.seqid = parts[0]\n self.source = parts[1]\n self.type = parts[2]\n self.start = int(parts[3])\n self.end = int(parts[4])\n self.score = parts[5]\n self.strand = parts[6]\n self.phase = parts[7]\n self.attrStr = parts[8]\n self.attrs = {}\n self._parseAttributes(field_delim, key_value_delim)\n\n def _parseAttributes(self, field_delim, key_value_delim):\n ''' Parse the attributes column '''\n parts = re.split(field_delim, self.attrStr.strip())\n for p in parts:\n if(p == ''):\n continue\n at = re.split(key_value_delim, p.strip())\n if len(at) == 2:\n self.attrs[at[0]] = at[1]\n else:\n self.attrs[at[0]] = \"\"\n\n def getAttributes(self):\n return self.attrs\n\n\nclass GFFError(Exception):\n ''' GFF parse error '''\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n","sub_path":"django_template/local_apps/db/management/loaders/GFF.py","file_name":"GFF.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"399995335","text":"from read_files import read_html_files\nimport json\n\n''' Data exploration to find keywords to put into keywords.txt '''\n\nscams = read_html_files('scam_HTML')\nnon_scams = read_html_files('non_scam_HTML')\n\nfor i, text in enumerate(scams):\n scams[i] = set(text.split(' '))\n\nfor i, text in enumerate(non_scams):\n non_scams[i] = set(text.split(' '))\n\n# Find keywords by finding most common words used in these sites\n# Remove keywords that also appear in non_scam_HTML\n# Key -> keyword, value -> number of occurances\nkeywords = {}\n\nfor scam in scams:\n for word in scam:\n if word in keywords:\n keywords[word] += 1\n else:\n keywords[word] = 1\n\n# Sort dict by values to see most frequently occuring keywords\nsorted_keyword_list = sorted(list( zip(keywords.values(), keywords.keys()) ))\nsorted_keywords = {keyword: num_occur for num_occur, keyword in sorted_keyword_list}\n\n# I manually classified these keywords based on whether or not they're indicative of a scam and added them to keywords.txt\nprint(json.dumps(sorted_keywords, indent=4))\n\n''' Testing that keywords appear in scam html but not in non scam html '''\n\nwith open('keywords.txt') as f:\n # Using a set of keywords to reduce lookup time\n keywords = set( f.read().split('\\n') )\n\ndef calculate_keyword_collisions(list_of_pages):\n collisions = []\n\n for text in list_of_pages: \n keyword_match_counter = 0\n for word in text:\n if word in keywords:\n # Print word when running function on non_scams to determine keywords that appear in non_scams\n # print(word)\n keyword_match_counter += 1\n collisions.append(keyword_match_counter)\n\n return collisions\n\nprint('Number of scam keyword collisions for each site:', calculate_keyword_collisions(scams))\nprint('Number of non scam keyword collisions for each site:', calculate_keyword_collisions(non_scams))\n","sub_path":"keyword_classifier/find_keywords.py","file_name":"find_keywords.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"505390470","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom models.init_product_type_databases import Product\nfrom models.init_all_product_databases import TheProduct\nfrom models.init_all_store_product_databases import StoreProductType\nfrom sqlalchemy.orm import sessionmaker\n\n\nimport os\nfrom os import path\nd = path.dirname(__file__)\nroot = os.path.dirname(d)\nthe_path = root+'/'+'testDB.db'\nengine = create_engine('sqlite:///'+the_path)\nBase = declarative_base()\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\nfrom configs import storeID\n\n\n\n\n\n\n\n\n# list1 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14']\n\n\n#Product.status == StoreProductType.status == 0,\n#StoreProductType.store_id == 32,Product.parent_id==0\n\ndef yiji_list():\n a = session.query(Product.product_type_name).filter(Product.product_type_id == StoreProductType.product_type_id,Product.status == 0, StoreProductType.status == 1,StoreProductType.store_id == storeID,Product.parent_id==0).all()\n\n\n print(a)\n print(len(a))\n list1 = []\n for i in a:\n list1.append(i[0])\n\n # list1 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14']\n\n if len(list1) <= 12:\n return list1\n\n else:\n for i in range(11, 2000, 12):\n try:\n if list1[i] is not None:\n list1.insert(i, '下一页')\n list1.insert(i + 1, '上一页')\n except IndexError:\n break\n yiji_listfenge = [list1[x:x + 12] for x in range(0, len(list1), 12)]\n return yiji_listfenge\n\n# print(yiji_list(list1))\n\n# yiji_listfenge = [list1[x:x+12] for x in range(0,len(list1),12)]\n\nprint(yiji_list())\n\n\n\n\n\n","sub_path":"controllers/fanhui_yiji_fenlei_list.py","file_name":"fanhui_yiji_fenlei_list.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"87079955","text":"from typing import Any, Dict, List, Type, TypeVar, Union, cast\n\nimport attr\n\nfrom ..models.null import Null\nfrom ..models.otoroshimodels_rs_algo_settings_type import OtoroshimodelsRSAlgoSettingsType\nfrom ..types import UNSET, Unset\n\nT = TypeVar(\"T\", bound=\"OtoroshimodelsRSAlgoSettings\")\n\n\n@attr.s(auto_attribs=True)\nclass OtoroshimodelsRSAlgoSettings:\n \"\"\"Settings to use RSA signing algorithm\"\"\"\n\n private_key: Union[Null, Unset, str] = UNSET\n size: Union[Unset, int] = UNSET\n public_key: Union[Unset, str] = UNSET\n type: Union[Unset, OtoroshimodelsRSAlgoSettingsType] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n private_key: Union[Dict[str, Any], Unset, str]\n if isinstance(self.private_key, Unset):\n private_key = UNSET\n elif isinstance(self.private_key, Null):\n private_key = UNSET\n if not isinstance(self.private_key, Unset):\n private_key = self.private_key.to_dict()\n\n else:\n private_key = self.private_key\n\n size = self.size\n public_key = self.public_key\n type: Union[Unset, str] = UNSET\n if not isinstance(self.type, Unset):\n type = self.type.value\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if private_key is not UNSET:\n field_dict[\"privateKey\"] = private_key\n if size is not UNSET:\n field_dict[\"size\"] = size\n if public_key is not UNSET:\n field_dict[\"publicKey\"] = public_key\n if type is not UNSET:\n field_dict[\"type\"] = type\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n\n def _parse_private_key(data: object) -> Union[Null, Unset, str]:\n if isinstance(data, Unset):\n return data\n try:\n if not isinstance(data, dict):\n raise TypeError()\n _private_key_type_0 = data\n private_key_type_0: Union[Unset, Null]\n if isinstance(_private_key_type_0, Unset):\n private_key_type_0 = UNSET\n else:\n private_key_type_0 = Null.from_dict(_private_key_type_0)\n\n return private_key_type_0\n except: # noqa: E722\n pass\n return cast(Union[Null, Unset, str], data)\n\n private_key = _parse_private_key(d.pop(\"privateKey\", UNSET))\n\n size = d.pop(\"size\", UNSET)\n\n public_key = d.pop(\"publicKey\", UNSET)\n\n _type = d.pop(\"type\", UNSET)\n type: Union[Unset, OtoroshimodelsRSAlgoSettingsType]\n if isinstance(_type, Unset):\n type = UNSET\n else:\n type = OtoroshimodelsRSAlgoSettingsType(_type)\n\n otoroshimodels_rs_algo_settings = cls(\n private_key=private_key,\n size=size,\n public_key=public_key,\n type=type,\n )\n\n otoroshimodels_rs_algo_settings.additional_properties = d\n return otoroshimodels_rs_algo_settings\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","sub_path":"otoroshi_admin_api_client/models/otoroshimodels_rs_algo_settings.py","file_name":"otoroshimodels_rs_algo_settings.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"504034967","text":"class Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n \n \n nrows = len(nums)\n ncols = len(nums[0])\n \n if nrows * ncols == r * c:\n onedArray = []\n reshaped = [[0] * c for i in range(r)]\n for x in nums:\n onedArray += x\n for index, item in enumerate(onedArray):\n placeRow = index / c\n placeCol = index % c\n reshaped[placeRow][placeCol] = item\n return reshaped\n else:\n return nums\n\n\ntest = Solution()\nlist1 = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]\n\nprint(test.matrixReshape(list1, 4, 3))\n","sub_path":"566 Reshape the Matrix/reshapeMatrix.py","file_name":"reshapeMatrix.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"380049221","text":"# Replace Words\n\n# In English, we have a concept called root, which can be followed by some other\n# word to form another longer word - let's call this word successor. For\n# example, when the root \"an\" is followed by the successor word \"other\", we can\n# form a new word \"another\".\n\n# Given a dictionary consisting of many roots and a sentence consisting of words\n# separated by spaces, replace all the successors in the sentence with the root\n# forming it. If a successor can be replaced by more than one root, replace it\n# with the root that has the shortest length.\n\n# Return the sentence after the replacement.\n\n# Example 1:\n\n# Input: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\n# Output: \"the cat was rat by the bat\"\n\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n trie = Trie()\n for word in dictionary:\n trie.insert(word)\n result = sentence.split(' ')\n for index in range(len(result)):\n result[index] = trie.search_for_root(result[index])\n return ' '.join(result)\n\n\nclass Trie:\n def __init__(self):\n self.trie = {}\n self.endSymbol = '*'\n \n def insert(self, word):\n curr = self.trie\n for letter in word:\n if letter not in curr:\n curr[letter] = {}\n curr = curr[letter]\n curr[self.endSymbol] = True\n \n def search_for_root(self, word):\n curr = self.trie\n for index in range(len(word)):\n if self.endSymbol in curr:\n return word[:index]\n elif word[index] not in curr:\n return word\n else:\n curr = curr[word[index]]\n return word\n ","sub_path":"medium/replace_words.py","file_name":"replace_words.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"252384488","text":"# R-1.3\r\n#Write a short Python function, minmax(data), that takes a sequence of one or more numbers,\r\n# and returns the smallest and largest numbers, in the form of a tuple of length two.\r\n# Do not use the built-in functions min or max in implementing your solution.\r\n\r\ndef minmax(data):\r\n largest = data[0]\r\n smallest = data[0]\r\n for item in data:\r\n if item > largest:\r\n largest = item\r\n elif item < smallest:\r\n smallest = item\r\n return smallest, largest\r\n\r\n\r\nalpha = [2, 2, 3, 4, 5, 6, 7, 8, 99]\r\n\r\nprint(minmax(alpha))\r\n","sub_path":"ridhaentim tugas strukturdata/R-1.3.py","file_name":"R-1.3.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"270936197","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pymongo\r\nimport pandas as pd\r\nfrom bson import ObjectId\r\n\r\n\r\nclass Connection_Mongo: \r\n \r\n def __init__(self, server, mongodb_port):\r\n self.server = server\r\n self.mongodb_port = mongodb_port\r\n self.conexao = pymongo.MongoClient(\"mongodb://\"+server+\":\"+mongodb_port+\"/\")\r\n \r\n \r\n #********CREATE DATABASE********\r\n def create_db(self,name):\r\n \r\n mydb = self.conexao[name]\r\n \r\n #print('Base de Dados carregada!')\r\n \r\n return mydb\r\n \r\n #********DROP DATABASE********\r\n def drop_db(self,name):\r\n \r\n try:\r\n self.conexao.drop_database(name)\r\n \r\n print('Base de Dados deletada!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1)\r\n \r\n \r\n #********CREATE Collection********\r\n def create_collection(self, mydb, name_collection):\r\n \r\n try:\r\n mycol = mydb[name_collection]\r\n \r\n print('Coleção criada!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(mycol)\r\n \r\n #********GET Collection********\r\n def get_collection(self, mydb, name_collection, query, remove_id):\r\n \r\n try:\r\n mycol = mydb[name_collection]\r\n \r\n cursor = mycol.find(query)\r\n \r\n df = pd.DataFrame(list(cursor))\r\n \r\n if remove_id:\r\n del df['_id']\r\n\r\n print('Coleção criada!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(df)\r\n \r\n #********INSERT ONE Collection********\r\n def insert_one_collection(self, mydb, name_collection, vector_name, vector_data):\r\n \r\n try:\r\n \r\n if len(vector_name) == len(vector_data):\r\n \r\n mycol = mydb[name_collection]\r\n \r\n df = pd.DataFrame(columns = vector_name)\r\n \r\n index_df = len(df) + 1\r\n \r\n df.loc[index_df] = vector_data\r\n \r\n mycol.insert_many(df.to_dict('records'))\r\n \r\n print('Informação inserida na coleção com sucesso!')\r\n \r\n else:\r\n \r\n print('Impossível inserir esta informação na coleção')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1)\r\n \r\n #********DROP ONE Collection********\r\n def drop_one_collection(self, mydb, name_collection, identificador):\r\n \r\n try:\r\n \r\n mycol = mydb[name_collection]\r\n \r\n find = mycol.find_one({\"_id\": ObjectId(identificador)})\r\n \r\n mycol.delete_one({'_id': find['_id']})\r\n \r\n print('Informação removida com sucesso!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1) \r\n \r\n #********INSERT Collection PANDAS********\r\n def insert_collection_pandas(self, mydb, name_collection, vec_prec):\r\n \r\n try:\r\n \r\n for i in vec_prec:\r\n \r\n mydb[name_collection].insert_many(i.to_dict('records'))\r\n \r\n indexes = i.columns\r\n \r\n mydb[name_collection].delete_many({indexes[0]: indexes[0]})\r\n \r\n print('Inserção de dataframe na coleção concluída!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1)\r\n \r\n #********DELETE Collection********\r\n def drop_collection(self, mydb, name_collection):\r\n \r\n try:\r\n mydb.drop_collection(name_collection)\r\n \r\n print('Remoção de coleção concluída!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1)\r\n \r\n #********CLEAR Collection********\r\n def clear_collection(self, mydb, name_collection):\r\n \r\n try:\r\n mydb[name_collection].delete_many({})\r\n \r\n print('Remoção de coleção concluída!')\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(1)\r\n \r\n #********COUNT Collection********\r\n def count_collection(self, mydb, name_collection):\r\n \r\n try:\r\n mycol = mydb[name_collection]\r\n \r\n tamanho = mycol.estimated_document_count()\r\n \r\n except ValueError as e:\r\n print('Erro:', e)\r\n \r\n return(tamanho)\r\n \r\n# =============================================================================\r\nx = Connection_Mongo('localhost', '27017')\r\ny = x.create_db('crawler_insideSP_tweets')\r\n\r\n\r\n#inmet = pd.read_csv('2016_11-2017_03-INMET-NEBUL-PRESS.csv', names = ['Estacao','Data','Hora','PressaoAtmEstacao','Nebulosidade'], sep=';')\r\n\r\n#print(inmet)\r\n\r\n#Connection_Mongo.clear_collection(y, 'inmet')\r\n\r\n#Connection_Mongo.insert_collection_pandas(y, 'inmet', [inmet])\r\n\r\n#prec1 = pd.read_csv('2692_SP_2016_11.csv', names = ['municipio', 'codEstacao', 'uf', 'nomeEstacao', 'latitude', 'longitude', 'datahora', 'valorMedida'], sep=';')\r\n#prec2 = pd.read_csv('2692_SP_2016_12.csv', names = ['municipio', 'codEstacao', 'uf', 'nomeEstacao', 'latitude', 'longitude', 'datahora', 'valorMedida'], sep=';')\r\n#prec3 = pd.read_csv('2692_SP_2017_1.csv', names = ['municipio', 'codEstacao', 'uf', 'nomeEstacao', 'latitude', 'longitude', 'datahora', 'valorMedida'], sep=';')\r\n#prec4 = pd.read_csv('2692_SP_2017_2.csv', names = ['municipio', 'codEstacao', 'uf', 'nomeEstacao', 'latitude', 'longitude', 'datahora', 'valorMedida'], sep=';')\r\n#prec5 = pd.read_csv('2692_SP_2017_3.csv', names = ['municipio', 'codEstacao', 'uf', 'nomeEstacao', 'latitude', 'longitude', 'datahora', 'valorMedida'], sep=';')\r\n#\r\n#vec_prec = [prec1,prec2, prec3, prec4, prec5]\r\n\r\n#Connection_Mongo.insert_collection_pandas(y, 'cemaden', vec_prec)\r\n#\r\n# #Connection_Mongo.clear_collection(y, 'inmet')\r\n# \r\n# #y.create_collection('estacoes_sp')\r\n# #y.create_collection('cemaden')\r\n# #y.create_collection('cge')\r\n# #for i in vec_prec: \r\n# # Connection_Mongo.insert_collection_pandas(y, 'inmet', i)\r\n# \r\n#Connection_Mongo.clear_collection(y, 'inmet')\r\n# \r\n# vec_name = ['municipio','codEstacao','uf','nomeEstacao','latitude','longitude','datahora','valorMedida']\r\n# vec_data = ['São Paulo','355030801A','SP','Jardim Paulistano','-46,751','-23,582','2016-11-01 00:00:00.0','0']\r\n# \r\n# Connection_Mongo.drop_one_collection(y, 'inmet', '5d5ebbee06aa53383c331fe0')\r\n# \r\n# #print(y.list_collections)\r\n# =============================================================================\r\n#------------Quantidade de Tweets------------\r\nprint(x.count_collection(y, 'tweets'))\r\n\r\n#------------Obeter Tweets------------\r\ndf = x.get_collection(y,'tweets',{},1)\r\n\r\ndf.to_csv('tweets_insideSP.csv')\r\n\r\n","sub_path":"con_mongodb.py","file_name":"con_mongodb.py","file_ext":"py","file_size_in_byte":7210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45797690","text":"#!usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys\nsys.path.append(\"../../../api-sdk-python\")\n\nimport suning.api as api\n'''\nCreated on 2014年6月6日\n\n@author: dd\n'''\na = api.ItemQueryRequest()\na.status = ''\n\na.pageSize = 20\n\na.categoryCode = 'R3301006'\n\na.brandCode = 'A120'\n\na.pageNo = 1\n\ntry:\n \n f = a.getResponse()\n print(f)\nexcept Exception as e:\n print(e)","sub_path":"test/item/ItemQueryTest.py","file_name":"ItemQueryTest.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"515127208","text":"\"\"\"Script to run stacking scripts on the DESY cluster.\n\nThrough use of argparse, a given configuration for the code can be selected.\nThis can be given from the command line, in the form:\n\npython RunCluster.py -c Desired_Configuration_Name -n Number_Of_Tasks -s\n\nEach available configuration must be listed in \"config.ini\", and controls\noptions for fitting, such as which catalogue is to be used, and which seasons\nof data should be included. If -x is included, then a new job is submitted\nto the cluster. Having submitted the job to the cluster it will be run in\nparallel Number_of_Tasks times. The shell script SubmitOne.sh is called for\neach task, which in turn calls RunLocal.py with the given configuration setting.\n\nThe Wait function will periodically query the cluster\nto check on the status of the job, and will output the job status occasionally.\n\nOnce all sub-tasks are completed, the script will proceed to call\nMergeFiles.run() for the given configuration, combining results.\n\n\"\"\"\nimport subprocess\nimport time\nimport os\nimport os.path\nimport logging\nimport argparse\nimport numpy as np\nfrom flarestack.shared import log_dir, fs_dir\nfrom flarestack.cluster.submitter import Submitter\nfrom flarestack.cluster.make_desy_cluster_script import make_desy_submit_file, submit_file\n\nlogger = logging.getLogger(__name__)\n\nusername = os.path.basename(os.environ['HOME'])\n\ncmd = 'qstat -u ' + username\n\n\ndef wait_for_cluster(job_ids=None):\n logger.warning('The wait_for_cluster function is deprecated! '\n 'Use the Submitter class instead.')\n Submitter.wait_for_cluster(job_ids)\n\n # if not job_ids:\n # wait_for_job()\n # else:\n # try:\n # for i, job_id in enumerate(job_ids):\n #\n # logger.debug(f'waiting for job {job_id}')\n # prog_str = f'{i}/{len(job_ids)}'\n # wait_for_job(job_id, prog_str)\n #\n # except TypeError:\n # logger.debug('Only waiting for one job')\n # wait_for_job(job_ids)\n\n\ndef wait_for_job(job_id=None, progress_str=None):\n \"\"\"\n Runs the command cmd, which queries the status of the job on the\n cluster, and reads the output. While the output is not an empty\n string (indicating job completion), the cluster is re-queried\n every 30 seconds. Occasionally outputs the number of remaining sub-tasks\n on cluster, and outputs full table result every ~ 8 minutes. On\n completion of job, terminates function process and allows the script to\n continue.\n \"\"\"\n\n if not job_id:\n job_id_str = 's'\n else:\n if progress_str:\n job_id_str = f' {progress_str} {job_id}'\n else:\n job_id_str = ' ' + str(job_id)\n\n time.sleep(10)\n\n cmd = f'qstat -u {username}'\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n tmp = process.stdout.read().decode()\n n_total = n_tasks(tmp, job_id)\n i = 31\n j = 6\n while n_total != 0:\n if i > 3:\n\n running_process = subprocess.Popen(\n cmd + \" -s r\", stdout=subprocess.PIPE, shell=True)\n running_tmp = running_process.stdout.read().decode()\n\n if running_tmp != '':\n n_running = n_tasks(running_tmp, job_id)\n else:\n n_running = 0\n\n logger.info(f'{time.asctime(time.localtime())} - Job{job_id_str}:'\n f' {n_total} entries in queue. '\n f'Of these, {n_running} are running tasks, and '\n f'{n_total-n_running} are tasks still waiting to be executed.')\n i = 0\n j += 1\n\n if j > 7:\n logger.info(str(tmp))\n j = 0\n\n time.sleep(30)\n i += 1\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n tmp = process.stdout.read().decode()\n n_total = n_tasks(tmp, job_id)\n\n\ndef submit_to_cluster(path, n_cpu=2, n_jobs=10, ram_per_core=None, **kwargs):\n\n for file in os.listdir(log_dir):\n os.remove(log_dir + file)\n\n # Submits job to the cluster\n\n submit_cmd = \"qsub \"\n\n if n_cpu > 1:\n submit_cmd += \" -pe multicore {0} -R y \".format(n_cpu)\n\n ram_per_core = \"{0:.1f}G\".format(6./float(n_cpu) + 2.) if not ram_per_core else ram_per_core\n print(\"Ram per core:\", ram_per_core)\n\n submit_cmd += \"-t 1-{0}:1 {1} {2} {3}\".format(\n n_jobs, submit_file, path, n_cpu\n )\n\n make_desy_submit_file(ram_per_core, **kwargs)\n\n print(time.asctime(time.localtime()), submit_cmd, \"\\n\")\n\n process = subprocess.Popen(submit_cmd, stdout=subprocess.PIPE, shell=True)\n msg = process.stdout.read().decode()\n print(msg)\n job_id = int(str(msg).split('job-array')[1].split('.')[0])\n\n return job_id\n\n\ndef n_tasks(tmp, job_id):\n \"\"\"\n Returns the number of tasks given the output of qsub\n :param tmp: output of qsub\n :param job_id: int, optional, if given only tasks belonging to this job will we counted\n :return: int\n \"\"\"\n st = str(tmp)\n ids = np.array([int(s.split(' ')[2]) for s in st.split('\\n')[2:-1]])\n\n if job_id:\n return len(ids[ids == job_id])\n else:\n return len(ids)\n\n\nif not os.path.isfile(submit_file):\n make_desy_submit_file()\n","sub_path":"flarestack/cluster/run_desy_cluster.py","file_name":"run_desy_cluster.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"440425395","text":"import numpy as np\n#from Agents.PPO.utils import make_parallel_env\nimport torch\nimport argparse\nfrom tabulate import tabulate\nfrom Env.make_env import make_env\nfrom gym import spaces\nimport config\nfrom PIL import Image\nimport time\nimport os\nimport ray\n\n#ray.init()\n\n\n\n#class DataGenerator():\n #def __init__(self):\n # pass\n #self.args = args\n #self.data_path = data_path\n # self.env = make_parallel_env(args, np.random.randint(5000), 2)\n # self.n_envs = len(self.env)\n#@ray.remote\ndef generate(env, episodes, n_agents):\n def make_start_postion_list(env_hldr):\n '''Assumes agent keys in evn.agents is the same as agent id's '''\n start_positions = []\n for i in range(len(env_hldr.agents.values())):\n start_positions.append(env_hldr.agents[i].pos)\n return start_positions\n\n def make_end_postion_list(env_hldr):\n '''Assumes agent keys in evn.agents is the same as agent id's '''\n end_positions = []\n for i in range(len(env_hldr.goals.values())):\n end_positions.append(env_hldr.goals[i].pos)\n return end_positions\n data = []\n observations = []\n actions = []\n ep_observations = []\n ep_actions = []\n for ep in range(episodes):\n #for ep in range(1):\n #continue_flag = False\n mstar_actions = None\n while mstar_actions is None:\n obs = env.reset()\n # env.render('human')\n start_pos = make_start_postion_list(env)\n end_pos = make_end_postion_list(env)\n mstar_actions = env.graph.mstar_search3(start_pos, end_pos)\n if mstar_actions is None:\n print(\"No M-star solution found for env generated\")\n for a in mstar_actions:\n #assert continue_flag == False\n ep_observations.append(obs)\n for i in range(n_agents):\n data.append((obs[i], a[i]))\n obs, r, dones, info = env.step(a)\n # env.render(mode = 'human')\n ep_actions.append(a)\n if info[\"terminate\"]:\n if info[\"all_agents_on_goal\"] == 1:\n #add ep data\n for ep_obs, ep_a in zip(ep_observations, ep_actions):\n # print(\"observations: {}\".format(ep_obs))\n # print(\"\\nActions: {}\".format(ep_a))\n for agent_handle, agent_obs in ep_obs.items():\n pass\n # data.append((agent_obs, ep_a[agent_handle]))\n \n ####################\n # headers = [\"Channels\"]\n # rows = [[\"Obstacle Channel\"], [\"Other Agent Channel\"], [\"Own Goals Channel\"], \\\n # [\"Own Position Channel\"], [\"Other Goal Channel\"]]\n # rows[0].append(agent_obs[0])\n # rows[1].append(agent_obs[1])\n # rows[2].append(agent_obs[2])\n # rows[3].append(agent_obs[4])\n # rows[4].append(agent_obs[3])\n # print(tabulate(rows, tablefmt = 'fancy_grid'))\n # print(\"Action: {}\".format(ep_a[agent_handle]))\n #######################\n else:\n print(\"M-star gave wrong solution. Episode data discarded.\")\n ep_observations = []\n ep_a = []\n # continue_flag = True\n # #if continue_flag:\n # headers = [\"Channels\"]\n # rows = [[\"Obstacle Channel\"], [\"Other Agent Channel\"], [\"Own Goals Channel\"], \\\n # [\"Own Position Channel\"], [\"Other Goal Channel\"]]\n # #for agnt in range(args.n_agents):\n # #headers.append(\"Agent {}\".format(agnt))\n # rows[0].append(observations[ep*5][0])\n # rows[1].append(observations[ep*5][1])\n # rows[2].append(observations[ep*5][2])\n # rows[3].append(observations[ep*5][4])\n # rows[4].append(observations[ep*5][3])\n # print(tabulate(rows, tablefmt = 'fancy_grid'))\n # print(\"Action: {}\".format(actions[ep*5]))\n #continue\n return data\n #return #{\"observations\": np.array(observations),\n # \"actions\": np.array(actions)}\n\n\n\ndef generate_data(name = \"independent_navigation-v0\", custom_args = None):\n \n #Environment:\n parser = argparse.ArgumentParser(\"Generate Data\")\n parser.add_argument(\"--file_number\", default = 0, type=int)\n parser.add_argument(\"--map_shape\", default = 5, type=int)\n parser.add_argument(\"--n_agents\", default = 4, type=int)\n parser.add_argument(\"--env_name\", default = name, type= str)\n parser.add_argument(\"--use_default_rewards\", default=True, type=bool)\n parser.add_argument(\"--view_d\", default = 3, type=int)\n parser.add_argument(\"--obj_density\", default = 0.2, type=float)\n parser.add_argument(\"--use_custom_rewards\", default = False, action='store_true')\n parser.add_argument(\"--custom_env_ind\", default= 1, type=int)\n parser.add_argument(\"--n_episodes\", default= -1, type=int)\n parser.add_argument(\"--folder_name\", default= \"none\", type=str)\n parser.add_argument(\"--data_name\", default= \"none\", type=str)\n parser.add_argument(\"--base_path\", default= \"Notnone\", type=str)\n\n if custom_args is None:\n args = parser.parse_args()\n else:\n args = parser.parse_args(custom_args)\n\n args.map_shape = (args.map_shape, args.map_shape)\n\n if not args.n_episodes > 1:\n EPISODES = 5000\n else:\n EPISODES = args.n_episodes\n #WORKERS = 4\n if args.base_path == \"none\":\n import __main__\n base_path = os.path.dirname(__main__.__file__)\n base_path = os.path.join(base_path, \"BC_Data\")\n else:\n #base_path = args.base_path\n base_path = '/home/james/Desktop/Gridworld/BC_Data'\n\n data_folder = args.folder_name #'none'\n if args.data_name == \"none\":\n data_name = \"none_\" + str(args.file_number) + \".pt\"\n else:\n data_name = args.data_name\n \n data_folder_dir = os.path.join(base_path, data_folder) #base_path + '/' + data_folder + '/'\n if not os.path.exists(data_folder_dir):\n os.makedirs(data_folder_dir)\n\n all_data = generate(make_env(args), EPISODES, args.n_agents)\n torch.save(all_data, os.path.join(data_folder_dir, data_name))\n\n\n\n\n\n\n","sub_path":"Agents/BC/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":6457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"644180423","text":"\"\"\"\n研究PyQt5用的代码\n通过这个代码和tkinter进行对比。\n试着一边学习一边开发桌面应用\n\n作者:Lynn Lin\n最后一次编辑:2018/9/29\n\"\"\"\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom ChildMessageBox import MessageBox\n\n\nclass Example(QWidget):\n # close_signal = pyqtSignal()\n\n def __init__(self, parent=None):\n super(Example, self).__init__(parent)\n self.initUI()\n\n def initUI(self):\n # self.setToolTip('this is <b>QWidget</b>')\n\n btn = QPushButton('Strat', self)\n btn.resize(btn.sizeHint())\n\n qbtn = QPushButton('Quit', self)\n qbtn.resize(qbtn.sizeHint())\n\n # 按钮提示框\n btn.setToolTip('Start the time')\n\n # 按钮位置\n btn.move(50, 50)\n qbtn.move(50, 100)\n\n # 信号与槽\n btn.clicked.connect(self.onclick)\n qbtn.clicked.connect(self.close)\n\n self.resize(250, 150)\n self.center()\n self.setWindowTitle('main widget')\n\n def center(self):\n qr = self.frameGeometry() # 获取父类的几何形状\n cp = QDesktopWidget().availableGeometry().center() # QDesktopWidget获取桌面窗口信息\n qr.moveCenter(cp) # 将形状放在移动到桌面中央\n self.move(qr.topLeft()) # 获取形状的左上角位置,写入父类\n\n def closeEvent(self, event): # 关闭QWidget父类时自动调用的函数\n reply = QMessageBox.question(\n self, 'Message', \"Are you sure to quit?\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n def onclick(self):\n newWindow = MessageBox()\n newWindow.handle_click(self)\n\n# def showMessageBox():\n# view = new MyMessageBox(this)\n# view.main()\n\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n\n ex = Example()\n ex.show()\n\n # sys.exit(app.exec_())\n app.exec_()\n","sub_path":"Explore/PyQt5ParentChildFormTest.py","file_name":"PyQt5ParentChildFormTest.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"132323565","text":"from inspect import getgeneratorstate\nfrom functools import wraps\nfrom collections import namedtuple\n\n\ndef simple_coroutine():\n print('-> coroutine started')\n x = yield\n print('-> coroutine received:', x)\n\n\nmy_coro = simple_coroutine()\nprint(my_coro)\n# my_coro.send(1729)\nnext(my_coro)\nprint(getgeneratorstate(simple_coroutine()))\ntry:\n my_coro.send(42)\nexcept StopIteration:\n print('Warning: Generator stop iteration!!!')\n\n\ndef simple_coro2(a):\n print('-> Started: a =', a)\n b = yield a\n print('-> Received: b =', b)\n c = yield a + b\n print('-> Received: c =', c)\n\n\nmy_coro2 = simple_coro2(14)\nprint(getgeneratorstate(my_coro2))\nnext(my_coro2)\nprint(getgeneratorstate(my_coro2))\nmy_coro2.send(28)\ntry:\n my_coro2.send(99)\nexcept StopIteration:\n print('Warning: Generator stop iteration!!!')\nprint(getgeneratorstate(my_coro2))\n\n\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True:\n term = yield average\n total += term\n count += 1\n average = total/count\n\n\ncoro_avg = averager()\nnext(coro_avg)\nprint(coro_avg.send(10))\nprint(coro_avg.send(11))\nprint(coro_avg.send(12))\n\n\ndef coroutine(func):\n \"\"\"\n decorator: running forward to first \"yield\" formulation, pre-excitate the coroutine\n \"\"\"\n @wraps(func)\n def primer(*args, **kwargs):\n gen = func(*args, **kwargs)\n next(gen)\n return gen\n return primer\n\n\n@coroutine\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True:\n term = yield average\n total += term\n count += 1\n average = total/count\n\n\ncoro_avg = averager()\nprint(coro_avg.send(40))\nprint(coro_avg.send(50))\n# print(coro_avg.send('spam'))\nprint(coro_avg.send(60))\ncoro_avg.close()\n\n\nclass DemoException(Exception):\n \"\"\"\n The type of exception defined for this demo\n \"\"\"\n\n\ndef demo_exc_handling():\n print('-> coroutine started')\n while True:\n try:\n x = yield\n except DemoException:\n print('*** DemoException handled. Continuing...')\n else:\n print('-> coroutine received: {!r}'.format(x))\n raise RuntimeError('This line should never run.')\n\n\nexc_coro = demo_exc_handling()\nnext(exc_coro)\nexc_coro.send(11)\nexc_coro.send(22)\nexc_coro.close()\nprint(getgeneratorstate(exc_coro))\n\nexc_coro = demo_exc_handling()\nnext(exc_coro)\nexc_coro.send(11)\nexc_coro.send(22)\nexc_coro.throw(DemoException)\nprint(getgeneratorstate(exc_coro))\n\nexc_coro = demo_exc_handling()\nnext(exc_coro)\nexc_coro.send(11)\nexc_coro.send(22)\n# exc_coro.throw(ZeroDivisionError)\nprint(getgeneratorstate(exc_coro))\n\n\ndef demo_finally():\n print('-> coroutine started')\n try:\n while True:\n try:\n x = yield\n except DemoException:\n print('*** DemoException handled. Continuing...')\n else:\n print('-> coroutine received: {!r}'.format(x))\n finally:\n print('coroutine ending')\n\n\nexc_coro1 = demo_finally()\nnext(exc_coro1)\nexc_coro1.send(11)\nexc_coro1.close()\n\n\nResult = namedtuple('Result', 'count average')\n\n\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True:\n term = yield\n if term is None:\n break\n total += term\n count += 1\n average = total/count\n return Result(count, average)\n\n\ncoro_avg = averager()\nnext(coro_avg)\ncoro_avg.send(10)\ncoro_avg.send(30)\ncoro_avg.send(6.5)\ntry:\n coro_avg.send(None)\nexcept StopIteration as exc:\n result = exc.value\nprint(result)\n\n\ndef chain(*iterables):\n for it in iterables:\n yield from it\n\n\ns = 'ABC'\nt = tuple(range(3))\nprint(list(chain(s, t)))\n\n\ndef grouper(results, key):\n while True:\n results[key] = yield from averager()\n\n\ndef main(data):\n results = {}\n for key, values in data.items():\n group = grouper(results, key)\n next(group)\n for value in values:\n group.send(value)\n group.send(None)\n # group.close() # define by myself, I think it should be closed\n print(results)\n report(results)\n\n\ndef report(results):\n for key, result in sorted(results.items()):\n group, unit = key.split(';')\n print('{:2} {:5} averageing {:2f}{}'.format(result.count, group, result.average, unit))\n\n\ndata = {'girls;kg': [40.9, 38.5, 44.3, 42.2, 45.2, 41.7, 44.5, 38.0, 40.6, 44.5],\n 'girls;m': [1.6, 1.51, 1.4, 1.3, 1.41, 1.39, 1.33, 1.46, 1.45, 1.43],\n 'boys;kg': [39.0, 40.8, 43.2, 40.8, 43.1, 38.6, 41.4, 40.6, 36.3],\n 'boys;m': [1.38, 1.5, 1.32, 1.25, 1.37, 1.48, 1.25, 1.49, 1.46]}\n\nmain(data)\n\nEvent = namedtuple('Event', 'time proc action')\n\n\ndef taxi_process(ident, trips, start_time=0):\n\n time = yield Event(start_time, ident, 'leave garage')\n for i in range(trips):\n time = yield Event(time, ident, 'pick up passenger')\n time = yield Event(time, ident, 'drop off passenger')\n\n yield Event(time, ident, 'going home')\n\n\ntaxi = taxi_process(ident=13, trips=2, start_time=0)\nprint(next(taxi))\nprint(taxi.send(7))\nprint(taxi.send(30))\nprint(taxi.send(35))\nprint(taxi.send(83))\nprint(taxi.send(84))\n# print(taxi.send(94))\n\n","sub_path":"Coroutine.py","file_name":"Coroutine.py","file_ext":"py","file_size_in_byte":5185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"330898834","text":"import os\nimport subprocess\n\nfrom get_model.campos import obtiene_campos\nfrom get_model.foranea import obtiene_fk\nfrom get_model.primary_key import obtiene_pk\nfrom get_model.referencia import obtiene_referencia\n\n\ndef obtener_tablas():\n\n sql = \"\"\"\n select table_name \n from information_schema.tables \n where table_type = 'BASE TABLE' \n and table_schema = 'public';\n \"\"\"\n\n PgIP = os.environ['PgIP']\n dbuser = os.environ['dbuser']\n database = os.environ['database']\n\n campos = 'echo \"%s\" | psql -t -h %s -U %s -d %s' % (sql,PgIP,dbuser,database)\n return (((subprocess.check_output(campos, shell=True)).decode('utf8')).replace(' ','')).split()\n\n\ndef obtener_lista(tabla):\n\n js = {}\n\n for table, pk in obtiene_pk().items():\n\n if tabla == table:\n\n pk_ = {'p_key': {\n 'per': {u'periodo': [u'None']},\n 'coor': {}\n }}\n\n vector = []\n vector.append(pk)\n\n js.update(pk_)\n js.update({\"referencias\": obtiene_referencia(table)})\n js.update({\"foraneas\": obtiene_fk(table)})\n\n\n for f in obtiene_fk(table).keys():\n vector.append(f)\n\n campos = {}\n\n n = 0\n\n for c in obtiene_campos(table):\n\n if c in vector:\n pass\n else:\n campos.update({c: ['text',n]})\n n += 1\n\n if len(campos) == 0:\n campos = {'None':['None',0]}\n\n js.update({\"campos\": campos})\n\n js.update({\"orden\":[[pk,'desc']]})\n js.update({\"buscar\":['nombre']})\n\n return {\"tabla\": table, \"valores\": js}\n\n\n\nif __name__ == \"__main__\":\n\n for t in obtener_tablas():\n lista = obtener_lista(t)\n for v in lista:\n if v == 'tabla':\n print('Tabla : ',lista[v])\n else: \n print('Valores : ')\n detalle = lista[v]\n for v_ in detalle:\n print(v_,detalle[v_])\n\n","sub_path":"get_model/listar.py","file_name":"listar.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"565496134","text":"'''\nCreated on Aug 25, 2012\n\n@author: xavier\n'''\n\nfrom Robot import Robot\nfrom Track import Track\nimport math\nimport random\n\nclass Particle(Track):\n def __init__(self,max=1):\n Track.__init__(self, max=max)\n \n def position(self):\n return self.track[-1]\n \n def last_position(self):\n return self.track[-2]\n \n def set(self,x,y,d):\n self.add((x,y,d))\n\nclass ProbRobot(Robot):\n \n def __init__(self,position,orientation,settings,mapbuilder,\n trackparticles=False,\n command_producer=None):\n Robot.__init__(self,position,orientation,settings,mapbuilder,command_producer=None)\n \n self.cposition = [i for i in position]\n self.corientation = orientation\n \n self.nbparticles = 300\n self.init_particles()\n \n def init_particles(self):\n self.particles = [0 for i in range(self.nbparticles)]\n for i in range(self.nbparticles):\n self.particles[i] = Particle()\n self.particles[i].set(self.rposition[0],self.rposition[1],self.orientation)\n \n def calculate_position(self,t):\n nx, ny, nd = self._calculate_position(t, self.cposition[0], self.cposition[1], self.corientation)\n self.corientation = nd\n self.cposition = [nx,ny]\n \n def _calculate_position(self,t,x,y,d):\n nd = self.tacc*t**2/2.0 + \\\n self.tspeed*t + d\n nx = self.acc*math.cos(nd)*t**2/2.0 + self.speed*math.cos(nd)*t + x\n ny = self.acc*math.sin(nd)*t**2/2.0 + self.speed*math.sin(nd)*t + y\n return (nx,ny,nd)\n \n def update_map(self,readings):\n self.last_readings = self.new_readings\n self.new_readings = readings\n for reading,angle in zip(readings,self.settings.get(\"sensors\")):\n self.mapbuilder.reading([int(i) for i in self.cposition],self.corientation-angle,reading)\n pass\n \n def generate_particles(self,t):\n a = [self.settings.get(\"tvunc\"),\n self.settings.get(\"vunc\"),\n self.settings.get(\"vunc\"),\n self.settings.get(\"tvunc\")]\n \n for particle in self.particles:\n x, y, theta = particle.position()\n \n xp, yp, thetap = self._calculate_position(t, x, y, theta)\n dt = math.sqrt((xp-x)*(xp-x)+(yp-y)*(yp-y)) \n dr1 = math.atan2(yp-y, xp-x) - theta\n dr2= thetap-theta-dr1\n tdt = dt + random.gauss(0,a[0]*abs(dr1)+a[1]*abs(dt))\n tdr1 = dr1 + random.gauss(0,a[2]*abs(dt)+a[3]*abs(dr1+dr2))\n tdr2 = dr2 + random.gauss(0,a[0]*abs(dr2)+a[1]*abs(dt))\n px = x + tdt*math.cos(theta+tdr1)\n py = y + tdt*math.sin(theta+tdr1)\n ptheta = theta + tdr1 + tdr2\n #self.particles[i] = (random.gauss(self.cposition[0],self.radius*2),\n # random.gauss(self.cposition[1],self.radius*2))\n particle.set(px,py,ptheta)","sub_path":"mobilerobotix/src/kernel/robot/ProbRobot.py","file_name":"ProbRobot.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"123846402","text":"def getSpanColumnCount(span):\n \"\"\"Gets the number of columns inluded in a span\"\"\"\n columns = 1\n first_column = span[0][1]\n for i in range(len(span)):\n if span[i][1] > first_column:\n columns += 1\n first_column = span[i][1]\n return columns\n\n\ndef getSpanRowCount(span):\n \"\"\"Gets the number of rows included in a span\"\"\"\n rows = 1\n first_row = span[0][0]\n for i in range(len(span)):\n if span[i][0] > first_row:\n rows += 1\n first_row = span[i][0]\n return rows\n\n\ndef sortSpans(spans):\n \"\"\"Ensure the first cell of each span is the text cell\"\"\"\n for span in range(len(spans)):\n spans[span] = sorted(spans[span])\n return spans\n\n\ndef getSpan(spans, row, column):\n \"\"\"checks if a row,column is in spans\"\"\"\n for i in range(len(spans)):\n if [row, column] in spans[i]:\n return spans[i]\n return None\n\n\ndef lineBreak(count, symbol):\n \"\"\"makes a string that is count long of symbol\"\"\"\n x = \"\"\n for i in range(0, count):\n x = x + symbol\n return x\n\n\ndef centerWord(spaces, word):\n '''\n given a number of spaces, creates a string that has the word\n centered with half the space on each side.\n '''\n word = word.lstrip().rstrip()\n if len(word) > spaces:\n return word\n extra_space = spaces - len(word)\n space1 = int(extra_space/2)\n space2 = extra_space - space1\n intro = ''\n for i in range(space1):\n intro = intro + ' '\n outro = ''\n for i in range(space2):\n outro = outro + ' '\n string = intro + word + outro\n return string\n\n\ndef addCushions(table):\n \"\"\"adds space to start and end of each item in a list of lists\"\"\"\n for row in range(len(table)):\n for column in range(len(table[row])):\n lines = table[row][column].split(\"\\n\")\n for i in range(len(lines)):\n if not lines[i] == \"\":\n lines[i] = \" \" + lines[i].rstrip() + \" \"\n table[row][column] = \"\\n\".join(lines)\n return table\n\n\ndef removeNewlines(table):\n \"\"\"\n Replaces newlines with ' '\n \"\"\"\n for r in range(len(table)):\n for c in range(len(table[r])):\n table[r][c] = table[r][c].replace('\\n', ' ')\n return table\n","sub_path":"dashtable/dashutils.py","file_name":"dashutils.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"275404146","text":"\"\"\"\r\nCreator: Brett Gerard\r\nCreated: 20151208\r\nLast Modified: 20160707\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom pylab import *\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nimport time\r\nimport pandas as pd\r\n\r\nclass Settings:\r\n \"\"\"=============================================================================================\r\n A script to analyse the data fit between observed and modeled data.\r\n =============================================================================================\"\"\"\r\n \r\n def __init__(self,timestep, starteval, endeval, timeshift, offset):\r\n \"\"\"=========================================================================================\r\n Return analysis settings.\r\n =========================================================================================\"\"\"\r\n self.timestep = timestep\r\n self.starteval = starteval\r\n self.endeval = endeval\r\n self.timeshift = timeshift\r\n self.offset = offset\r\n \r\n def Data(self,modver,flowfile,snowfile):\r\n \"\"\"=========================================================================================\r\n Return modelled data.\r\n =========================================================================================\"\"\"\r\n self.modver = modver\r\n self.flowfile = flowfile\r\n self.snowfile = snowfile\r\n \r\n obsflow = ('CromwellDetailedTS_M11_{}.txt'.format(self.modver))\r\n flowsim_df = pd.read_csv('{}'.format(obsflow),sep='\\t',usecols=[0,1],skiprows=3,parse_dates=[0],index_col=[0],keep_date_col=True,names=['DateTime','SimCrom'])\r\n flowsim_df = flowsim_df.shift(self.timeshift,freq='H')\r\n flowsim_df = flowsim_df.resample(self.timestep)\r\n\r\n modsnow = ('CromwellDetailedTS_MIKESHE_{}.txt'.format(self.modver))\r\n snowsim_df = pd.read_csv('{}'.format(modsnow),sep='\\t',usecols=[0,1],skiprows=3,parse_dates=[0],index_col=[0],keep_date_col=True,names=['DateTime','SimSnow'])\r\n snowsim_df = snowsim_df.shift(self.timeshift,freq='H')\r\n snowsim_df = snowsim_df.resample(self.timestep)\r\n \r\n directory = 'D:/B.Gerard/Documents/Research/DataMarts/TemporalData/FlowData/NEST_FlowData/TimeSeries/ISCO_Data'\r\n flowobs_df = (pd.read_hdf('{}/{}'.format(directory,self.flowfile))).resample(self.timestep)\r\n\r\n directory = 'D:/B.Gerard/Documents/Research/Projects/MIKE_Projects/WebhannetRiverWatershed/Metadata/ClimateData/SnowPack'\r\n snowobs_df = (pd.read_csv('{}/{}'.format(directory,self.snowfile),skiprows=1,usecols=[0,3],parse_dates=[0],index_col=[0],keep_date_col=True,names=['DateTime','ObsSnow']))\r\n \r\n df = pd.DataFrame()\r\n df.insert(len(df.columns),'SimCrom',flowsim_df.SimCrom+self.offset)\r\n df.insert(len(df.columns),'ObsCrom',flowobs_df.discharge_cms)\r\n df.insert(len(df.columns),'ObsSnow',snowobs_df.ObsSnow*10)\r\n df.insert(len(df.columns),'SimSnow',snowsim_df.SimSnow)\r\n\r\n df = df[(df.index>self.starteval) & (df.index<self.endeval)]\r\n df = df[(df.SimCrom>0) & (df.ObsCrom>0)]\r\n \r\n return df\r\n","sub_path":"ConcatFiles.py","file_name":"ConcatFiles.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"439502325","text":"class Secretaria:\n def __init__(self):\n self.user = \"\"\n\n # query de autentificação\n def autentificar(self, login, senha):\n campos = \" * \"\n tabela = \" tbl_secretaria \"\n where = \" login = \" + login + \" and senha = \"+ senha\n self.user = self.bd.select(campos, tabela, where)\n print(\"User is\" + self.user)\n return self.user","sub_path":"atividades_python/projeto_python/model/secretaria.py","file_name":"secretaria.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"271258967","text":"#!/bin/python3\n\"\"\"\nhttps://www.hackerrank.com/challenges/frequency-queries/problem\n\nYou are given queries. Each query is of the form two integers described below:\n- : Insert x in your data structure.\n- : Delete one occurence of y from your data structure, if present.\n- : Check if any integer is present whose frequency is exactly . If yes, print 1 else 0.\n\nThe queries are given in the form of a 2-D array of size where contains the operation, and contains the data element. For example, you are given array . The results of each operation are:\n\nOperation Array Output\n(1,1) [1]\n(2,2) [1]\n(3,2) 0\n(1,1) [1,1]\n(1,1) [1,1,1]\n(2,1) [1,1]\n(3,2) 1\nReturn an array with the output: .\n\nFunction Description\n\nComplete the freqQuery function in the editor below. It must return an array of integers where each element is a if there is at least one element value with the queried number of occurrences in the current array, or 0 if there is not.\n\nfreqQuery has the following parameter(s):\n\nqueries: a 2-d array of integers\nInput Format\n\nThe first line contains of an integer , the number of queries.\nEach of the next lines contains two integers denoting the 2-d array .\n\nConstraints\n\nAll \nOutput Format\n\nReturn an integer array consisting of all the outputs of queries of type .\n\nSample Input 0\n\n8\n1 5\n1 6\n3 2\n1 10\n1 10\n1 6\n2 5\n3 2\nSample Output 0\n\n0\n1\nExplanation 0\n\nFor the first query of type , there is no integer whose frequency is (). So answer is .\nFor the second query of type , there are two integers in whose frequency is (integers = and ). So, the answer is .\n\nSample Input 1\n\n4\n3 4\n2 1003\n1 16\n3 1\nSample Output 1\n\n0\n1\nExplanation 1\n\nFor the first query of type , there is no integer of frequency . The answer is . For the second query of type , there is one integer, of frequency so the answer is .\n\nSample Input 2\n\n10\n1 3\n2 3\n3 2\n1 4\n1 5\n1 5\n1 4\n3 2\n2 4\n3 2\nSample Output 2\n\n0\n1\n1\nExplanation 2\n\nWhen the first output query is run, the array is empty. We insert two 's and two 's before the second output query, so there are two instances of elements occurring twice. We delete a and run the same query. Now only the instances of satisfy the query.\n\"\"\"\n\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef handle_operation(operation, value, frequencies):\n output = None\n if operation == 1:\n if value in frequencies:\n frequencies[value] += 1\n else:\n frequencies[value] = 1\n elif operation == 2:\n if value in frequencies:\n if frequencies[value] > 1:\n frequencies[value] -= 1\n else:\n del frequencies[value]\n else:\n values = set(frequencies.values())\n if value in values:\n return frequencies, 1\n else:\n return frequencies, 0\n return frequencies, None\n \ndef freqQuery(queries):\n frequencies = {}\n outputs = []\n for query in queries:\n operation, value = query\n frequencies, output = handle_operation(operation, value, frequencies)\n if output != None:\n outputs.append(output)\n return outputs\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input().strip())\n\n queries = []\n\n for _ in range(q):\n queries.append(list(map(int, input().rstrip().split())))\n\n ans = freqQuery(queries)\n\n fptr.write('\\n'.join(map(str, ans)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"hackerrank/interview-preparation-kit/dictionaries-and-hashmaps/frequency-queries.py","file_name":"frequency-queries.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"525175094","text":"#!/usr/bin/python3\nfrom cgi import FieldStorage\nimport copy\n\n\nclass Sudoku(object):\n \"\"\"\n Class to represent a Sudoku solver.\n This uses the backtracking algorithm\n \"\"\"\n\n def __init__(self, input_file=\"input.txt\", serverHTML=0):\n \"\"\"\n Initializer for the class\n :param input_file: String --> The path to the file containing the Sudoku board.\n :param serverHTML: Int --> 0 Does not print each step.\n 1 Prints out each step as a HTML document (This is for an API\n displaying each step of the algorithm).\n \"\"\"\n self.serveHTML = serverHTML\n self._grid = []\n self._generate_grid(input_file)\n self._solved_grid = copy.deepcopy(self._grid)\n self.solve()\n\n def solve(self):\n \"\"\"\n Recursive method to solve the board\n :return: Bool --> True if the board is solved.\n False if the board is not solved (Starts the back tracking)\n \"\"\"\n\n l = [0, 0]\n\n if not self._find_empty_location(l):\n return True\n\n row = l[0]\n col = l[1]\n\n for number in range(1, 10):\n if self._is_valid_move(row, col, number):\n self._solved_grid[row][col] = number\n\n if self.serveHTML == 1:\n print(\"%d%d%d\" % (row, col, number), end=\"\")\n if self.solve():\n return True\n\n self._solved_grid[row][col] = 0\n\n return False\n\n def write_to_file(self, ouput_file = \"output.txt\"):\n \"\"\"\n Method to write the solved grid to file\n :param ouput_file: String --> Path to the output file to write to\n :return: None\n \"\"\"\n fout = open(ouput_file, \"w\")\n for line in self._solved_grid:\n fout.write(str(line)[1:-1] + \"\\n\")\n\n fout.close()\n\n @property\n def og_board(self):\n \"\"\"\n Getter for the unsolved board\n :return: List --> representing the unsolved board\n \"\"\"\n return self._grid\n\n @og_board.setter\n def og_board(self, grid):\n \"\"\"\n Setter for the unsolved board.\n Also calls self.solve()\n :param grid: List of Lists --> Representing the board\n :return: None\n \"\"\"\n self._grid = grid\n self.solve()\n\n @property\n def solved_board(self):\n return self._solved_grid\n\n\n def _is_valid_move(self, row, col, num):\n \"\"\"\n Method to test if inserting a num at position[row][col] would be legal\n :param row: Int --> Representing the row of the position\n :param col: Int --> Representing the column of the position\n :param num: Int --> The number to be tested if it was valid\n :return: Bool --> True if the move is valid.\n False if the move is not valid.\n \"\"\"\n valid = True\n if self._used_in_row(row, num):\n valid = False\n\n if valid and self._used_in_column(col, num):\n valid = False\n\n if valid and self._used_in_box(row - row % 3, col - col % 3, num):\n valid = False\n\n return valid\n\n def _find_empty_location(self, l):\n \"\"\"\n Finds the next empty position after the current position.\n The location is stored in the local variable l.\n :param l: List --> Containing the position of the current location. [row, col]\n :return: Bool --> True if an empty location was found.\n False if no empty location is found.\n \"\"\"\n for r in range(9):\n for c in range(9):\n if self._solved_grid[r][c] == 0:\n l[0] = r\n l[1] = c\n return True\n return False\n\n def _generate_grid(self, input_file):\n \"\"\"\n Method to generate the 2D matrix of the unsolved board from the file.\n The 2D matrix is stored in self._grid and self._solved_grid attributes.\n :param input_file: String --> Representing the path to the to the input file\n :return: None.\n \"\"\"\n if input_file.endswith(\".txt\"):\n self._generate_grid_txt_file(input_file)\n\n def _generate_grid_txt_file(self, input_file):\n \"\"\"\n Method to generate the 2D matrix of the unsolved board from the file.\n The 2D matrix is stored in self._grid and self._solved_grid attributes.\n :param input_file: String --> Representing the path to the to the input file\n :return: None.\n \"\"\"\n file = open(input_file, \"r\")\n\n for line in file:\n l = list(map(int, line.strip().split(\",\")))\n self._grid.append(l)\n\n def _used_in_row(self, row, num):\n \"\"\"\n Method to check if a number is used in the row\n :param row: Int --> Representing the row to be checked\n :param num: Int --> Representing the number to be checked\n :return: Bool --> True if the number is used in the row.\n False if the number is not used in the row.\n \"\"\"\n used = False\n for i in range(9):\n if self._solved_grid[row][i] == num:\n used = True\n break\n return used\n\n def _used_in_column(self, col, num):\n \"\"\"\n Method to check if a number is used in the column\n :param col: Int --> Representing the column to be checked\n :param num: Int --> Representing the number to be checked\n :return: Bool --> True if the number is used in the column.\n False if the number is not used in the column.\n \"\"\"\n used = False\n for i in range(9):\n if self._solved_grid[i][col] == num:\n used = True\n break\n return used\n\n def _used_in_box(self, row, col, num):\n \"\"\"\n Method to check if a number is used in the row\n :param row: Int --> Representing the row to be checked\n :param col: Int --> Representing the column to be checked\n :param num: Int --> Representing the number to be checked\n :return: Bool --> True if the number is used in the box.\n False if the number is not used in the box.\n \"\"\"\n used = False\n for i in range(3):\n for j in range(3):\n if self._solved_grid[i+row][j+col] == num:\n used = True\n break\n\n return used\n\n def _print_solved_grid(self):\n \"\"\"\n Method to print the solved grid. In the following format\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n :return: None\n \"\"\"\n for row in self._solved_grid:\n print(row)\n\n print()\n\n def _print_og_grid(self):\n \"\"\"\n Method to print the original unsolved grid. In the following format\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n [1,2,3,4,5,6,7,8,9]\n :return: None\n \"\"\"\n for row in self._grid:\n print(row)\n\n print()\n\n def __str__(self):\n \"\"\"\n String method for the class. It will have the following format.\n _____________________________\n | 4 8 3 | 9 2 1 | 6 5 7 |\n | 9 6 7 | 3 4 5 | 8 2 1 |\n | 2 5 1 | 8 7 6 | 4 9 3 |\n _____________________________\n | 5 4 8 | 1 3 2 | 9 7 6 |\n | 7 2 9 | 5 6 4 | 1 3 8 |\n | 1 3 6 | 7 9 8 | 2 4 5 |\n _____________________________\n | 3 7 2 | 6 8 9 | 5 1 4 |\n | 8 1 4 | 2 5 3 | 7 6 9 |\n | 6 9 5 | 4 1 7 | 3 8 2 |\n _____________________________\n :return: String --> Representing the solved board if the board has been solved.\n Else the unsolved board.\n \"\"\"\n m = \"\"\n m += \"\\n _____________________________\\n|\"\n for i in range(9):\n for k in range(9):\n m += \" \" + str(self._solved_grid[i][k]) + \" \"\n if (k+1) % 3 == 0:\n m+=\"|\"\n\n if (i+1) % 3 ==0:\n m += \"\\n _____________________________\\n|\"\n else:\n m+=\"\\n|\"\n return m[0:-1]\n\n def __hash__(self):\n \"\"\"\n Hash method for the class.\n :return: Hash of the unsolved board\n \"\"\"\n\n return hash(str(self._grid))\n\n def __eq__(self, other):\n \"\"\"\n Method to test if 2 unsolved boards are the same.\n :param other: Sudoku class one to test\n :return: Bool --> True if the boards are the same\n False if the boards are not the same.\n \"\"\"\n\nif __name__ == \"__main__\":\n form_data = FieldStorage()\n mode = int(form_data.getfirst(\"mode\", \"0\").strip())\n if mode == 0:\n s = Sudoku()\n s.solve()\n print(s)\n\n elif mode == 1:\n print('Content-Type: text/html')\n print()\n s = Sudoku(serverHTML=1)\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":9498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"28961162","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 3 11:39:10 2019\n\n@author: hacklavya\n\"\"\"\n\nimport numpy as np\nfrom planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset\n\nnp.random.seed(1)\n\nX, Y = load_planar_dataset()\n\n# layers [n_x, 4, n_y]\nn_x = X.shape[0]\nn_h = 4\nn_y = Y.shape[0]\nm = X.shape[1]\n\nnp.random.seed(2)\nW1 = np.random.randn(n_h, n_x) * 0.01\nb1 = np.zeros((n_h, 1))\nW2 = np.random.randn(n_y, n_h) * 0.01\nb2 = np.zeros((n_y,1))\n\nlearning_rate = 1.2\nnum_iterations = 10000\n\n# loop things below\nfor i in range(0, num_iterations):\n Z1 = np.dot(W1, X) + b1\n A1 = np.tanh(Z1)\n Z2 = np.dot(W2, A1) + b2\n A2 = sigmoid(Z2)\n\n logprobs = np.multiply(Y, np.log(A2) ) + np.multiply(1-Y, np.log(1-A2))\n cost = -(1.0/m) * np.sum(logprobs)\n cost = np.squeeze(cost)\n \n if i % 1000 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n\n dZ2 = A2 - Y\n dW2 = (1.0/m) * np.dot(dZ2, A1.T)\n db2 = (1.0/m) * np.sum(dZ2, axis = 1, keepdims = True)\n dZ1 = np.multiply( np.dot(W2.T, dZ2), 1.0 - np.power(A1, 2) )\n dW1 = (1.0/m) * np.dot(dZ1, X.T)\n db1 = (1.0/m) * np.sum(dZ1, axis = 1, keepdims = True)\n\n W1 = W1 - learning_rate * dW1\n b1 = b1 - learning_rate * db1\n W2 = W2 - learning_rate * dW2\n b2 = b2 - learning_rate * db2\n\n","sub_path":"course_01/02 Planar data classification with one hidden layer/my_code.py","file_name":"my_code.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"519701482","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django_countries.fields import CountryField\nfrom registrasion import models as rego\n\n\n@python_2_unicode_compatible\nclass PastEvent(models.Model):\n ''' This is populated in 0001_initial.py '''\n\n def __str__(self):\n return self.name\n\n year = models.IntegerField(unique=True,)\n name = models.CharField(max_length=255, unique=True,)\n\n\nclass AttendeeProfile(rego.AttendeeProfileBase):\n '''\n\n\nHave you attended linux.conf.au before?\n\n1999 (CALU, Melbourne)\n2001 (Sydney)\n2002 (Brisbane)\n2003 (Perth)\n2004 (Adelaide)\n2005 (Canberra)\n2006 (Dunedin)\n2007 (Sydney)\n2008 (Melbourne)\n2009 (Hobart)\n2010 (Wellington)\n2011 (Brisbane)\n2012 (Ballarat)\n2013 (Canberra)\n2014 (Perth)\n2015 (Auckland)\n\n\n\nDo you want?\n\nMembership of Linux Australia. (read more)\nThe low traffic linux.conf.au 2016 announcement mailing list\nThe linux.conf.au 2016 attendees mailing listName\n '''\n\n @classmethod\n def name_field(cls):\n ''' This is used to pre-fill the attendee's name from the\n speaker profile. If it's None, that functionality is disabled. '''\n return \"name\"\n\n def invoice_recipient(self):\n\n lines = [\n self.name_per_invoice,\n ]\n\n if self.company:\n lines.append(\"C/- \" + self.company)\n\n if self.address_line_1:\n lines.append(self.address_line_1)\n\n if self.address_line_2:\n lines.append(self.address_line_2)\n\n if self.address_suburb or self.address_postcode:\n lines.append(\"%s %s\" % (\n self.address_suburb or \"\",\n self.address_postcode or \"\",\n ))\n\n if self.state:\n lines.append(self.state)\n\n if self.country:\n lines.append(self.country.name)\n\n return \"\\n\".join(unicode(line) for line in lines)\n\n def clean(self):\n errors = []\n if self.country == \"AU\" and not self.state:\n errors.append(\n (\"state\", \"Australians must list their state\"),\n )\n\n if self.address_line_2 and not self.address_line_1:\n errors.append((\n \"address_line_1\",\n \"Please fill in line 1 before filling line 2\",\n ))\n\n if errors:\n raise ValidationError(dict(errors))\n\n def save(self):\n if not self.name_per_invoice:\n self.name_per_invoice = self.name\n super(AttendeeProfile, self).save()\n\n # Things that appear on badge\n name = models.CharField(\n verbose_name=\"Your name (for your conference nametag)\",\n max_length=64,\n help_text=\"Your name, as you'd like it to appear on your badge. \",\n )\n company = models.CharField(\n max_length=64,\n help_text=\"The name of your company, as you'd like it on your badge\",\n blank=True,\n )\n\n free_text_1 = models.CharField(\n max_length=64,\n verbose_name=\"Free text line 1\",\n help_text=\"A line of free text that will appear on your badge. Use \"\n \"this for your Twitter handle, IRC nick, your preferred \"\n \"pronouns or anything else you'd like people to see on \"\n \"your badge.\",\n blank=True,\n )\n free_text_2 = models.CharField(\n max_length=64,\n verbose_name=\"Free text line 2\",\n blank=True,\n )\n\n # Other important Information\n name_per_invoice = models.CharField(\n verbose_name=\"Your legal name (for invoicing purposes)\",\n max_length=256,\n help_text=\"If your legal name is different to the name on your badge, \"\n \"fill this in, and we'll put it on your invoice. Otherwise, \"\n \"leave it blank.\",\n blank=True,\n )\n\n address_line_1 = models.CharField(\n verbose_name=\"Address line 1\",\n help_text=\"This address, if provided, will appear on your invoices.\",\n max_length=1024,\n blank=True,\n )\n address_line_2 = models.CharField(\n verbose_name=\"Address line 2\",\n max_length=1024,\n blank=True,\n )\n address_suburb = models.CharField(\n verbose_name=\"City/Town/Suburb\",\n max_length=1024,\n blank=True,\n )\n address_postcode = models.CharField(\n verbose_name=\"Postal/Zip code\",\n max_length=1024,\n blank=True,\n )\n country = CountryField(\n default=\"AU\",\n )\n state = models.CharField(\n max_length=256,\n verbose_name=\"State/Territory/Province\",\n blank=True,\n )\n\n of_legal_age = models.BooleanField(\n default=False,\n verbose_name=\"Are you over 18?\",\n blank=True,\n help_text=\"Being under 18 will not stop you from attending the \"\n \"conference. We need to know whether you are over 18 to \"\n \"allow us to cater for you at venues that serve alcohol.\",\n )\n dietary_restrictions = models.CharField(\n verbose_name=\"Food allergies, intolerances, or dietary restrictions\",\n max_length=256,\n blank=True,\n )\n accessibility_requirements = models.CharField(\n verbose_name=\"Accessibility-related requirements\",\n max_length=256,\n blank=True,\n )\n gender = models.CharField(\n help_text=\"Gender data will only be used for demographic purposes.\",\n max_length=64,\n blank=True,\n )\n\n linux_australia = models.BooleanField(\n verbose_name=\"Linux Australia membership\",\n help_text=\"Select this field to register for free \"\n \"<a href='http://www.linux.org.au/'>Linux Australia</a> \"\n \"membership.\",\n blank=True,\n )\n\n lca_announce = models.BooleanField(\n verbose_name=\"Subscribe to lca-announce list\",\n help_text=\"Select to be subscribed to the low-traffic lca-announce \"\n \"mailing list\",\n blank=True,\n )\n\n lca_chat = models.BooleanField(\n verbose_name=\"Subscribe to the lca2017-chat list\",\n help_text=\"lca2017-chat is a high-traffic mailing list used by \"\n \"attendees during the week of the conference for general \"\n \"discussion.\",\n blank=True,\n )\n\n past_lca = models.ManyToManyField(\n PastEvent,\n verbose_name=\"Which past linux.conf.au events have you attended?\",\n blank=True,\n )\n","sub_path":"pinaxcon/registrasion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"192038378","text":"#!/usr/bin/env python3.6\n\nimport os\nimport sys\nimport urllib.request\nimport json\nimport datetime\nimport sqlite3\nfrom contextlib import closing\nimport time\n\n#debugstr='debug_'\n#debugmode=True\ndebugmode=False\ndebugstr=''\n\ndef debugprint(str):\n if debugmode:\n print(str)\n\ndef MvData(result, p, t):\n \n #now=datetime.datetime.now()\n #dt=now.strftime('%Y%m%d')\n now=result['now']\n dt=now.strftime('%Y%m%d')\n #print(dt[0:4])\n #print(dt[4:6])\n #print(dt[6:8])\n\n tm={}\n tm['min5']='_min5'\n tm['hour1']='_hour1'\n tm['day1']='_day1'\n\n pair={}\n pair['USDJPY']=debugstr + 'usdjpy_tick_' + dt + tm[t] + '.db'\n pair['EURJPY']=debugstr + 'eurjpy_tick_' + dt + tm[t] + '.db'\n pair['GBPJPY']=debugstr + 'gbpjpy_tick_' + dt + tm[t] + '.db'\n pair['AUDJPY']=debugstr + 'audjpy_tick_' + dt + tm[t] + '.db'\n pair['NZDJPY']=debugstr + 'nzdjpy_tick_' + dt + tm[t] + '.db'\n pair['CADJPY']=debugstr + 'cadjpy_tick_' + dt + tm[t] + '.db'\n pair['CHFJPY']=debugstr + 'chfjpy_tick_' + dt + tm[t] + '.db'\n pair['ZARJPY']=debugstr + 'zarjpy_tick_' + dt + tm[t] + '.db'\n\n pair2={}\n pair2['USDJPY']=debugstr + 'usdjpy_tick_' + dt + '.db'\n pair2['EURJPY']=debugstr + 'eurjpy_tick_' + dt + '.db'\n pair2['GBPJPY']=debugstr + 'gbpjpy_tick_' + dt + '.db'\n pair2['AUDJPY']=debugstr + 'audjpy_tick_' + dt + '.db'\n pair2['NZDJPY']=debugstr + 'nzdjpy_tick_' + dt + '.db'\n pair2['CADJPY']=debugstr + 'cadjpy_tick_' + dt + '.db'\n pair2['CHFJPY']=debugstr + 'chfjpy_tick_' + dt + '.db'\n pair2['ZARJPY']=debugstr + 'zarjpy_tick_' + dt + '.db'\n\n tbl={}\n tbl['USDJPY']='usdjpy_tick'\n tbl['EURJPY']='eurjpy_tick'\n tbl['GBPJPY']='gbpjpy_tick'\n tbl['AUDJPY']='audjpy_tick'\n tbl['NZDJPY']='nzdjpy_tick'\n tbl['CADJPY']='cadjpy_tick'\n tbl['CHFJPY']='chfjpy_tick'\n tbl['ZARJPY']='zarjpy_tick'\n\n mlist={}\n mlist['min5']=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]\n mlist['hour1']=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]\n mlist['day1']=[]\n\n tgtdir='./db/kawase/' + dt\n if not os.path.exists(tgtdir):\n os.makedirs(tgtdir)\n\n dbname=tgtdir + '/' + pair[p]\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n sql='create table if not exists ' + tbl[p] + '(dt text primary key, open real, end real, high real, low real)'\n c.execute(sql)\n\n dmax=now\n dmin=datetime.datetime(now.year, now.month, now.day, now.hour, 0)\n if t=='day1':\n dmin=datetime.datetime(now.year, now.month, now.day, 0, 0)\n dmax=dmin+datetime.timedelta(days=1)\n for m in mlist[t]:\n if t=='min5':\n d1=datetime.datetime(now.year, now.month, now.day, now.hour, m)\n debugprint(\"d1:\" + d1.strftime('%Y%m%d%H%M%S'))\n elif t=='hour1':\n d1=datetime.datetime(now.year, now.month, now.day, m, 0)\n d2=now.timestamp()-d1.timestamp()\n if d2 < 0:\n dmax=d1\n break\n dmin=d1\n\n if dmax==now:\n if t=='min5':\n dmax=dmin+datetime.timedelta(minutes=5)\n debugprint(\"dmax:\" + dmin.strftime('%Y%m%d%H%M%S'))\n debugprint(\"dmax:\" + dmax.strftime('%Y%m%d%H%M%S'))\n elif t=='hour1':\n dmax=dmin+datetime.timedelta(hours=1)\n\n debugprint('t:' + t)\n debugprint('dmax:' + dmax.strftime('%Y%m%d%H%M%S'))\n dbnameorg=tgtdir + '/' + pair2[p]\n with closing(sqlite3.connect(dbnameorg)) as conn2:\n c2 = conn2.cursor()\n\n sql2=\"select min(bid), max(ask) from \" + tbl[p] + \" where dt < \" + dmax.strftime('%Y%m%d%H%M%S')\\\n +\" and dt >= \" + dmin.strftime('%Y%m%d%H%M%S')\n for row in c2.execute(sql2):\n low=row[0]\n high=row[1]\n\n debugprint(sql2)\n debugprint(\"low:\" + str(low) + \" high:\" + str(high))\n\n sql2=\"select min(dt), max(dt) from \" + tbl[p] + \" where dt < \" + dmax.strftime('%Y%m%d%H%M%S')\\\n +\" and dt >= \" + dmin.strftime('%Y%m%d%H%M%S')\n for row in c2.execute(sql2):\n dstartstr=row[0]\n dendstr=row[1]\n\n debugprint(sql2)\n debugprint(\"dstartstr:\" + str(dstartstr) + \" dendstr:\" + str(dendstr)) \n\n openp=0\n sql2=\"select bid from \" + tbl[p] + \" where dt = '\" + dstartstr + \"'\"\n for row in c2.execute(sql2):\n openp=row[0]\n\n endp=0\n sql2=\"select bid from \" + tbl[p] + \" where dt = '\" + dendstr + \"'\"\n for row in c2.execute(sql2):\n endp=row[0]\n\n debugprint(\"d:\" + dmin.strftime('%Y%m%d %H%M%S') + \" \" + \"low:\" + str(low) + \" high:\" + str(high)\\\n + \" s:\" + str(openp) + \" e:\" + str(endp))\n \n sql=\"replace into \" + tbl[p] + \"(dt, open, end, high, low) values (\"\\\n +\"'\" + dmin.strftime('%Y%m%d%H%M%S') + \"',\"\\\n + str(openp) + \",\"\\\n + str(endp) + \",\"\\\n + str(high) + \",\"\\\n + str(low) + \"\"\\\n + \")\"\n\n #print(sql)\n c.execute(sql)\n conn.commit()\n\n sql2=\"update \" + tbl[p]\n if t=='min5':\n sql2=sql2 + \" set min5=1\"\n elif t=='hour1':\n sql2=sql2 + \" set hour1=1\"\n elif t=='day1':\n sql2=sql2 + \" set day1=1\"\n sql2=sql2+\" where dt < \" + dmax.strftime('%Y%m%d%H%M%S')\\\n +\" and dt >= \" + dmin.strftime('%Y%m%d%H%M%S')\n #print(sql2)\n c2.execute(sql2)\n conn2.commit()\n\n conn.commit()\n\n\ndef InsertData(d):\n ret={}\n ret['now'] = datetime.datetime.now()\n dt=ret['now'].strftime('%Y%m%d')\n now=ret['now'].strftime('%Y%m%d%H%M%S')\n\n pair={}\n pair['USDJPY']=debugstr + 'usdjpy_tick_' + dt + '.db'\n pair['EURJPY']=debugstr + 'eurjpy_tick_' + dt + '.db'\n pair['GBPJPY']=debugstr + 'gbpjpy_tick_' + dt + '.db'\n pair['AUDJPY']=debugstr + 'audjpy_tick_' + dt + '.db'\n pair['NZDJPY']=debugstr + 'nzdjpy_tick_' + dt + '.db'\n pair['CADJPY']=debugstr + 'cadjpy_tick_' + dt + '.db'\n pair['CHFJPY']=debugstr + 'chfjpy_tick_' + dt + '.db'\n pair['ZARJPY']=debugstr + 'zarjpy_tick_' + dt + '.db'\n\n tbl={}\n tbl['USDJPY']='usdjpy_tick'\n tbl['EURJPY']='eurjpy_tick'\n tbl['GBPJPY']='gbpjpy_tick'\n tbl['AUDJPY']='audjpy_tick'\n tbl['NZDJPY']='nzdjpy_tick'\n tbl['CADJPY']='cadjpy_tick'\n tbl['CHFJPY']='chfjpy_tick'\n tbl['ZARJPY']='zarjpy_tick'\n\n tgtdir='./db/kawase/' + dt\n if not os.path.exists(tgtdir):\n os.makedirs(tgtdir)\n\n if d['currencyPairCode'] in pair:\n dbname=tgtdir + '/' + pair[d['currencyPairCode']]\n debugprint(dbname)\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n sql='create table if not exists ' + tbl[d['currencyPairCode']] + '(dt text primary key, bid real, ask real, min5 int, hour1 int, day1 int)'\n debugprint(sql)\n c.execute(sql)\n\n sql=\"insert into \" + tbl[d['currencyPairCode']] + \"(dt,bid,ask,min5,hour1,day1) values (\"\\\n + \"'\" + now + \"'\"\\\n + \",\" + str(d['bid'])\\\n + \",\" + str(d['ask'])\\\n + \",0,0,0)\" \n c.execute(sql)\n conn.commit()\n\n return ret\n\nwhile True:\n \n url= 'https://www.gaitameonline.com/rateaj/getrate'\n headers = { \"User-Agent\" : \"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)\" }\n req = urllib.request.Request(url, None, headers)\n res = urllib.request.urlopen(req)\n if res.getcode() == 200:\n dataStr = res.read()\n dataObj = json.loads(dataStr.decode('utf-8'))\n #print(dataObj)\n else:\n exit()\n \n \n pairstr={}\n pairstr['USDJPY']='USD_JPY'\n pairstr['EURJPY']='EURJPY'\n pairstr['GBPJPY']='GBPJPY'\n pairstr['AUDJPY']='AUDJPY'\n pairstr['NZDJPY']='NZDJPY'\n pairstr['CADJPY']='CADJPY'\n pairstr['CHFJPY']='CHFJPY'\n pairstr['ZARJPY']='ZARJPY'\n \n tickstr={}\n tickstr['min5']='min5'\n tickstr['hour1']='hour1'\n tickstr['day1']='day1'\n\n '''\n test={}\n test['min5']=[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] \n now=datetime.datetime(2018, 7, 8, 18, 56, 10)\n print(now.strftime('%Y%m%d%H%M%S'))\n dmax=now\n for m in test['min5']:\n d1=datetime.datetime(now.year, now.month, now.day, now.hour, m)\n d2=now.timestamp()-d1.timestamp()\n if d2 < 0:\n dmax=d1\n break\n dmin=d1\n\n if dmax==now:\n \n print(dmin.strftime('%Y%m%d%H%M%S'))\n print(dmax.strftime('%Y%m%d%H%M%S'))\n exit()\n '''\n\n for d in dataObj['quotes']:\n result=InsertData(d)\n\n for p in pairstr:\n for t in tickstr:\n #print('test')\n MvData(result, p, t)\n\n time.sleep(10)\n\n\n","sub_path":"getkawase2.py","file_name":"getkawase2.py","file_ext":"py","file_size_in_byte":9026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"302021324","text":"from contextlib import contextmanager\n\nfrom sqlalchemy import Column, Integer, String, func, MetaData, Table, select, and_\nfrom sqlalchemy.engine import Engine, Connection\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom aitools.storage.base import NodeStorage\n\nmetadata = MetaData()\nBase = declarative_base()\n\nabstruse_to_object = Table(\n 'abstruse_to_object', metadata,\n Column('abstruse_id', Integer, primary_key=True),\n Column('object_id', Integer, primary_key=True)\n)\n\n\nabstruse_to_subtrie = Table(\n 'abstruse_to_subtrie', metadata,\n Column('abstruse_id', Integer, primary_key=True),\n Column('subtrie_id', Integer)\n)\n\n\ntrie_to_abstruse = Table(\n 'trie_to_abstruse', metadata,\n Column('trie_id', Integer, primary_key=True),\n Column('abstruse_id', Integer, unique=True, sqlite_on_conflict_unique='IGNORE')\n)\n\n\ntrie_to_key_and_subtrie = Table(\n 'trie_to_key_and_subtrie', metadata,\n Column('trie_id', Integer, primary_key=True),\n Column('key_element', String, primary_key=True),\n Column('subtrie_id', Integer)\n)\n\n\nobject_to_data = Table(\n 'object_to_data', metadata,\n Column('object_id', Integer, primary_key=True),\n Column('data', Integer, unique=True)\n)\n\n\n# TODO: handle the session creation in a sensible way :P like.. not here\nclass SQLAlchemyNodeStorage(NodeStorage):\n def __init__(self, connection: Connection):\n self.connection = connection\n\n metadata.create_all(self.connection.engine)\n\n self.last_id = self.__fetch_last_id()\n\n @contextmanager\n def transaction(self):\n # TODO: feeling lazy, might implement later :P\n raise NotImplementedError()\n\n def commit(self):\n # TODO: feeling lazy, might implement later :P\n raise NotImplementedError()\n\n def rollback(self):\n # TODO: feeling lazy, might implement later :P\n raise NotImplementedError()\n\n def close(self):\n self.connection.close()\n\n def __fetch_last_id(self):\n # TODO I'm sure there's a better way of doing this but SQLAlchemy eludes my feeble brain\n max_results = [\n self.connection.execute(select([\n func.max(abstruse_to_subtrie.c.abstruse_id),\n ])).scalar(),\n self.connection.execute(select([\n func.max(abstruse_to_subtrie.c.subtrie_id),\n ])).scalar(),\n self.connection.execute(select([\n func.max(object_to_data.c.object_id),\n ])).scalar(),\n ]\n return max(\n x if x is not None else 0\n for x in max_results\n )\n\n def next_id(self):\n self.last_id += 1\n return self.last_id\n\n def store_abstruse_node_for_trie_index_id(self, trie_id, abstruse_id):\n try:\n self.connection.execute(trie_to_abstruse.insert().values(trie_id=trie_id, abstruse_id=abstruse_id))\n except IntegrityError:\n pass\n\n def get_all_object_ids_in_trie_node(self, trie_id):\n results = self.connection.execute(trie_to_abstruse.select(trie_to_abstruse.c.trie_id == trie_id)).fetchall()\n for obj in results:\n yield obj.abstruse_id\n\n def get_object(self, object_id):\n obj = self.connection.execute(object_to_data.select(object_to_data.c.object_id == object_id)).fetchone()\n return obj.data\n\n def get_all_object_ids_in_abstruse_node(self, abstruse_id):\n results = self.connection.execute(\n abstruse_to_object.select(abstruse_to_object.c.abstruse_id == abstruse_id)\n ).fetchall()\n\n for obj in results:\n yield obj.object_id\n\n def get_subindex_id_for_abstruse_node(self, abstruse_id):\n obj = self.connection.execute(\n abstruse_to_subtrie.select(abstruse_to_subtrie.c.abstruse_id == abstruse_id)\n ).fetchone()\n if obj is None:\n subtrie_id = self.next_id()\n self.connection.execute(abstruse_to_subtrie.insert().values(abstruse_id=abstruse_id, subtrie_id=subtrie_id))\n else:\n subtrie_id = obj.subtrie_id\n return subtrie_id\n\n def store_object_for_abstruse_node(self, abstruse_id, object_id):\n try:\n self.connection.execute(abstruse_to_object.insert().values(abstruse_id=abstruse_id, object_id=object_id))\n except IntegrityError:\n pass\n\n def get_all_subindices_in_trie_node(self, trie_id):\n results = self.connection.execute(\n trie_to_key_and_subtrie.select(trie_to_key_and_subtrie.c.trie_id == trie_id)\n ).fetchall()\n for res in results:\n yield res.subtrie_id\n\n def get_all_key_value_pairs_in_trie_node(self, trie_id):\n results = self.connection.execute(\n trie_to_key_and_subtrie.select(trie_to_key_and_subtrie.c.trie_id == trie_id)\n ).fetchall()\n\n for res in results:\n key = res.key_element if res.key_element[0] in \"#*\" else int(res.key_element)\n yield key, res.subtrie_id\n\n def get_subindex_from_trie_by_key(self, trie_id, key_element):\n res = self.connection.execute(trie_to_key_and_subtrie.select(\n and_(trie_to_key_and_subtrie.c.trie_id == trie_id,\n trie_to_key_and_subtrie.c.key_element == key_element)\n )).fetchone()\n return res.subtrie_id if res is not None else None\n\n def store_trie_subindex_for_trie_node_and_key(self, trie_id, key_element, subindex_id):\n try:\n self.connection.execute(\n trie_to_key_and_subtrie.insert().values(\n trie_id=trie_id, key_element=key_element, subtrie_id=subindex_id\n )\n )\n except IntegrityError:\n pass\n\n def store_obj(self, obj):\n try:\n object_id = self.next_id()\n self.connection.execute(object_to_data.insert().values(object_id=object_id, data=obj))\n return object_id\n except IntegrityError:\n res = self.connection.execute(object_to_data.select(object_to_data.c.data==obj)).fetchone()\n return res.object_id\n","sub_path":"aitools/storage/implementations/sqlalchemy.py","file_name":"sqlalchemy.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"236716563","text":"import sys\nimport socket\nimport traceback\nimport uuid\nimport time\n\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nPORT = 3439\naddress = ('<broadcast>', PORT)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n\nmac = uuid.getnode()\nhostname = socket.gethostname()\nhostname_len = len(hostname)\n\npool = ThreadPoolExecutor(max_workers=1)\n\nwhile True:\n try:\n timestamp = int(time.time())\n s.sendto(','.join([str(mac), str(hostname_len), hostname, str(timestamp)]).encode('utf8'), address)\n pool.submit(print, 'Send broadcast...')\n time.sleep(5)\n except KeyboardInterrupt:\n traceback.print_exc()\n s.close()\n sys.exit(0)\n\n","sub_path":"MatveevAlexander/Lab1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"182403909","text":"\"\"\"\nCreated on 16.01.2017\n\n@author: kristina ibanez-garikano\n\"\"\"\n\nimport sys\nimport os\nimport ConfigParser\nimport optparse\nimport logging\nfrom subprocess import Popen, PIPE\nimport pandas as pd\n\n\nclass OptionParser(optparse.OptionParser):\n def check_required(self, opt):\n\n option = self.get_option(opt)\n\n atrib = getattr(self.values, option.dest)\n\n if atrib is None:\n return False\n else:\n return True\n\n\ndef read_tsv_file(input_tsv):\n \"\"\"\n It reads a TSV file containing genomes retrieved from Catalog\n :param input_tsv: tsv file with 2 columns: <lp_id>\\t<path_to_the_structure>\n :return: hash table containing the 2 columns - associates the LP id with the BAM file\n \"\"\"\n\n data = pd.read_csv(input_tsv, sep=\"\\t\", header=None)\n\n l_lp = data.iloc[:, 0].tolist()\n l_paths = data.iloc[:, 1].tolist()\n l_gender = data.iloc[:, 2].tolist()\n\n hash_path = dict(zip(l_lp, l_paths))\n hash_gender = dict(zip(l_lp, l_gender))\n\n return hash_path, hash_gender\n\n\ndef read_cfg_file(cfg_filename):\n \"\"\"\n It reads the config file, containing required input data to run EH\n :param cfg_filename: config file with the GENERAL (the tsv), OUTPUT paths, REFERENCE\n files and their paths, as well as the SOFTWARE (EH binary file)\n :return: hash table with all this information\n \"\"\"\n\n file_input = open(cfg_filename, 'r')\n\n config = ConfigParser.ConfigParser()\n config.readfp(file_input)\n\n hash_cfg = {}\n\n for field in config.options('GENERAL'):\n hash_cfg[field] = config.get('GENERAL', field)\n\n for field in config.options('OUTPUT'):\n hash_cfg[field] = config.get('OUTPUT', field)\n\n for field in config.options('REFERENCE'):\n hash_cfg[field] = config.get('REFERENCE', field)\n\n for field in config.options('SOFTWARE'):\n hash_cfg[field] = config.get('SOFTWARE', field)\n\n file_input.close()\n\n return hash_cfg\n\n\ndef compute_expansion_hunter_offtarget_reads(eh_path, lp_id, gender, bam_path, fasta_file,\n specs_path, output_path, logger):\n \"\"\"\n Calling EH algorithm, with the off-target functionality\n :param eh_path: path to the EH binary file\n :param lp_id: LP id\n :param gender: sex male/female\n :param bam_path: path to the BAM file\n :param fasta_file: path to the human reference file (GRCh37 or GRCh38)\n :param specs_path: path to the folder containing genomic coordinates for each STR locus defined\n :param output_path: path to the output folder in which EH will write the results\n :param logger: logger object\n :return:\n \"\"\"\n\n # We need to take the BAM file from the structure - from bam_path/Assembly/<lp_id>.bam\n bam_path = os.path.join(bam_path, 'Assembly')\n bam_file = os.path.join(bam_path, lp_id + '.bam')\n # if bam path is already provided in the batch files, there is no need in adding the /Assembly/information\n # bam_file = bam_path\n\n # Definition of the output files: VCF, JSON and the output LOG files\n output_prefix = os.path.join(output_path, 'EH_' + lp_id)\n if os.path.exists(bam_file):\n args = [eh_path, '--reads', bam_file, '--sex', gender, '--reference', fasta_file, '--variant-catalog',\n specs_path, '--output-prefix', output_prefix, '--log-level', 'error']\n\n eh_output = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, bufsize=1)\n (out_info, log_data) = eh_output.communicate()\n eh_output.wait()\n\n logger.info('EH output %s \\n%s\\n' % (lp_id, out_info))\n logger.info('EH log output:\\n%s\\n' % log_data)\n\n if 'error' in log_data:\n if log_data.lower().find('error') != -1:\n raise RuntimeError('run_EH.compute_expansion_hunter: Error in running EH:\\n%s'\n % log_data)\n else:\n raise IOError(\"The BAM file %s does not exist\" % bam_file)\n\n\ndef run(argv=None):\n if argv is None:\n argv = sys.argv\n\n parser = OptionParser(add_help_option=True, description=\"\")\n\n parser.add_option(\"--cfg\", default=None,\n help=\"Config file with the complete information of the target regions\"\n \"and paths of the files needed for the calling\", dest=\"f_cfg\")\n\n (options, args) = parser.parse_args(argv[1:])\n\n if len(argv) == 1:\n sys.exit(0)\n\n if not parser.check_required(\"--cfg\"):\n raise IOError('The cfg file does not exist')\n\n if options.f_cfg is not None:\n\n cfg_file = options.f_cfg\n\n if not os.path.exists(cfg_file):\n raise IOError('The cfg file %s does not exist' % cfg_file)\n\n hash_cfg = read_cfg_file(cfg_file)\n\n f_catalog = hash_cfg.get('catalog_file', '')\n\n if not os.path.isfile(f_catalog):\n raise IOError('The tsv file including the individuals to be analyse '\n 'does not exist. %s' % f_catalog)\n\n # Output folder in which the output of popSTR will be saved\n output_path = hash_cfg.get('output_path', '')\n\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n # Path to the EH algorithm\n eh_path = hash_cfg.get('eh_path', '')\n\n if not os.path.exists(eh_path):\n raise IOError('The executable binary file with the EH algorithm '\n 'does not exist %s' % eh_path)\n\n # FASTA file\n fasta_file = hash_cfg.get('fasta_file', '')\n\n if not os.path.isfile(fasta_file):\n raise IOError('The human genome reference fasta file does not exist %s'\n % fasta_file)\n\n specs_path = hash_cfg.get('specs_path', '')\n\n if not os.path.isfile(specs_path):\n raise IOError(\n 'The json file containing coordinates for STR loci genomic '\n 'positions of each STR loci or markers does not exist %s'\n % specs_path)\n\n formatter = logging.Formatter('%(asctime)s - %(module)s - %(levelname)s - %(message)s')\n console = logging.StreamHandler()\n console.setFormatter(formatter)\n console.setLevel(logging.INFO)\n logger = logging.getLogger(\"preprocess\")\n logger.setLevel(logging.INFO)\n logger.addHandler(console)\n\n logger.info(\"The detection of STRs by using EH started ...\")\n\n logger.info(\"1 - Reading the information of the individuals to be analysed ...\")\n\n hash_path, hash_gender = read_tsv_file(f_catalog)\n\n logger.info(\"2 - Detecting the STR for each sample ...\")\n\n for lp_id, path in hash_path.iteritems():\n gender = hash_gender.get(lp_id)\n logger.info(\"Running EH in %s, path is %s and gender is %s\" % (lp_id, path, gender))\n # for every chr in each individual we pass it\n if path == '.':\n continue\n compute_expansion_hunter_offtarget_reads(eh_path, lp_id, gender, path, fasta_file,\n specs_path, output_path, logger)\n logger.info(\"... finished\")\n\n logger.info('Finished running EH algorithm')\n\n\nif __name__ == '__main__':\n run()\n\n","sub_path":"EH/run_EH_v3.1.2.py","file_name":"run_EH_v3.1.2.py","file_ext":"py","file_size_in_byte":7213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"275285292","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom blog import Article #ArticleLikes\nfrom django.template import RequestContext\nfrom blog import Category\nfrom django.db.models import Count, F\n\n\ndef create_context(request):\n context = RequestContext(request)\n article_set = Article.get_published().order_by('-created').annotate(likes=Count('articlelikes'))\n categories = Category.objects.annotate(articles=Count('article')).order_by('-articles')\n context.push({\n 'categories': categories,\n 'popular_tags': Article.get_counted_tags(),\n 'article_set': article_set,\n })\n return context\n\n\ndef article_analytics(request, article_set):\n query_set = article_set.order_by('-created')\n newest = query_set[0].created.year\n oldest = query_set.reverse()[0].created.year\n article_by_year = dict()\n for year in range(oldest, newest+1):\n try:\n temp = query_set.filter(created__year=year)\n article_by_year.update({year:{}})\n for month in range(1,13):\n by_month = temp.filter(created__month=month)\n if by_month:\n article_by_year[year].update({by_month[0].created:temp.filter(created__month=month)})\n except:\n pass\n return article_by_year\n\n\n# for future use\ndef handle_uploaded_file(f, type=None):\n\n with open('some/file/name.txt', 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)","sub_path":"blog/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"290245966","text":"from decimal import Decimal\n\nfrom cryptofeed.exchanges import Binance\nfrom yapic import json as json_parser\n\n\ndef temp_f(r, address, json=False, text=False, uuid=None):\n if r.status_code == 451:\n return {'symbols': []}\n r.raise_for_status()\n if json:\n return json_parser.loads(r.text, parse_float=Decimal)\n if text:\n return r.text\n return r \n\nBinance.http_sync.process_response = temp_f\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"57733962","text":"import torch\nimport math\nimport torch.optim as optim\nimport torch.nn as nn\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pytorchtools import EarlyStopping\n\n\ndef training(model, train_data, ground_truth, eval_data, eval_ground_truth, lr, epochs, patience, weight_decay):\n num_batches = len(train_data)\n optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n early_stopping = EarlyStopping(patience=patience, verbose=False)\n \n # print train_data and ground truth\n fig_dif = plt.figure()\n plt.plot( np.concatenate( train_data )[:,0] )\n plt.plot( np.concatenate( ground_truth) )\n plt.savefig('Figs/score_difference.png')\n plt.close()\n\n for epoch in range(epochs):\n\n store_res = [] \n store_gt = []\n store_loss = []\n store_ev_loss = []\n for batch in range(num_batches):\n #loss = nn.L1Loss()\n loss = nn.MSELoss()\n model.train()\n optimizer.zero_grad()\n\n # compute the loss \n output = model(train_data[batch])\n loss_train = loss(output, ground_truth[batch])\n store_loss.append( loss_train.detach().numpy() )\n store_res.append( output.detach().numpy() )\n store_gt.append( ground_truth[batch].detach().numpy() )\n\n # backpropagate\n loss_train.backward() \n\n # new step\n optimizer.step() \n\n # validate the model\n model.eval()\n ev_output = model( eval_data[batch] )\n ev_loss = loss(ev_output, eval_ground_truth[batch])\n store_ev_loss.append( ev_loss.detach().numpy() ) \n \n early_stopping(np.mean(store_ev_loss), model)\n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n\n\n if epoch%50 == 0:\n print('epoch, loss, ev_loss',epoch, np.mean(store_loss), np.mean(store_ev_loss))\n \n # Load model\n model.load_state_dict(torch.load('checkpoint.pt'))\n\n fig_train = plt.figure()\n plt.plot( np.concatenate( store_gt, axis=0), label='gt' )\n plt.plot( np.concatenate( store_res, axis=0 ), label='learned' )\n plt.legend()\n plt.savefig('Figs/train_res.png')\n plt.close()\n\n return model\n\n\ndef prepare_data_train(seq, snaps, method, hops):\n #####################\n # Feature vectors for all the points on all the snapshopts\n feat_train_data = []; train_data = []; feat_eval_data = []; eval_data = [];\n\n for snapshot in range(snaps):\n\n # indices of the active nodes (not the ones that have left or havent joined the graph)\n idx = np.where( seq[snapshot+1].clust_memb > 0 )[0]\n \n # feature 1: pagerank on the nodes that are active\n if method == 'PageRank':\n feat_1 = seq[snapshot].pr.T[idx] \n elif method == 'GammaPageRank':\n feat_1 = seq[snapshot].gpr[idx]\n \n # diffuse in both graphs\n val_g2 = [feat_1]\n val_g1 = [feat_1]\n tmp_feat = []\n for k in range(hops):\n if method == 'PageRank':\n val_g2.append( seq[snapshot+1].P[np.ix_(idx,idx)].T.dot(val_g2[k]))\n val_g1.append( seq[snapshot].P[np.ix_(idx,idx)].T.dot(val_g1[k]) )\n tmp_feat.append( val_g1[k+1] )\n tmp_feat.append( val_g2[k+1] )\n elif method == 'GammaPageRank':\n val_g2.append( seq[snapshot+1].P2[np.ix_(idx,idx)].dot(val_g2[k]) )\n val_g1.append( seq[snapshot].P2[np.ix_(idx,idx)].dot(val_g1[k]) ) \n tmp_feat.append( val_g1[k+1] )\n tmp_feat.append( val_g2[k+1] )\n tmp_feat = np.concatenate( tmp_feat, axis=1 )\n\n\n # subsample the amount of changes\n nzero_idx = np.where(idx)[0]\n tot_nzero = math.ceil( len(nzero_idx) )\n if len(idx)/2 < tot_nzero:\n tmp_idx = np.arange(math.ceil(tot_nzero/2))\n tmp_eval = np.arange(math.ceil(tot_nzero/2), tot_nzero)\n tmp_nzero_idx = np.random.permutation(nzero_idx) \n nzero_idx = tmp_nzero_idx[tmp_idx]\n eval_idx = tmp_nzero_idx[tmp_eval]\n \n # features\n feat_train_data.append( torch.tensor(np.concatenate([feat_1[nzero_idx], tmp_feat[nzero_idx]], axis=1)).double() )\n\n feat_eval_data.append( torch.tensor(np.concatenate([feat_1[eval_idx], tmp_feat[eval_idx]], axis=1)).double() )\n\n # Ground truth\n if method == 'PageRank':\n ground_truth = seq[snapshot+1].pr.T[idx]\n train_data.append( torch.tensor( ground_truth[nzero_idx] ).double() )\n eval_data.append( torch.tensor( ground_truth[eval_idx] ).double() )\n elif method == 'GammaPageRank':\n ground_truth = seq[snapshot+1].gpr[idx]\n train_data.append( torch.tensor( ground_truth[nzero_idx] ).double() )\n eval_data.append( torch.tensor( ground_truth[eval_idx] ).double() )\n\n return feat_train_data, train_data, feat_eval_data, eval_data\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"385823533","text":"import requests\nimport numpy as np\n\n\ndef encode_serve(matri):\n url = \"http://localhost:8502/v1/models/encode_test:predict\"\n data = {\"instances\": matri}\n res = requests.post(url, json=data)\n return eval(res.text)[\"predictions\"]\n\n\ndef decode_serve(matri):\n url = \"http://localhost:8501/v1/models/decode_test:predict\"\n data = {\"instances\": matri}\n res = requests.post(url, json=data)\n print(eval(res.text))\n return eval(res.text)[\"predictions\"]\n","sub_path":"chatbot/tf_serving/post_docker.py","file_name":"post_docker.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"98395577","text":"import os, sys\nimport torch\n\nfrom model import *\n\ndef evaluate(opt):\n\tevalPath = opt.data_root+'train_pair.lst'\n\n\t# create data loaders from dataset\n\ttransform = transforms.Compose([\n\t\t\t\t\t\t\t\t\ttransforms.ToTensor(),\n\t\t\t\t\t\t\t\t\ttransforms.Normalize(opt.mean,opt.std)\n\t\t\t\t\t\t\t])\n\ttargetTransform = transforms.Compose([\n\t\t\t\t\t\t\t\t\ttransforms.ToTensor()\n\t\t\t\t\t\t\t])\n\n\tevalDataset = TrainDataset(evalPath, opt.data_root, transform, targetTransform)\n\tevalDataloader = DataLoader(evalDataset, shuffle=False)\n\n\t\t# initialize the network\n\tif opt.arch == 'vgg16':\n\t\tnet = HED_vgg16()\n\telif opt.arch == 'vgg16_bn':\n\t\tnet = HED_vgg16_bn()\n\telse:\n\t\traise NotImplementedError\n\n\t","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"143640046","text":"from captcha.fields import ReCaptchaField\nfrom crispy_forms.layout import HTML, Div, Field\nfrom django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom extrequests.forms import (\n WorkshopRequestBaseForm,\n WorkshopInquiryRequestBaseForm,\n SelfOrganisedSubmissionBaseForm,\n)\nfrom workshops.fields import (\n RadioSelectWithOther,\n CheckboxSelectMultipleWithOthers,\n Select2Widget,\n)\nfrom workshops.models import TrainingRequest\nfrom workshops.forms import BootstrapHelper\n\n\nclass TrainingRequestForm(forms.ModelForm):\n # agreement fields are moved to the model\n\n captcha = ReCaptchaField()\n\n helper = BootstrapHelper(wider_labels=True, add_cancel_button=False)\n\n class Meta:\n model = TrainingRequest\n fields = (\n 'review_process',\n 'group_name',\n 'personal',\n 'family',\n 'email',\n 'secondary_email',\n 'github',\n 'occupation',\n 'occupation_other',\n 'affiliation',\n 'location',\n 'country',\n 'underresourced',\n 'domains',\n 'domains_other',\n 'underrepresented',\n 'underrepresented_details',\n 'nonprofit_teaching_experience',\n 'previous_involvement',\n 'previous_training',\n 'previous_training_other',\n 'previous_training_explanation',\n 'previous_experience',\n 'previous_experience_other',\n 'previous_experience_explanation',\n 'programming_language_usage_frequency',\n 'teaching_frequency_expectation',\n 'teaching_frequency_expectation_other',\n 'max_travelling_frequency',\n 'max_travelling_frequency_other',\n 'reason',\n 'user_notes',\n 'data_privacy_agreement',\n 'code_of_conduct_agreement',\n 'training_completion_agreement',\n 'workshop_teaching_agreement',\n )\n widgets = {\n 'review_process': forms.RadioSelect(),\n 'occupation': RadioSelectWithOther('occupation_other'),\n 'domains': CheckboxSelectMultipleWithOthers('domains_other'),\n 'underrepresented': forms.RadioSelect(),\n 'previous_involvement': forms.CheckboxSelectMultiple(),\n 'previous_training': RadioSelectWithOther(\n 'previous_training_other'),\n 'previous_experience': RadioSelectWithOther(\n 'previous_experience_other'),\n 'programming_language_usage_frequency': forms.RadioSelect(),\n 'teaching_frequency_expectation': RadioSelectWithOther(\n 'teaching_frequency_expectation_other'),\n 'max_travelling_frequency': RadioSelectWithOther(\n 'max_travelling_frequency_other'),\n 'country': Select2Widget,\n }\n\n def __init__(self, *args, initial_group_name=None, **kwargs):\n initial = kwargs.pop('initial', {})\n if initial_group_name is not None:\n initial['group_name'] = initial_group_name\n initial['review_process'] = 'preapproved'\n super().__init__(*args, initial=initial, **kwargs)\n if initial_group_name is not None:\n field = self.fields['group_name']\n field.widget = field.hidden_widget()\n\n # set up a layout object for the helper\n self.helper.layout = self.helper.build_default_layout(self)\n\n # set up RadioSelectWithOther widget so that it can display additional\n # field inline\n self['occupation'].field.widget.other_field = self['occupation_other']\n self['domains'].field.widget.other_field = self['domains_other']\n self['previous_training'].field.widget.other_field = (\n self['previous_training_other'])\n self['previous_experience'].field.widget.other_field = (\n self['previous_experience_other'])\n self['teaching_frequency_expectation'].field.widget.other_field = (\n self['teaching_frequency_expectation_other'])\n self['max_travelling_frequency'].field.widget.other_field = (\n self['max_travelling_frequency_other'])\n\n # remove that additional field\n self.helper.layout.fields.remove('occupation_other')\n self.helper.layout.fields.remove('domains_other')\n self.helper.layout.fields.remove('previous_training_other')\n self.helper.layout.fields.remove('previous_experience_other')\n self.helper.layout.fields.remove(\n 'teaching_frequency_expectation_other')\n self.helper.layout.fields.remove('max_travelling_frequency_other')\n\n # fake requiredness of the registration code / group name\n self['group_name'].field.widget.fake_required = True\n\n # special accordion display for the review process\n self['review_process'].field.widget.subfields = {\n 'preapproved': [\n self['group_name'],\n ],\n 'open': [], # this option doesn't require any additional fields\n }\n self['review_process'].field.widget.notes = \\\n TrainingRequest.REVIEW_CHOICES_NOTES\n\n # get current position of `review_process` field\n pos_index = self.helper.layout.fields.index('review_process')\n\n self.helper.layout.fields.remove('review_process')\n self.helper.layout.fields.remove('group_name')\n\n # insert div+field at previously saved position\n self.helper.layout.insert(\n pos_index,\n Div(\n Field('review_process',\n template=\"bootstrap4/layout/radio-accordion.html\"),\n css_class='form-group row',\n ),\n )\n\n # add <HR> around \"underrepresented*\" fields\n index = self.helper.layout.fields.index('underrepresented')\n self.helper.layout.insert(\n index, HTML(self.helper.hr()))\n\n index = self.helper.layout.fields.index('underrepresented_details')\n self.helper.layout.insert(\n index + 1, HTML(self.helper.hr()))\n\n def clean(self):\n super().clean()\n errors = dict()\n\n # 1: validate registration code / group name\n review_process = self.cleaned_data.get('review_process', '')\n group_name = self.cleaned_data.get('group_name', '').split()\n\n # it's required when review_process is 'preapproved', but not when\n # 'open'\n if review_process == 'preapproved' and not group_name:\n errors['review_process'] = ValidationError(\n \"Registration code is required for pre-approved training \"\n \"review process.\"\n )\n\n # it's required to be empty when review_process is 'open'\n if review_process == 'open' and group_name:\n errors['review_process'] = ValidationError(\n \"Registration code must be empty for open training review \"\n \"process.\"\n )\n\n if errors:\n raise ValidationError(errors)\n\n\nclass WorkshopRequestExternalForm(WorkshopRequestBaseForm):\n captcha = ReCaptchaField()\n\n class Meta(WorkshopRequestBaseForm.Meta):\n fields = WorkshopRequestBaseForm.Meta.fields + (\"captcha\", )\n\n\nclass WorkshopInquiryRequestExternalForm(WorkshopInquiryRequestBaseForm):\n captcha = ReCaptchaField()\n\n class Meta(WorkshopInquiryRequestBaseForm.Meta):\n fields = WorkshopInquiryRequestBaseForm.Meta.fields + (\"captcha\", )\n\n\nclass SelfOrganisedSubmissionExternalForm(SelfOrganisedSubmissionBaseForm):\n captcha = ReCaptchaField()\n\n class Meta(SelfOrganisedSubmissionBaseForm.Meta):\n fields = SelfOrganisedSubmissionBaseForm.Meta.fields + (\"captcha\", )\n","sub_path":"amy/extforms/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"227981981","text":"from transformice.game.ClientManager import ClientManager\r\nfrom transformice.game.clients.Client import Client\r\nfrom transformice.messages.output.server.OPLoginResult import OPLoginResult\r\n\r\n\r\nclass Transformice:\r\n\r\n @staticmethod\r\n def login(session, data, start_room):\r\n print(data)\r\n if ClientManager.contains(data):\r\n session.send(OPLoginResult(1, \"\"))\r\n return\r\n if len(data) <= 0:\r\n session.send(OPLoginResult(2, \"\"))\r\n return\r\n client = Client(session, data[0], ClientManager.generatePlayerCode())\r\n ClientManager.append(client.data()[\"Username\"], client)\r\n session.client = client","sub_path":"transformice/Transformice.py","file_name":"Transformice.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"317728895","text":"import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n\n# System model:\ndef vessel(F, t, qout, qin, Cf, Tf):\n # Parameters\n V = F[0]\n C = F[1]\n T = F[2]\n r=0\n\n # Mass balance ro=Const\n dVdt = qin - qout\n\n # Concentration balance\n # d(V*C)/s]dt = C*dV/dt + V*dC/dt\n dCdt = (qin * Cf - qout * C) / V - r - (C * dVdt) / V\n\n # Energy balance\n # d(T*V)/dt = T*dV/dt + V*dT/dt\n dTdt = (qin * Tf - qout * T) / V - (T * dVdt) / V\n return [dVdt, dCdt, dTdt]\n\n\ndef main():\n V0 = 1.0\n C0 = 0.0\n T0 = 350.0\n F0 = [V0, C0, T0]\n\n # Time\n t = np.linspace(0, 10, 100)\n\n # Reaction\n r = np.zeros(len(t))\n\n # Flows\n qin = np.ones(len(t)) * 5.2\n qin[50:] = 5.1\n qout = np.ones(len(t)) * 5.0\n\n # Concentration\n Cf = np.ones(len(t)) * 1.0\n Cf[30:] = 0.5\n\n # Temperature\n Tf = np.ones(len(t)) * 300.0\n Tf[70:] = 325.0\n\n # Storage\n V = np.ones(len(t)) * V0\n C = np.ones(len(t)) * C0\n T = np.ones(len(t)) * T0\n\n # Simulate\n for it in range(len(t)-1):\n inputs = (qout[it], qin[it], Cf[it], Tf[it])\n ts = [t[it], t[it + 1]]\n F = odeint(vessel, F0, ts, args=inputs)\n\n # Restore\n V[it + 1] = F[-1][0]\n C[it + 1] = F[-1][1]\n T[it + 1] = F[-1][2]\n F0 = F[-1]\n\n # Plot the inputs and results\n plt.figure()\n\n plt.subplot(3, 2, 1)\n plt.plot(t, qin, 'b--', linewidth=3)\n plt.plot(t, qout, 'b:', linewidth=3)\n plt.ylabel('Flow Rates (L/min)')\n plt.legend(['Inlet', 'Outlet'], loc='best')\n\n plt.subplot(3, 2, 3)\n plt.plot(t, Cf, 'r--', linewidth=3)\n plt.ylabel('Cf (mol/L)')\n plt.legend(['Feed Concentration'], loc='best')\n\n plt.subplot(3, 2, 5)\n plt.plot(t, Tf, 'k--', linewidth=3)\n plt.ylabel('Tf (K)')\n plt.legend(['Feed Temperature'], loc='best')\n plt.xlabel('Time (min)')\n\n plt.subplot(3, 2, 2)\n plt.plot(t, V, 'b-', linewidth=3)\n plt.ylabel('Volume (L)')\n plt.legend(['Volume'], loc='best')\n\n plt.subplot(3, 2, 4)\n plt.plot(t, C, 'r-', linewidth=3)\n plt.ylabel('C (mol/L)')\n plt.legend(['Concentration'], loc='best')\n\n plt.subplot(3, 2, 6)\n plt.plot(t, T, 'k-', linewidth=3)\n plt.ylabel('T (K)')\n plt.legend(['Temperature'], loc='best')\n plt.xlabel('Time (min)')\n\n plt.show()\n\n\nmain()","sub_path":"Home/PythonODE/SysODE.py","file_name":"SysODE.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"111270003","text":"from tkinter import *\r\nimport logging\r\nfrom Game import Game\r\n\r\ndef donothing(event):\r\n filewin = Toplevel(root)\r\n button = Button(filewin, text=\"Do nothing button\")\r\n button.pack()\r\n\r\ndef get_configuration():\r\n return \"Default\", \"File\"\r\n\r\nif __name__ == \"__main__\":\r\n root = Tk()\r\n\r\n configuration, input = get_configuration()\r\n game = Game(configuration, input, root)\r\n\r\n menubar = Menu(root)\r\n filemenu = Menu(menubar, tearoff = 0)\r\n filemenu.add_command(label=\"Configure\")\r\n filemenu.add_command(label=\"Run\", command=game)\r\n filemenu.add_separator()\r\n filemenu.add_command(label = \"Exit\", command = root.quit)\r\n menubar.add_cascade(label = \"File\", menu = filemenu)\r\n\r\n root.columnconfigure(0, weight=1)\r\n root.rowconfigure(0, weight=1)\r\n root.config(menu = menubar)\r\n\r\n logging.basicConfig(level=logging.INFO)\r\n logging.debug('This will get logged')\r\n\r\n root.mainloop()\r\n","sub_path":"Framework.py","file_name":"Framework.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"346144432","text":"import numpy as np\r\nimport random\r\nimport string\r\n\r\n# zrobic slicami lepiej\r\n# np.zeros((x,x),dtype='str')\r\n#a[0,0:3] = list('kot')\r\n# np.put\r\n\r\nword = \"ciupaga\"\r\nlist = list(word)\r\nn = len(word)\r\nmat = np.chararray((n+1,n))\r\nfor x in range(n+1):\r\n for y in range(n):\r\n mat[x,y]=random.choice(string.ascii_lowercase)\r\nfor x in range(n):\r\n mat[0,x]=list[x]\r\n mat[x,0]=list[x]\r\nfor y in range(n):\r\n mat[y,y]=list[y]\r\nlist.reverse()\r\nprint(list)\r\nfor x in range(n):\r\n mat[n,x]=list[x]\r\nprint(mat)","sub_path":"cw_6/zad6.py","file_name":"zad6.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"440723939","text":"\n\nfrom xai.brain.wordbase.nouns._petunia import _PETUNIA\n\n#calss header\nclass _PETUNIAS(_PETUNIA, ):\n\tdef __init__(self,): \n\t\t_PETUNIA.__init__(self)\n\t\tself.name = \"PETUNIAS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"petunia\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_petunias.py","file_name":"_petunias.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"243274910","text":"import os\nimport pathlib\n\nfrom .dataset import Dataset\n\nfrom ..utils import read_csv\nfrom ..utils import read_json\n\n\n__all__ = ['CountriesS1']\n\n\nclass CountriesS1(Dataset):\n \"\"\"CountriesS1 dataset.\n\n countriesS1 aim to iterate over the associated dataset. It provide positive samples, corresponding\n weights and the mode (head batch / tail batch)\n\n Parameters:\n batch_size (int): Size of the batch.\n classification (bool): Must be set to True when using ConvE model to optimize BCELoss.\n shuffle (bool): Whether to shuffle the dataset or not.\n pre_compute (bool): Pre-compute parameters such as weights when using translationnal model\n (TransE, DistMult, RotatE, pRotatE, ComplEx). When using ConvE, pre-compute target\n matrix. When pre_compute is set to True, the model training is faster but it needs more\n memory.\n num_workers (int): Number of workers dedicated to iterate on the dataset.\n seed (int): Random state.\n\n Attributes:\n train (list): Training set.\n valid (list): Validation set.\n test (list): Testing set.\n entities (dict): Index of entities.\n relations (dict): Index of relations.\n n_entity (int): Number of entities.\n n_relation (int): Number of relations.\n\n Example:\n\n >>> from mkb import datasets\n\n >>> dataset = datasets.CountriesS1(batch_size=1, pre_compute=True, shuffle=False, seed=42)\n\n >>> dataset\n CountriesS1 dataset\n Batch size 1\n Entities 271\n Relations 2\n Shuffle False\n Train triples 1111\n Validation triples 24\n Test triples 24\n\n >>> import torch\n\n >>> dataset = datasets.CountriesS1(batch_size=2, classification=False,\n ... pre_compute=True, shuffle=False, seed=42)\n\n >>> for data in dataset:\n ... assert data['sample'].shape == torch.Size([2, 3])\n ... assert data['weight'].shape == torch.Size([2])\n ... break\n\n References:\n 1. [Bouchard, Guillaume, Sameer Singh, and Theo Trouillon. \"On approximate reasoning capabilities of low-rank vector spaces.\" 2015 AAAI Spring Symposium Series. 2015.](https://www.aaai.org/ocs/index.php/SSS/SSS15/paper/view/10257/10026)\n 2. [Datasets for Knowledge Graph Completion with Textual Information about Entities](https://github.com/villmow/datasets_knowledge_embedding)\n\n \"\"\"\n\n def __init__(self, batch_size, classification=False, shuffle=True, pre_compute=True,\n num_workers=1, seed=42):\n\n self.filename = 'countries_s1'\n\n path = pathlib.Path(__file__).parent.joinpath(self.filename)\n\n super().__init__(\n train=read_csv(file_path=f'{path}/train.csv'),\n valid=read_csv(file_path=f'{path}/valid.csv'),\n test=read_csv(file_path=f'{path}/test.csv'),\n classification=classification,\n pre_compute=pre_compute,\n entities=read_json(f'{path}/entities.json'),\n relations=read_json(f'{path}/relations.json'),\n batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, seed=seed\n )\n","sub_path":"mkb/datasets/countries_s1.py","file_name":"countries_s1.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"486305072","text":"from flask import Blueprint, json\nfrom flask.signals import request_finished\nfrom app import db\nfrom flask import request, make_response, jsonify\nfrom datetime import datetime, date, timedelta\nfrom app.models.customer import Customer\nfrom app.models.video import Video\nfrom app.models.rental import Rental\nimport os\nimport requests\n\ncustomer_bp = Blueprint(\"customers\", __name__, url_prefix=\"/customers\")\nvideo_bp = Blueprint(\"videos\", __name__, url_prefix=\"/videos\")\nrental_bp = Blueprint(\"rentals\", __name__, url_prefix=\"/rentals\")\n\n# Wave 1 Customer routers\n# Lists all existing customers and details about each customer. No arguments\n@customer_bp.route(\"\", methods=[\"GET\"])\ndef get_all_customers():\n customers = Customer.query.all()\n customers_response = []\n for customer in customers:\n customers_response.append(customer.customer_info())\n\n return jsonify(customers_response)\n\n\n# Gives back details about specific customer with required argument \"id\"\n@customer_bp.route(\"/<customer_id>\", methods=[\"GET\"])\ndef get_specific_customer(customer_id):\n customer = Customer.query.get(customer_id)\n\n if customer is None:\n return make_response(\"\", 404)\n else:\n return make_response(customer.customer_info(), 200)\n\n\n# Creates a new video with the params \"name\", \"postal_code\", \"phone\"\n@customer_bp.route(\"\", methods=[\"POST\"])\ndef create_customer():\n request_body = request.get_json()\n required_properties = [\"name\", \"postal_code\", \"phone\"]\n for prop in required_properties:\n if prop not in request_body:\n return make_response({\"details\": \"Invalid data\"}, 400)\n \n new_customer = Customer(name=request_body[\"name\"],\n postal_code=request_body[\"postal_code\"],\n phone_number=request_body[\"phone\"])\n\n db.session.add(new_customer)\n db.session.commit() \n \n return make_response({\"id\": new_customer.customer_id}, 201)\n\n\n# Updates and returns details about specific customer with params \"name\", \"postal_code\", and \"phone\"\n@customer_bp.route(\"/<customer_id>\", methods=[\"PUT\"])\ndef update_customer(customer_id):\n customer = Customer.query.get(customer_id)\n request_body = request.get_json()\n\n if customer is None:\n return make_response(\"Not Found\", 404)\n\n required_properties = [\"name\", \"postal_code\", \"phone\"]\n for prop in required_properties:\n if len(prop)==0 or prop not in request_body:\n return make_response({\"details\": \"Bad Request\"}, 400)\n else:\n customer.name=request_body[\"name\"]\n customer.postal_code=request_body[\"postal_code\"]\n customer.phone_number=request_body[\"phone\"]\n \n db.session.commit()\n return make_response(customer.customer_info(), 200)\n\n\n@customer_bp.route(\"/<customer_id>\", methods=[\"DELETE\"])\ndef delete_customer(customer_id):\n customer = Customer.query.get(customer_id)\n\n if customer is None:\n return make_response(\"\", 404)\n else:\n db.session.delete(customer)\n db.session.commit()\n \n return make_response({\"id\": customer.customer_id}, 200)\n\n\n# Wave 1 Video routes\n@video_bp.route(\"\", methods=[\"GET\"])\ndef get_all_videos():\n videos = Video.query.all()\n videos_response = []\n for video in videos:\n videos_response.append(video.video_info())\n\n return jsonify(videos_response)\n\n\n@video_bp.route(\"\", methods=[\"POST\"])\ndef create_video():\n request_body = request.get_json()\n required_properties = [\"title\", \"release_date\", \"total_inventory\"]\n for prop in required_properties:\n if prop not in request_body:\n return make_response({\"details\": \"Invalid data\"}, 400)\n \n new_video = Video(title=request_body[\"title\"],\n release_date=request_body[\"release_date\"],\n total_inventory=request_body[\"total_inventory\"],\n available_inventory=request_body[\"total_inventory\"])\n\n db.session.add(new_video)\n db.session.commit() \n return make_response({\"id\": new_video.video_id}, 201)\n\n\n@video_bp.route(\"/<video_id>\", methods=[\"GET\"])\ndef get_videos(video_id):\n video = Video.query.get(video_id)\n\n if video is None:\n return make_response(\"\", 404)\n else:\n return make_response(video.video_info())\n\n\n@video_bp.route(\"/<video_id>\", methods=[\"PUT\"])\ndef update_video(video_id):\n video = Video.query.get(video_id)\n request_body = request.get_json(silent=False)\n\n if video is None:\n return make_response(\"\", 404)\n else:\n video.title=request_body[\"title\"]\n video.release_date=request_body[\"release_date\"]\n video.total_inventory=request_body[\"total_inventory\"]\n \n db.session.commit()\n return make_response(video.video_info(), 200)\n \n\n@video_bp.route(\"/<video_id>\", methods=[\"DELETE\"])\ndef delete_video(video_id):\n video = Video.query.get(video_id)\n \n if video is None:\n return make_response(\"\", 404)\n else:\n db.session.delete(video)\n db.session.commit()\n \n return make_response({\"id\": video.video_id}, 200)\n\n\n# Wave 2 Rental routes\n# Checks out a video to a customer, and updates the data in the database\n# Required request body parameters are customer_id and video_id\n@rental_bp.route(\"/check-out\", methods=[\"POST\"])\ndef rental_checkout():\n request_body = request.get_json()\n customer_id = request_body[\"customer_id\"]\n video_id = request_body[\"video_id\"]\n\n customer = Customer.query.get(customer_id)\n if \"customer_id\" not in request_body or \"video_id\" not in request_body:\n return make_response({\"details\": \"Not Found\"}, 400)\n\n if not isinstance(customer_id, int) or not isinstance(video_id, int):\n return make_response({\"details\": \"Not Found\"}, 400)\n \n video = Video.query.get(video_id)\n if video.available_inventory < 1:\n return make_response({\"details\": \"Bad Request\"}, 400)\n \n customer.videos_checked_out_count += 1\n video.available_inventory -= 1\n # Create this as a person who is renting something new\n new_rental = Rental(customer_id=customer_id,\n video_id=video_id,\n due_date=(datetime.now() + timedelta(days=7)))\n\n db.session.add(new_rental)\n db.session.commit()\n \n return jsonify({\n \"customer_id\": new_rental.customer_id,\n \"video_id\": new_rental.video_id,\n \"due_date\": new_rental.due_date,\n \"videos_checked_out_count\": customer.videos_checked_out_count,\n \"available_inventory\": video.available_inventory\n }), 200\n\n\n# Checks in a video to a customer, and updates the data in the database as such.\n# Required request body parameters are customer_id and video_id\n@rental_bp.route(\"/check-in\", methods=[\"POST\"])\ndef rental_checkin():\n request_body = request.get_json()\n customer_id = request_body[\"customer_id\"]\n video_id = request_body[\"video_id\"]\n\n customer = Customer.query.get(customer_id)\n video = Video.query.get(video_id)\n if \"customer_id\" not in request_body or \"video_id\" not in request_body:\n return make_response({\"details\": \"Not Found\"}, 404)\n\n if video and customer in request_body:\n customer.videos_checked_out_count -= 1\n video.available_inventory += 1\n\n db.session.commit()\n \n return jsonify({\n \"customer_id\": customer_id,\n \"video_id\": video_id,\n \"videos_checked_out_count\": customer.videos_checked_out_count,\n \"available_inventory\": video.available_inventory\n }), 200\n # else:\n # return jsonify({\"video and customer do not match a current rental\"}, 400)\n\n\n@rental_bp.route(\"customers/<customer_id>/rentals\", methods=[\"GET\"])\ndef customers_video_rentals(customer_id):\n rentals = Rental.query.get(customer_id)\n customers = Customer.query.get(customer_id)\n video = Video.query.get(customer_id)\n video_rental_list = []\n\n if rentals is None:\n return make_response(\"Not Found\", 404)\n \n for rental in rentals:\n video = Video.query.get(rental.video_id)\n video_rental_list.append()\n\n return make_response({\n \"release_date\": video.release_date,\n \"title\": video.title,\n \"due_date\": rental.due_date\n }), 200\n\n\n@rental_bp.route(\"videos/<video_id>/rentals\", methods=[\"GET\"])\ndef customers_with_due_date(video_id):\n rentals = Rental.query.get(video_id)\n customers = Customer.query.get(video_id)\n video = Video.query.get(video_id)\n\n if rentals is None:\n return make_response(\"\", 404)\n else:\n return make_response({\n \"due_date\": rental.due_date,\n \"name\": customer.phone,\n \"postal_code\": customer.postal_code\n }), 200","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":8716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"29143288","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community\nEdition) available.\nCopyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\nimport logging\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom gcloud.taskflow3.models import TaskFlowInstance\nfrom gcloud.taskflow3.signals import taskflow_finished\nfrom gcloud.commons.message import send_task_flow_message, ATOM_FAILED, TASK_FINISHED\nfrom pipeline.models import PipelineInstance\n\nlogger = logging.getLogger('celery')\n\n\n@receiver(post_save, sender=PipelineInstance)\ndef pipeline_post_save_handler(sender, instance, created, **kwargs):\n if not created and instance.is_finished:\n try:\n taskflow = TaskFlowInstance.objects.get(pipeline_instance=instance)\n except TaskFlowInstance.DoesNotExist:\n logger.error(u\"pipeline finished handler get taskflow error, pipeline_instance_id=%s\" % instance.id)\n return\n if taskflow.current_flow != 'finished':\n taskflow.current_flow = 'finished'\n taskflow.save()\n taskflow_finished.send(sender=taskflow, username=taskflow.pipeline_instance.executor)\n\n\ndef taskflow_node_failed_handler(sender, pipeline_id, pipeline_activity_id, **kwargs):\n try:\n taskflow = TaskFlowInstance.objects.get(pipeline_instance__instance_id=pipeline_id)\n except TaskFlowInstance.DoesNotExist:\n logger.error(u\"pipeline finished handler get taskflow error, pipeline_instance_id=%s\" % pipeline_id)\n return\n\n try:\n activity_name = taskflow.get_act_web_info(pipeline_activity_id)['name']\n send_task_flow_message(taskflow, ATOM_FAILED, activity_name)\n except Exception as e:\n logger.error('taskflow_node_failed_handler[taskflow_id=%s] send message error: %s' % (taskflow.id, e))\n return\n\n\n@receiver(taskflow_finished)\ndef taskflow_finished_handler(sender, username, **kwargs):\n try:\n taskflow = sender\n send_task_flow_message(taskflow, TASK_FINISHED)\n except Exception as e:\n logger.error('taskflow_finished_handler[taskflow_id=%s] send message error: %s' % (taskflow.id, e))\n return\n","sub_path":"gcloud/taskflow3/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"204854892","text":"# coding: utf-8\n\n\"\"\"\n Penguin Statistics - REST APIs\n\n Backend APIs for Arknights drop rate statistics website 'Penguin Statistics': https://penguin-stats.io/ # noqa: E501\n\n OpenAPI spec version: 2.0.0\n Contact: alvissreimu@gmail.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Existence(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'close_time': 'int',\n 'exist': 'bool',\n 'open_time': 'int'\n }\n\n attribute_map = {\n 'close_time': 'closeTime',\n 'exist': 'exist',\n 'open_time': 'openTime'\n }\n\n def __init__(self, close_time=None, exist=None, open_time=None): # noqa: E501\n \"\"\"Existence - a model defined in Swagger\"\"\" # noqa: E501\n\n self._close_time = None\n self._exist = None\n self._open_time = None\n self.discriminator = None\n\n if close_time is not None:\n self.close_time = close_time\n if exist is not None:\n self.exist = exist\n if open_time is not None:\n self.open_time = open_time\n\n @property\n def close_time(self):\n \"\"\"Gets the close_time of this Existence. # noqa: E501\n\n\n :return: The close_time of this Existence. # noqa: E501\n :rtype: int\n \"\"\"\n return self._close_time\n\n @close_time.setter\n def close_time(self, close_time):\n \"\"\"Sets the close_time of this Existence.\n\n\n :param close_time: The close_time of this Existence. # noqa: E501\n :type: int\n \"\"\"\n\n self._close_time = close_time\n\n @property\n def exist(self):\n \"\"\"Gets the exist of this Existence. # noqa: E501\n\n\n :return: The exist of this Existence. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._exist\n\n @exist.setter\n def exist(self, exist):\n \"\"\"Sets the exist of this Existence.\n\n\n :param exist: The exist of this Existence. # noqa: E501\n :type: bool\n \"\"\"\n\n self._exist = exist\n\n @property\n def open_time(self):\n \"\"\"Gets the open_time of this Existence. # noqa: E501\n\n\n :return: The open_time of this Existence. # noqa: E501\n :rtype: int\n \"\"\"\n return self._open_time\n\n @open_time.setter\n def open_time(self, open_time):\n \"\"\"Sets the open_time of this Existence.\n\n\n :param open_time: The open_time of this Existence. # noqa: E501\n :type: int\n \"\"\"\n\n self._open_time = open_time\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(Existence, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Existence):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"vendor/penguin_client/penguin_client/models/existence.py","file_name":"existence.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"471207413","text":"from ctypes import *\n\nclass Converter:\n\n @staticmethod\n def floatToBytes(bigendian, value):\n # initialise return data\n data = [0,0,0,0]\n\n # pointer to float value\n ptr = pointer(c_float(value))\n \n # cast to int pointer\n ip = cast(ptr, POINTER(c_int))\n \n # retrieve integer value\n intvalue = ip.contents.value\n\n if bigendian:\n data[0] = (intvalue & 0xFF000000) >> 24\n data[1] = (intvalue & 0x00FF0000) >> 16\n data[2] = (intvalue & 0x0000FF00) >> 8\n data[3] = (intvalue & 0x000000FF)\n else:\n data[3] = (intvalue & 0xFF000000) >> 24\n data[2] = (intvalue & 0x00FF0000) >> 16\n data[1] = (intvalue & 0x0000FF00) >> 8\n data[0] = (intvalue & 0x000000FF)\n\n return data\n\n\n @staticmethod\n def bytesToFloat(bigendian, datain):\n\n if bigendian:\n intvalue = datain[0] << 24\n intvalue += datain[1] << 16\n intvalue += datain[2] << 8\n intvalue += datain[3]\n else:\n intvalue = datain[0]\n intvalue += datain[1] << 8\n intvalue += datain[2] << 16\n intvalue += datain[3] << 24\n \n # pointer to integer value\n ptr = pointer(c_int(intvalue))\n \n # cast to float pointer\n fp = cast(ptr, POINTER(c_float))\n \n # return float value\n return fp.contents.value\n\n\n\n\n","sub_path":"SCD30_Modbus/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"61568048","text":"import os\nimport random\nimport cv2\n\nvideo_path = r'D:\\fight-tsn-tsm\\tools\\video'\nframes_path = r'D:\\fight-tsn-tsm\\tools\\frames'\nsplits_path = r'D:\\fight-tsn-tsm\\tools\\splits'\n\ntrain_data = []\nval_data = []\ntest_data = []\n\nfor sub_dir in os.listdir(video_path):\n frames_sub_dir = os.path.join(frames_path, sub_dir)\n print(frames_sub_dir)\n if not os.path.exists(frames_sub_dir):\n os.mkdir(frames_sub_dir)\n\n # 制作标签\n tag_list = []\n video_sub_dir = os.path.join(video_path, sub_dir)\n for filename in os.listdir(video_sub_dir):\n name = filename.split(\".\")[0]\n tag = sub_dir + \",\" + name\n tag_list.append(tag)\n\n video_last_path = os.path.join(video_sub_dir, filename)\n frames_last_path = os.path.join(frames_sub_dir, name)\n if not os.path.exists(frames_last_path):\n os.mkdir(frames_last_path)\n print(video_last_path)\n print(frames_last_path)\n cap = cv2.VideoCapture(video_last_path)\n i_frame = 0\n while True:\n i_frame += 1\n flag, img = cap.read()\n if not flag:\n break\n # cv2.imshow('frame', img)\n print(os.path.join(frames_last_path, str(i_frame).zfill(6) + \".jpg\"))\n cv2.imwrite(os.path.join(frames_last_path, str(i_frame).zfill(6) + \".jpg\"), img)\n # cv2.waitKey(500)\n cap.release()\n cv2.destroyAllWindows()\n\n # 打乱顺序\n random.shuffle(tag_list)\n random.shuffle(tag_list)\n random.shuffle(tag_list)\n\n # 划分训练集:验证集:测试集=7:1.5:1.5\n leng = len(tag_list)\n train_data.extend(tag_list[:int(leng * 0.7)])\n val_data.extend(tag_list[int(leng * 0.7):int(leng * 0.85)])\n test_data.extend(tag_list[int(leng * 0.85):])\n\nprint(len(train_data), len(val_data), len(test_data))\n\nwith open(os.path.join(splits_path, 'train.csv'), mode='w') as train_file:\n train_file.write('label,name\\n')\n for e in train_data:\n train_file.write(e)\n train_file.write('\\n')\n train_file.close()\nwith open(os.path.join(splits_path, 'val.csv'), mode='w') as val_file:\n val_file.write('label,name\\n')\n for e in val_data:\n val_file.write(e)\n val_file.write('\\n')\n val_file.close()\nwith open(os.path.join(splits_path, 'test.csv'), mode='w') as test_file:\n test_file.write('label,name\\n')\n for e in test_data:\n test_file.write(e)\n test_file.write('\\n')\n test_file.close()\n","sub_path":"tools/gen_sample.py","file_name":"gen_sample.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"282550224","text":"import time\nimport unittest\n\nfrom RLBotServer import start_server\nfrom backend.tasks.celery_tasks import parse_replay_task\nfrom tests.utils.killable_thread import KillableThread\nfrom tests.utils.location_utils import get_test_folder\nfrom tests.utils.replay_utils import write_files_to_disk, get_test_file, clear_dir\n\nLOCAL_URL = 'http://localhost:8000'\n\n\nclass HeatmapTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.thread = KillableThread(target=start_server)\n cls.thread.daemon = True\n cls.thread.start()\n print('waiting for a bit')\n time.sleep(2)\n print('done waiting')\n write_files_to_disk(\n ['https://cdn.discordapp.com/attachments/493849514680254468/501630263881760798/OCE_RLCS_7_CARS.replay'])\n result = parse_replay_task.apply(args=(get_test_file('OCE_RLCS_7_CARS.replay'), False, get_test_folder(), True),\n throw=True).get()\n #\n # def test_heatmaps(self):\n # r = requests.get(LOCAL_URL + '/api/replay/5699EF4011E8B3E248B0878371BE58A5/heatmaps', timeout=30)\n # r.raise_for_status()\n # self.assertEqual(r.status_code, 200)\n\n @classmethod\n def tearDownClass(cls) -> None:\n clear_dir()\n try:\n cls.thread.terminate()\n except:\n pass\n cls.thread.join()\n","sub_path":"tests/integration_tests/heatmaps_test.py","file_name":"heatmaps_test.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"81082825","text":"import numpy as np\nimport astropy.units as au\nimport astropy.stats as stats\nfrom astropy.io import fits\nfrom spectral_cube import SpectralCube\nfrom astropy.utils.console import ProgressBar\n\ndef get_cube(inputfile, x_units=(au.km / au.s), y_units=au.K):\n\n \"\"\"Get datacube\n\n Parameters\n ----------\n inputfile : str\n input filename\n x_units:\n units of x-axis\n y_units:\n units of y-axis\n\n Returns\n -------\n cube : spectral-cube object\n output cube in xunit and yunit\n \"\"\"\n\n cube = SpectralCube.read(inputfile, format = 'fits', unit = y_units, beam_threshold = 0.05)\n cube = cube.with_spectral_unit(x_units, velocity_convention='radio')\n cube.beam_threshold = 0.5\n cube.allow_huge_operations=True\n\n if cube.unit == \"Jy / beam\":\n cube = cube.to(au.K)\n\n return cube\n\ndef get_rms(cube, rms_velocities, outputfile=''):\n\n \"\"\"Get RMS map from a given cube\n\n Parameters\n ----------\n cube : spectral cube object\n Input cube\n rms_velocities : list of velocities used to return the rms - unitless\n List of rms values - e.g [[20,30],[50,60]]\n outputfile : string (optional)\n Output filename\n\n Returns\n -------\n rms_map : fits.PrimaryHDU object\n map of rms values\n \"\"\"\n\n\n count = 0\n rms_arr = np.empty([len(rms_velocities), cube.shape[1], cube.shape[2]]) * np.nan\n\n for rms_velocity in rms_velocities:\n\n rms_velocity = rms_velocity * (au.km / au.s)\n rms_cube = cube.spectral_slab(rms_velocity[0], rms_velocity[1])\n\n rms_arr[count, :, :] = np.nanstd(rms_cube, axis=0)\n# rms_arr[count, :, :] = np.sqrt(np.nansum(rms_cube**2, axis=0) / len(rms_cube)) #RMS CALC\n #MAD -> used incase some emission is incl. in rms\n # rms_arr[count, :, :] = stats.mad_std(rms_cube, axis=0)\n\n count += 1\n\n rms_map = np.nanmean(rms_arr, axis = 0)\n\n header = cube.header\n del header['*3']\n del header['PV1_*']\n header['WCSAXES'] = 2\n rms_map = fits.PrimaryHDU(data=rms_map, header=header)\n\n if outputfile != '':\n rms_map.writeto(outputfile, overwrite = True)\n\n return rms_map\n\ndef get_threshmask(cube, thresh_map, thresh=0):\n\n \"\"\"Set a given threshold map as mask to cube (e.g. for rms)\n\n Parameters\n ----------\n cube : spectral cube object (in Kelvin)\n Input cube\n thresh_map :\n Input map to provide threshold (e.g. RMS map)\n thresh : float (optional)\n Input threshold to create mask\n\n Returns\n -------\n mask : fits.PrimaryHDU object\n Output mask\n cube : fits.PrimaryHDU object\n Output masked cube\n \"\"\"\n\n mask = cube > ((thresh_map * au.K) * thresh)\n cube_masked = cube.with_mask(mask)\n\n return mask, cube_masked\n\ndef get_momentmaps(cube, mom_velocity='', outputfile='',\n moments=['mom0', 'max', 'mom1', 'sigma', 'mom9', 'mom9-mom1', 'variance', 'fwhm'],\n ):\n\n \"\"\"Get moment maps from a given (masked) cube\n\n Parameters\n ----------\n cube : spectral cube object\n Input cube\n outputfile : str (optional)\n Prefix of output file name - [outputfile]_[mom].fits\n mom_velocity : list (optional)\n list of velocities over which to deteremine moment maps - e.g. [40,50]\n moments : list (optional)\n list of moments to output *to file* - can be one or more of the following\n ['mom0', 'max', 'mom1', 'sigma', 'mom9', 'mom9-mom1', 'variance', 'fwhm']\n 'mom0': moment 0 or integrated intensity\n 'max': peak intensity moment map\n 'mom1': (intensity weighted) centroid velocity moment map\n 'sigma': (intensity weighted) line-width moment map\n 'mom9': velocity at peak intensity moment map\n 'mom9-mom1': \"velocity complexity\" - measure of asymmetry of velocity profile\n\n Returns\n -------\n mom_out : dict\n dictionary of output moment maps - will be one or more of the following\n ['mom0', 'max', 'mom1', 'sigma', 'mom9', 'mom9-mom1', 'variance', 'fwhm']\n\n to reduce run time, if 'mom9' or 'mom9-mom1' not chosen as output to file\n they will not be calculated and None value will be returned in dict.\n \"\"\"\n\n if mom_velocity!='':\n velo_min = mom_velocity[0]*au.km / au.s\n velo_max = mom_velocity[1]*au.km / au.s\n cube_slab = cube.spectral_slab(velo_min, velo_max)\n\n else:\n print('[INFO] No velocity range.')\n cube_slab = cube\n\n shape = cube_slab.shape\n\n if 'mom0' in moments:\n moment_0 = cube_slab.moment(order=0, axis=0)\n else:\n moment_0 = None\n\n if 'max' in moments:\n maximum = cube_slab.max(axis = 0)\n else:\n maximum = None\n\n if 'mom1' in moments:\n moment_1 = cube_slab.moment(order=1, axis=0)\n else:\n moment_1 = None\n\n if 'sigma' in moments:\n sigma_map = cube_slab.linewidth_sigma()\n else:\n sigma_map = None\n\n if 'variance' in moments:\n variance_map = cube_slab.moment(order=2, axis=0)\n else:\n variance_map = None\n\n if 'fwhm' in moments:\n fwhm_map = cube_slab.linewidth_fwhm()\n else:\n fwhm_map = None\n\n # moment_0 = cube_slab.moment(order=0, axis=0)\n # maximum = cube_slab.max(axis = 0)\n # moment_1 = cube_slab.moment(order=1, axis=0)\n # sigma_map = cube_slab.linewidth_sigma()\n # variance_map = cube_slab.moment(order=2, axis=0)\n # fwhm_map = cube_slab.linewidth_fwhm()\n # moment_9 = None\n # velo_complexity = None\n\n if 'mom9' in moments:\n\n print('[INFO] Creating mom9 and velo_complexity - make take a while.')\n\n moment_9 = np.empty([shape[1], shape[2]]) * np.nan\n moment_9_ID = cube_slab.argmax(axis=0)\n spectral_axis = cube_slab.spectral_axis\n\n for velo in range(1, len(spectral_axis)):\n for x in range(shape[1]):\n for y in range(shape[2]):\n\n if moment_9_ID[x,y] == 0:\n moment_9[x,y] = np.nan\n else:\n moment_9[x,y] = spectral_axis[moment_9_ID[x,y]].value\n\n velo_complexity = np.absolute(np.asarray(moment_1) - np.asarray(moment_9))\n\n moment_9 = moment_9 *au.km/au.s\n velo_complexity = velo_complexity *au.km/au.s\n\n moment_9_hdu = fits.PrimaryHDU(moment_9.value, moment_1.header)\n velo_complexity_hdu = fits.PrimaryHDU(velo_complexity.value, moment_1.header)\n\n else:\n moment_9_hdu = None\n velo_complexity_hdu = None\n\n mom_out = dict.fromkeys(moments)\n mom_out['mom0'] = moment_0\n mom_out['max'] = maximum\n mom_out['mom1'] = moment_1\n mom_out['sigma'] = sigma_map\n mom_out['mom9'] = moment_9_hdu\n mom_out['mom9-mom1'] = velo_complexity_hdu\n mom_out['variance'] = variance_map\n mom_out['fwhm'] = fwhm_map\n\n if outputfile!='':\n if 'mom0' in moments:\n moment_0.write(outputfile+'_mom0.fits', overwrite=True)\n if 'max' in moments:\n maximum.write(outputfile+'_max.fits', overwrite=True)\n if 'mom1' in moments:\n moment_1.write(outputfile+'_mom1.fits', overwrite=True)\n if 'sigma' in moments:\n sigma_map.write(outputfile+'_sigma.fits', overwrite=True)\n if 'mom9' in moments:\n moment_9_hdu.writeto(outputfile+'_mom9.fits', overwrite=True)\n if 'mom9-mom1' in moments:\n velo_complexity.writeto(outputfile+'_mom9-mom1.fits', overwrite=True)\n if 'variance' in moments:\n variance_map.write(outputfile+'_variance.fits', overwrite=True)\n if 'fwhm' in moments:\n fwhm_map.write(outputfile+'_fwhm.fits', overwrite=True)\n\n return mom_out\n\ndef get_nchan(mask):\n\n \"\"\"Get map of number of channels along each pixel within a mask\n\n Parameters\n ----------\n mask : (2d) np.array\n Input mask\n\n Returns\n -------\n nchans : (2d) np.array\n Output map of number of channels\n \"\"\"\n\n arr1 = mask.include()\n arr2 = arr1 * 1\n nchan = np.sum(arr2, axis=0)\n\n return nchan\n\ndef get_nchanbool(data):\n \"\"\"Gets number of channels witin each LOS\"\"\"\n nchans = np.nansum(data*1, axis=0)\n return(nchans)\n\ndef get_mom0err(nchan, rms_map, velo_res):\n\n \"\"\"Get map of err on mom0\n sigma_W = rms * V_res * N_chan**0.5\n\n Parameters\n ----------\n nchan : (2d) np.array\n Input map of number of channels\n rms_map : fits hdu object\n Input map of rms (inc header for output hdu)\n velo_res : float\n Input velocity resolution (in kms-1 usally)\n\n Returns\n -------\n mom0err : fits hdu object\n Output map of err on mom0\n \"\"\"\n\n\n cdelt = np.absolute(velo_res)\n\n nchan_sqrt = np.sqrt(nchan)\n mom0err = rms_map.data * nchan_sqrt * velo_res\n\n id_nan = np.where(mom0err==0)\n mom0err[id_nan] = np.nan\n\n header = rms_map.header\n header['BUNIT'] = 'K km s-1'\n\n mom0err_hdu = fits.PrimaryHDU(mom0err, header)\n\n return mom0err_hdu\n","sub_path":"moments.py","file_name":"moments.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"419353292","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 16 15:33:49 2018\n\n@author: Thomas\n\"\"\"\n# This program may become outdated by Recent fight updater. \nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\n\noutput = []\n\ncurrentHistory = pd.read_csv('MMAFightHistory_4.csv')\n\nsherdogDir = 'http://www.sherdog.com/organizations/ProFC-1882' #Has all links on page\nsherdogDir2 = 'http://www.sherdog.com/organizations/M1-Global-72'\nsherdogDir3 = 'http://www.sherdog.com/organizations/Tsumada-Fighting-Championship-3636'\nsherdogDir4 = 'http://www.sherdog.com/organizations/Pancration-Atrium-Cup-3802'\n\nwebsites = [sherdogDir, sherdogDir2, sherdogDir3, sherdogDir4]\n\nfor j in websites:\n\ttime.sleep(3)\n\turl = requests.get(j)\n\tprint(j)\n\tsoup = BeautifulSoup(url.text,'html.parser')\n\tlinkParent = soup.find(id='events_list')\n\tlinkTable = linkParent.find_all(class_='event')\n\tlinkTable = linkTable[1]\n\tevenEvents = linkTable.find_all(class_='even')\n\toddEvents = linkTable.find_all(class_='odd')\n\tallEvents = oddEvents + evenEvents\n\t\n\tfor i in allEvents: \n\t\ttry:\n\t\t\thost = i.a #find link\n\t\t\tlink = host.get('href') #get link\n\t\t\t \n\t\t\tnewUrl = 'http://www.sherdog.com' + link\n\t\t\tprint(newUrl)\n\t\t\ttime.sleep(3)\n\t\t\tfightPage = requests.get(newUrl)\n\t\t\tfpSoup = BeautifulSoup(fightPage.text,'html.parser')\n\t\t\t\n\t\t\tmain1 = fpSoup.find(class_='fighter left_side')\n\t\t\tmain2 = fpSoup.find(class_='fighter right_side')\n\t\t\t\n\t\t\twinnerMain = main1.find(itemprop = 'name').text\n\t\t\tloserMain = main2.find(itemprop = 'name').text\n\t\t\n\t\t\tdate = ((fpSoup.find(class_='authors_info')).find(class_='date'))\n\t\t\tdate = date.text\n\t\t\t\n\t\t\tfightData = fpSoup.find_all(class_='fighter_result_data')\n\t\t\tsubCard = ([(x.text.split('\\n')[1],y.text.split('\\n')[1], date) for x,y in zip(fightData[0::2], fightData[1::2])])\n\t\t\t\n\t\t\tfor j in subCard:\n\t\t\t\t\toutput.append(j)\n\t\t\t\t\t\n\t\t\tfightOutcome = main1.text.split('\\n')[1]\n\t\t\toutput.append((winnerMain, loserMain, date))\n\t\n\t\texcept:\n\t\t\tprint('Error')\n\n\ndf = pd.DataFrame(output)\ndf.columns = ['Winner', 'Loser', 'Date']\ndf['Date'] = pd.to_datetime(df['Date'])\ncurrentHistory = pd.concat([currentHistory,df])\ncurrentHistory['Date'] = pd.to_datetime(currentHistory['Date'], format='%Y-%m-%d')\ncurrentHistory.sort_values('Date', inplace=True, ascending = True)\ncurrentHistory.to_csv('MMAFightHistory_4.csv', header = ['Winner','Loser', 'Date'],\n\t\t index = False)\n\nprint('Done')\n","sub_path":"IncludeStrikeForceFights.py","file_name":"IncludeStrikeForceFights.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"452930921","text":"# -*- coding: utf-8 -*-\r\n\"\"\" \r\n@date: Sun Jan 2 16:21:58 2022\r\n@author: rstreppa ( roberto.strepparava@gmail.com )\r\n@company: https://github.com/rstreppa\r\n@type: test\r\n@description: test file for script C:/Users/rober/OneDrive/Documents/Library/Programming/Data_Structures/LinkedList/linkedList.py\r\n\"\"\"\r\n\r\nfrom linkedList import Node, LinkedList, mergeTwoLists, getDecimalValue\r\n\r\n\r\ndef test_LinkedList():\r\n l1 = LinkedList()\r\n l1.head = Node('Mon')\r\n e2 = Node('Tue')\r\n e3 = Node('Wed')\r\n l1.head.next = e2 # link first Node to second Node\r\n e2.next = e3 # link secodn node to third Node\r\n return l1\r\n \r\n\r\ndef main():\r\n print('###################')\r\n l = test_LinkedList() \r\n print(l)\r\n \r\n print('###################')\r\n l.printList()\r\n \r\n print('###################') \r\n l.push('Sun')\r\n l.printList()\r\n \r\n print('###################')\r\n prev = l.head.next.next # Tue\r\n l.insert(prev, 'TueEvening')\r\n l.printList()\r\n \r\n print('###################')\r\n l.insertAt( 3 , 'TueNight' )\r\n l.printList()\r\n \r\n print('###################')\r\n l.append( 'Thur' )\r\n l.printList()\r\n \r\n print('###################')\r\n l.deleteKey( 'Sun' )\r\n l.printList()\r\n \r\n print('###################')\r\n l.deleteKey( 'TueEvening' )\r\n l.printList()\r\n \r\n print('###################')\r\n l.deleteAt( 0 )\r\n l.printList()\r\n \r\n print('###################')\r\n l.deleteAt( 2 )\r\n l.printList()\r\n \r\n print('###################')\r\n l.deleteAt( 20 )\r\n l.printList()\r\n\r\n print('###################')\r\n print( l.length() )\r\n\r\n print('###################')\r\n l = test_LinkedList()\r\n l.push('Sun')\r\n l.append( 'Thur' )\r\n l.swap( 'Sun', 'Thur' )\r\n l.printList()\r\n l.swap( 'Sun', 'Tue' )\r\n l.printList()\r\n \r\n print('###################')\r\n l = test_LinkedList()\r\n l.push('Sun')\r\n l.append( 'Thur' )\r\n l.printList()\r\n l.reverse()\r\n l.printList()\r\n \r\n print('###################')\r\n llist = LinkedList()\r\n llist.push(20)\r\n llist.push(4)\r\n llist.push(15)\r\n llist.push(10) \r\n # Create a loop for testing\r\n llist.head.next.next.next.next = llist.head \r\n \r\n if( llist.detectLoop() ):\r\n print(\"Loop found\")\r\n else:\r\n print(\"No Loop \")\r\n \r\n if( l.detectLoop() ):\r\n print(\"Loop found\")\r\n else:\r\n print(\"No Loop \")\r\n \r\n print('###################')\r\n if( llist.detectloopFloyd() ):\r\n print(\"Loop found\")\r\n else:\r\n print(\"No Loop \")\r\n \r\n if( l.detectloopFloyd() ):\r\n print(\"Loop found\")\r\n else:\r\n print(\"No Loop \")\r\n \r\n print('###################')\r\n l.rotate(3)\r\n l.printList()\r\n print('###################')\r\n l.rotate(2)\r\n l.printList()\r\n print('#### hasCycle #########################')\r\n llist = LinkedList()\r\n llist.push(20)\r\n llist.push(4)\r\n llist.push(15)\r\n llist.push(10) \r\n # Create a loop for testing\r\n llist.head.next.next.next.next = llist.head \r\n print(llist.hasCycle())\r\n print(llist.hasCycle2())\r\n print('#### middleNode #########################')\r\n l = LinkedList()\r\n l.push(5)\r\n l.push(4) \r\n l.push(3)\r\n l.push(2)\r\n l.push(1)\r\n print(l.middleNode().data)\r\n g = LinkedList()\r\n g.push(6)\r\n g.push(5) \r\n g.push(4)\r\n g.push(3)\r\n g.push(2)\r\n g.push(1)\r\n print(g.middleNode().data)\r\n print('#### isPalindrome #########################')\r\n l = LinkedList()\r\n l.push(1)\r\n l.push(2) \r\n l.push(2)\r\n l.push(1)\r\n print( l.isPalindrome() )\r\n g = LinkedList()\r\n g.push(2)\r\n g.push(1)\r\n print( g.isPalindrome() )\r\n h = LinkedList()\r\n h.push(1)\r\n h.push(2) \r\n h.push(3)\r\n h.push(2)\r\n h.push(1)\r\n print( h.isPalindrome() )\r\n print('#### removeElements #########################')\r\n l = LinkedList()\r\n for data in [1,2,6,3,4,5,6][::-1]:\r\n l.push(data)\r\n l.removeElements(6)\r\n l.printList()\r\n g = LinkedList()\r\n for data in [][::-1]:\r\n g.push(data)\r\n g.removeElements(1)\r\n g.printList()\r\n h = LinkedList()\r\n for data in [7,7,7,7][::-1]:\r\n h.push(data)\r\n h.removeElements(7)\r\n h.printList()\r\n print('#### deleteDuplicates #########################')\r\n l = LinkedList()\r\n for data in [1,1,2][::-1]:\r\n l.push(data)\r\n l.deleteDuplicates()\r\n l.printList()\r\n g = LinkedList()\r\n for data in [1,1,2,3,3][::-1]:\r\n g.push(data)\r\n g.deleteDuplicates()\r\n g.printList()\r\n print('#### mergeTwoLists #########################')\r\n l1 = LinkedList()\r\n for data in [1,2,4][::-1]:\r\n l1.push(data)\r\n l2 = LinkedList()\r\n for data in [1,3,4][::-1]:\r\n l2.push(data)\r\n head = mergeTwoLists(l1.head, l2.head)\r\n l3 = LinkedList()\r\n l3.head = head\r\n l3.printList()\r\n\r\n l1 = LinkedList()\r\n for data in [][::-1]:\r\n l1.push(data)\r\n l2 = LinkedList()\r\n for data in [][::-1]:\r\n l2.push(data)\r\n head = mergeTwoLists(l1.head, l2.head)\r\n l3 = LinkedList()\r\n l3.head = head\r\n l3.printList()\r\n \r\n l1 = LinkedList()\r\n for data in [][::-1]:\r\n l1.push(data)\r\n l2 = LinkedList()\r\n for data in [0][::-1]:\r\n l2.push(data)\r\n head = mergeTwoLists(l1.head, l2.head)\r\n l3 = LinkedList()\r\n l3.head = head\r\n l3.printList()\r\n print('#### getDecimalValue #########################')\r\n l = LinkedList()\r\n for data in [1,0,1][::-1]:\r\n l.push(data)\r\n print(getDecimalValue(l.head))\r\n l = LinkedList()\r\n for data in [0][::-1]:\r\n l.push(data)\r\n print(getDecimalValue(l.head))\r\n l = LinkedList()\r\n for data in [1,0,1,0][::-1]:\r\n l.push(data)\r\n print(getDecimalValue(l.head))\r\n ","sub_path":"DataStructures/test_linkedList.py","file_name":"test_linkedList.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"109703376","text":"#!/usr/bin/env python\n\nimport time\nimport pika\n\n# 用户认证\ncredentials = pika.PlainCredentials('rabbitmq', 'rabbitmq')\n\n# 以阻塞的方式连接到\"/\"下这个Vhost\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost',5672,'/',credentials))\nchannel = connection.channel()\n\n# 定义一个队列\nchannel.queue_declare(queue='hello')\n\ndef callback(ch, method, properties, body):\n # 消费者收到消息后,执行此回调\n print(\" [x] Received %r\" % body)\n time.sleep(1)\n\n# 从队列中拿取消息,指定回执函数并只要拿到队列的消息,就从队列中将此消息删除,不管业务有没有执行成功\nchannel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)\n# auto_ack=False,队列的消息不会删除,要手动回执\n\nprint(' [*] Waiting for messages. To exit press CTRL+C')\nchannel.start_consuming()\n# mq不允许重新定义(不同参数)一个已经存在的队列\n\n# 以python revc.py 来模拟启动消费者消费,从而处理真正的业务流程\n\n# 先多运行几个revc.py ,再启动python send.py(没有持久化消息和手动回执,所以要先监听任务). 生产者的消息会以轮询的方式来分配给消费者\n","sub_path":"Dockerfiles/mq/start/1/revc.py","file_name":"revc.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"39249976","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\ngnpy.core.service_sheet\n========================\n\nXLS parser that can be called to create a JSON request file in accordance with\nYang model for requesting path computation.\n\nSee: draft-ietf-teas-yang-path-computation-01.txt\n\"\"\"\n\nfrom sys import exit\ntry:\n from xlrd import open_workbook, XL_CELL_EMPTY\nexcept ModuleNotFoundError:\n exit('Required: `pip install xlrd`')\nfrom collections import namedtuple\nfrom logging import getLogger, basicConfig, CRITICAL, DEBUG, INFO\nfrom json import dumps\nfrom pathlib import Path\nfrom gnpy.core.equipment import load_equipment\nfrom gnpy.core.utils import db2lin, lin2db\n\nSERVICES_COLUMN = 11\n#EQPT_LIBRARY_FILENAME = Path(__file__).parent / 'eqpt_config.json'\n\nall_rows = lambda sheet, start=0: (sheet.row(x) for x in range(start, sheet.nrows))\nlogger = getLogger(__name__)\n\n# Type for input data\nclass Request(namedtuple('Request', 'request_id source destination trx_type mode \\\n spacing power nb_channel disjoint_from nodes_list is_loose')):\n def __new__(cls, request_id, source, destination, trx_type, mode , spacing , power , nb_channel , disjoint_from ='' , nodes_list = None, is_loose = ''):\n return super().__new__(cls, request_id, source, destination, trx_type, mode, spacing, power, nb_channel, disjoint_from, nodes_list, is_loose)\n\n# Type for output data: // from dutc\nclass Element:\n def __eq__(self, other):\n return type(self) == type(other) and self.uid == other.uid\n def __hash__(self):\n return hash((type(self), self.uid))\n\nclass Request_element(Element):\n def __init__(self,Request,eqpt_filename):\n # request_id is str\n # excel has automatic number formatting that adds .0 on integer values\n # the next lines recover the pure int value, assuming this .0 is unwanted\n if not isinstance(Request.request_id,str):\n value = str(int(Request.request_id))\n if value.endswith('.0'):\n value = value[:-2]\n self.request_id = value\n else:\n self.request_id = Request.request_id\n self.source = Request.source\n self.destination = Request.destination\n self.srctpid = f'trx {Request.source}'\n self.dsttpid = f'trx {Request.destination}'\n # test that trx_type belongs to eqpt_config.json\n # if not replace it with a default\n equipment = load_equipment(eqpt_filename)\n try :\n if equipment['Transceiver'][Request.trx_type]:\n self.trx_type = Request.trx_type\n if [mode for mode in equipment['Transceiver'][Request.trx_type].mode]:\n self.mode = Request.mode\n except KeyError:\n msg = f'could not find tsp : {Request.trx_type} with mode: {Request.mode} in eqpt library \\nComputation stopped.'\n #print(msg)\n logger.critical(msg)\n exit()\n # excel input are in GHz and dBm\n self.spacing = Request.spacing * 1e9\n self.power = db2lin(Request.power) * 1e-3\n self.nb_channel = int(Request.nb_channel)\n if not isinstance(Request.disjoint_from,str):\n value = str(int(Request.disjoint_from))\n if value.endswith('.0'):\n value = value[:-2]\n else:\n value = Request.disjoint_from\n self.disjoint_from = [n for n in value.split()]\n self.nodes_list = []\n if Request.nodes_list :\n self.nodes_list = Request.nodes_list.split(' | ')\n try :\n self.nodes_list.remove(self.source)\n msg = f'{self.source} removed from explicit path node-list'\n logger.info(msg)\n # print(msg)\n except ValueError:\n msg = f'{self.source} already removed from explicit path node-list'\n logger.info(msg)\n # print(msg)\n try :\n self.nodes_list.remove(self.destination)\n msg = f'{self.destination} removed from explicit path node-list'\n logger.info(msg)\n # print(msg)\n except ValueError:\n msg = f'{self.destination} already removed from explicit path node-list'\n logger.info(msg)\n # print(msg)\n\n self.loose = 'loose'\n if Request.is_loose == 'no' :\n self.loose = 'strict'\n\n uid = property(lambda self: repr(self))\n @property\n def pathrequest(self):\n return {\n 'request-id':self.request_id,\n 'source': self.source,\n 'destination': self.destination,\n 'src-tp-id': self.srctpid,\n 'dst-tp-id': self.dsttpid,\n 'path-constraints':{\n 'te-bandwidth': {\n 'technology': 'flexi-grid',\n 'trx_type' : self.trx_type,\n 'trx_mode' : self.mode,\n 'effective-freq-slot':[{'n': 'null','m': 'null'}] ,\n 'spacing' : self.spacing,\n 'max-nb-of-channel' : self.nb_channel,\n 'output-power' : self.power\n }\n },\n 'optimizations': {\n 'explicit-route-include-objects': [\n {\n 'index': self.nodes_list.index(node),\n 'unnumbered-hop':{\n 'node-id': f'{node}',\n 'link-tp-id': 'link-tp-id is not used',\n 'hop-type': 'loose',\n 'direction': 'direction is not used'\n },\n 'label-hop':{\n 'te-label': {\n 'generic': 'generic is not used',\n 'direction': 'direction is not used'\n }\n }\n }\n for node in self.nodes_list\n ]\n\n }\n }\n @property\n def pathsync(self):\n if self.disjoint_from :\n return {'synchonization-id':self.request_id,\n 'svec': {\n 'relaxable' : 'False',\n 'link-diverse': 'True',\n 'node-diverse': 'True',\n 'request-id-number': [self.request_id]+ [n for n in self.disjoint_from]\n }\n }\n # TO-DO: avoid multiple entries with same synchronisation vectors\n @property\n def json(self):\n return self.pathrequest , self.pathsync\n\ndef convert_service_sheet(input_filename, eqpt_filename, output_filename='', filter_region=[]):\n service = parse_excel(input_filename)\n req = [Request_element(n,eqpt_filename) for n in service]\n # dumps the output into a json file with name\n # split_filename = [input_filename[0:len(input_filename)-len(suffix_filename)] , suffix_filename[1:]]\n if output_filename=='':\n output_filename = f'{str(input_filename)[0:len(str(input_filename))-len(str(input_filename.suffixes[0]))]}_services.json'\n # for debug\n # print(json_filename)\n data = {\n 'path-request': [n.json[0] for n in req],\n 'synchronisation': [n.json[1] for n in req\n if n.json[1] is not None]\n }\n with open(output_filename, 'w') as f:\n f.write(dumps(data, indent=2))\n return data\n\n# to be used from dutc\ndef parse_row(row, fieldnames):\n return {f: r.value for f, r in zip(fieldnames, row[0:SERVICES_COLUMN])\n if r.ctype != XL_CELL_EMPTY}\n#\n\ndef parse_excel(input_filename):\n with open_workbook(input_filename) as wb:\n service_sheet = wb.sheet_by_name('Service')\n services = list(parse_service_sheet(service_sheet))\n return services\n\ndef parse_service_sheet(service_sheet):\n logger.info(f'Validating headers on {service_sheet.name!r}')\n header = [x.value.strip() for x in service_sheet.row(4)[0:SERVICES_COLUMN]]\n expected = ['route id', 'Source', 'Destination', 'TRX type', \\\n 'Mode', 'System: spacing', 'System: input power (dBm)', 'System: nb of channels',\\\n 'routing: disjoint from', 'routing: path', 'routing: is loose?']\n if header != expected:\n msg = f'Malformed header on Service sheet: {header} != {expected}'\n logger.critical(msg)\n raise ValueError(msg)\n\n service_fieldnames = 'request_id source destination trx_type mode spacing power nb_channel disjoint_from nodes_list is_loose'.split()\n # Important Note: it reads all colum on each row so that\n # it is not possible to write annotation in the excel sheet\n # outside the SERVICES_COLUMN ... TO BE IMPROVED\n # request_id should be unique for disjunction constraints (not used yet)\n for row in all_rows(service_sheet, start=5):\n yield Request(**parse_row(row[0:SERVICES_COLUMN], service_fieldnames))\n","sub_path":"gnpy/core/service_sheet.py","file_name":"service_sheet.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"538280785","text":"import math\r\nnum = float(input(\"Entre com um número:\\n\"))\r\nraiz = math.sqrt(num)\r\nprint(f'\\nA raiz quadrada de {num} é {raiz}\\n')\r\n\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nmodel = LinearRegression().fit(lx.reshape(-1, 1), ly)\r\nprint(('slope:', model.coef_))\r\n\r\nplt.scatter(lx, ly)\r\nplt.plot(lx, model.intercept_ + model.coef_ * lx, 'r')\r\nplt.show()","sub_path":"Exercício 03/outros/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"220245915","text":"from selenium import webdriver\nfrom time import sleep\ndriver = webdriver.Chrome()\n\ndriver.maximize_window()\ndriver.implicitly_wait(10)\n\ndriver.get(\"https://www.sqatools.in/2020/08/alerts.html\")\n\n\"\"\"\n# Handle Alert Box\ndriver.find_element_by_id(\"btnShowMsg\").click()\nalertobj = driver.switch_to.alert\nsleep(1)\nprint(alertobj.text)\nalertobj.accept()\n\"\"\"\n\n# Handle Confirm Box\n\"\"\"\ndriver.find_element_by_id(\"button\").click()\n\nalertobj1 = driver.switch_to.alert\nprint(alertobj1.text)\nsleep(1)\nalertobj1.accept()\n\nalert_msg = driver.find_element_by_id(\"demo\").text\nprint(alert_msg)\nassert alert_msg == \"You pressed OK!\"\n\n\nsleep(2)\n# Cancel box\ndriver.find_element_by_id(\"button\").click()\n\nalertobj11 = driver.switch_to.alert\nprint(alertobj1.text)\nsleep(1)\nalertobj11.dismiss()\n\nalert_msg1 = driver.find_element_by_id(\"demo\").text\nprint(alert_msg1)\nassert alert_msg1 == \"You pressed Cancel!\"\n\"\"\"\n\n\n\n# Prompt Box\ndriver.find_element_by_id(\"promptbtn\").click()\n\nprompt_alert = driver.switch_to.alert\n\nprint(prompt_alert.text)\nprompt_alert.send_keys(\"SQA Tools\")\nsleep(1)\nprompt_alert.accept()\n\nprompt_msg = driver.find_element_by_id(\"prompt\").text\n\nprint(prompt_msg)\nassert prompt_msg == \"Hello SQA Tools! How are you today?\"\n\ndriver.close()\n","sub_path":"BatchNov2020/Selenium_Code/HandleAlerts.py","file_name":"HandleAlerts.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"9155331","text":"import time\nimport queue as queuemodule\nimport sys\n\nfrom microscope.monitor.monitor import MonitorRunner\n\n\ndef batch(runner: MonitorRunner, timeout: int):\n start_time = time.time()\n while(runner.is_alive() and runner.close_queue.empty()\n and (start_time + timeout > time.time() or timeout == 0)):\n try:\n output = runner.data_queue.get(True, 1)\n except queuemodule.Empty:\n continue\n if (\"output\" in output):\n sys.stdout.write(output[\"output\"])\n","sub_path":"microscope/batch/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"10025940","text":"import numpy as np\nimport math\nimport time\nimport matplotlib.pyplot as plt\nfrom collections import deque\n\nif __name__ == \"__main__\":\n\n figsize = 8, 4\n figure, ax = plt.subplots(figsize=figsize)\n\n file1 = open(\"./ProbLeft-Q\", \"rb\")\n file2 = open(\"./ProbLeft-D-Q\", \"rb\")\n file3 = open(\"./ProbLeft-D-Q-twice\", \"rb\")\n file4 = open(\"./ProbLeft-D-Q-twice-average\", \"rb\")\n num_iter = 1000\n arr1 = np.load(file1)\n arr2 = np.load(file2)\n arr3 = np.load(file3)\n arr4 = np.load(file4)\n mean1 = np.mean(arr1,axis=1)\n var1 = np.sqrt(np.var(arr1,axis=1) / num_iter)\n mean2 = np.mean(arr2,axis=1)\n var2 = np.sqrt(np.var(arr2,axis=1) / num_iter)\n mean3 = np.mean(arr3,axis=1)\n var3 = np.sqrt(np.var(arr3,axis=1) / num_iter)\n mean4 = np.mean(arr4,axis=1)\n var4 = np.sqrt(np.var(arr4,axis=1) / num_iter)\n\n x=range(200)\n\n #ax.set_yscale('log')\n\n plt.errorbar(x, mean1, 2 * var1, fmt='r--', capsize=2.5, errorevery=10, markevery=10, label='Q')\n plt.errorbar(x, mean2, 2 * var2, fmt='b-o', capsize=2.5, markevery=10, errorevery=10, label='D-Q')\n plt.errorbar(x, mean3, 2 * var3, fmt='k-*', capsize=2.5, markevery=10, errorevery=10,\n label='D-Q with twice the step size')\n plt.errorbar(x, mean4, 2 * var4, fmt='g-x', capsize=2.5, markevery=10, errorevery=10,\n label='D-Q avg with twice the step size')\n\n handles, labels = plt.gca().get_legend_handles_labels()\n legend = plt.legend(loc='best',\n ncol=1, fancybox=True, shadow=True, prop={'size': 16})\n legend.get_title().set_fontname('Times New Roman')\n legend.get_title().set_fontweight('black')\n\n plt.tick_params(labelsize=20)\n labels = ax.get_xticklabels() + ax.get_yticklabels()\n [label.set_fontname('Times New Roman') for label in labels]\n\n font2 = {'family': 'Times New Roman',\n 'weight': 'black',\n 'size': 20,\n }\n plt.xlabel('Number of Episodes', font2)\n plt.ylabel('Probability of a left action', font2)\n plt.tight_layout()\n plt.savefig('./Sutton-Barto(nn).pdf', dpi=600, bbox_inches='tight')\n plt.close()\n","sub_path":"Bias(nn)/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"292577583","text":"# C - Green Bin\n# https://atcoder.jp/contests/abc137/tasks/abc137_c\n# 考えはあっているが、実装ができなかった。。\n# collectionsライブラリを使った。\n# str.joinを使った\n# sum(x*(x-1)//2)の部分がまだよくわかっていない\n\n# 15:20 -16:08 giveup\n# 21:45 -22:33 review\nfrom collections import Counter\n\n# 3\n# acornistnt\n# peanutbomb\n# constraint\nn = int(input())\ns = [''.join(sorted(input())) for _ in range(n)]\n# s is ['acinnorstt', 'abbemnoptu', 'acinnorstt']\ncounter = Counter(s)\n# counter is Counter({'acinnorstt': 2, 'abbemnoptu': 1})\n# counter.values() is dict_values([3, 2])\nans = sum(x*(x-1)//2 for x in counter.values())\nprint(ans)","sub_path":"abc_py/abc137/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"45565361","text":"# coding = utf-8\n\"\"\"\n@Author: Felix\n@Time: 2019/9/14 18:25\n@Software: PyCharm\n@File: pra1.py\n@Version: V1.0\n@Desc: 在屏幕上显示跑马灯文字\n\"\"\"\nimport os\nimport time\n\n\ndef Marquee_word():\n content = '古城西安人民欢迎您......'\n while True:\n # 清理屏幕上的输出\n os.system('cls') # 和这个函数作用相同os.system('clear')\n print(content)\n # 休眠200毫秒\n time.sleep(0.2)\n content = content[1:] + content[0]\n # content[1:]意思是输出第二个元素到最后一个元素。\n # 上面的结果再加上第一个元素,把这样的值赋给新的变量,然后第一个元素再到末尾\n # 这样保证了整体的字符串数量不变,只变了字符串元素中的次序,可以说很灵活地使用了字符串的性质\n # 及其所属操作:切片操作。\n\n\nif __name__ == '__main__':\n Marquee_word()\n","sub_path":"ONE-TEN/day7/pra1.py","file_name":"pra1.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"460383226","text":"#-*- coding: utf-8 -*-\nimport re\nimport urllib\nimport urllib2\nimport json\nimport web\nimport os\n\nurls = (\n '/','index',\n '/i/(.*),(.*),(.*),(.*)','sign_in',\t\t#sign in\n '/cs/(.*),(.*)','check_score',\t\t#check score\n '/ce/(.*),(.*)','check_exam',\n '/cp/(.*),(.*)','check_plan'\n)\n\nif __name__ == \"__main__\": \n\tapp = web.application(urls, globals())\n\tapp.run()\n\nclass index:\n def GET(self):\n return 'argu format:[i/cs/ics],xh,cookie,[password],[verify]'\n\nclass sign_in:\n def GET(self,xh,cookie,password,verify):\n handler = API(xh,cookie)\n handler.sign_in(verify,password)\n\nclass check_score:\n def GET(self,xh,cookie):\n handler = API(xh,cookie)\n return handler.check_score()\n\nclass check_exam:\n def GET(self,xh,cookie):\n handler = API(xh,cookie)\n return handler.check_exam()\n\nclass check_plan:\n def GET(self,xh,cookie):\n handler = API(xh,cookie)\n return handler.check_schedule()\n\nclass API:\n index_url = 'http://jwgldx.gdut.edu.cn/default2.aspx'\n score_url = 'http://jwgldx.gdut.edu.cn/xscj.aspx?xh='\n exam_url = 'http://jwgldx.gdut.edu.cn/xskscx.aspx?xh='\n schedule_url = 'http://jwgldx.gdut.edu.cn/xskbcx.aspx?xh='\n ID = ''\n head = {}\n def __init__(self,xh,cookie):\n self.ID = xh\n Cookie = 'ASP.NET_SessionId=' + cookie\n self.head = { 'Accept':'*/*','Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Referer':'http://jwgldx.gdut.edu.cn/', 'Cookie':Cookie,'User-Agent':'zfquery/1.3.1.2 CFNetwork/711.3.18 Darwin/14.0.0'}\n self.score_url = self.score_url + xh\n self.exam_url = self.exam_url + xh\n self.schedule_url = self.schedule_url + xh\n\n def sign_in(self,verify,password):\n html = urllib.urlopen(self.index_url).read()\n _VIEWSTATE = self.get_VIEWSTATE(html)\n post_date = self.in_post(_VIEWSTATE,self.ID,password,verify)\n myRequest = urllib2.Request(self.index_url,post_date,self.head)\n response = urllib2.urlopen(myRequest)\n\n def check_score(self):\n myRequest = urllib2.Request(self.score_url,None,self.head)\n html = urllib2.urlopen(myRequest).read()\n _VIEWSTATE = self.get_VIEWSTATE(html)\n post_date = self.score_post(_VIEWSTATE)\n MyRequest= urllib2.Request(self.score_url,post_date,self.head)\n response = urllib2.urlopen(MyRequest).read()\n #result = unicode(response, \"gb2312\").encode(\"utf8\")\n reg = re.compile(r'<td>([^<]*)</td>')\n data_list = re.findall(reg,response) #response result\n data_list = data_list[9:len(data_list)-4]\n json_pre = []\n data_len = len(data_list)-1\n for i in range(0,data_len,9):\n json_pre.append([data_list[i+1],data_list[i+3],data_list[i+7]])\n data_json = json.dumps(json_pre,ensure_ascii=False)\n return data_json\n\n def check_exam(self):\n MyRequest= urllib2.Request(self.exam_url,None,self.head)\n response = urllib2.urlopen(MyRequest).read()\n __VIEWSTATE = self.get_VIEWSTATE(response)\n #result = unicode(response, \"gb2312\").encode(\"utf8\")\n data = {}\n option = self.get_selected(response)\n first_data = self.withdraw_data(response)\n data[option[0][0]]={'1':first_data}\n\n for xnd in option[1]:\n if xnd == option[0][0]:\n post_data = self.exam_post(__VIEWSTATE,xnd,'2')\n MyRequest= urllib2.Request(self.exam_url,post_data,self.head)\n response = urllib2.urlopen(MyRequest).read()\n data[xnd]['2'] = self.withdraw_data(response)\n else:\n data[xnd]={}\n for xqd in ['1','2']:\n post_data = self.exam_post(__VIEWSTATE,xnd,xqd)\n MyRequest= urllib2.Request(self.exam_url,post_data,self.head)\n response = urllib2.urlopen(MyRequest).read()\n #data_debug = self.withdraw_data(response)\n #data[xnd]={xqd:data_debug}\n data[xnd][xqd] = self.withdraw_data(response)\n\n data_json = json.dumps(data,ensure_ascii=False)\n return data_json\n\n def check_schedule(self): #TODO:debug\n MyRequest= urllib2.Request(self.schedule_url,None,self.head)\n response = urllib2.urlopen(MyRequest).read()\n __VIEWSTATE = self.get_VIEWSTATE(response)\n #result = unicode(response, \"gb2312\").encode(\"utf8\")\n data = {}\n option = self.get_selected(response)\n first_data = self.withdraw_schedule(response)\n data[option[0][0]]={'1':first_data}\n for xnd in option[1]:\n if xnd == option[0][0]:\n post_data = self.exam_post(__VIEWSTATE,xnd,'2')\n MyRequest= urllib2.Request(self.exam_url,post_data,self.head)\n response = urllib2.urlopen(MyRequest).read()\n data[xnd]['2'] = self.withdraw_schedule(response)\n else:\n data[xnd]={}\n for xqd in ['1','2']:\n post_data = self.exam_post(__VIEWSTATE,xnd,xqd)\n MyRequest= urllib2.Request(self.schedule_url,post_data,self.head)\n response = urllib2.urlopen(MyRequest).read()\n #data_debug = self.withdraw_data(response)\n #data[xnd]={xqd:data_debug}\n data[xnd][xqd] = self.withdraw_schedule(response)\n data_json = json.dumps(data,ensure_ascii=False)\n return data_json\n\n def in_post(self,_VIEWSTATE,ID,Passwd,Verify):\n post_data = urllib.urlencode({'__VIEWSTATE':_VIEWSTATE,\n 'txtUserName':ID,\n 'TextBox2':Passwd,\n 'txtSecretCode':Verify,\n 'RadioButtonList1':'%D1%A7%C9%FA',\n 'Button1':'',\n 'lbLanguage':'',\n 'hidPdrs':'',\n 'hidsc':''})\n return post_data\n\n def score_post(self,_VIEWSTATE):\n data = urllib.urlencode({\n '__VIEWSTATE':_VIEWSTATE,\n 'ddlXN':'',\n 'ddlXQ':'',\n 'txtQSCJ':'0',\n 'txtZZCJ':'100',\n 'Button2':'%EF%BF%BD%EF%BF%BD%D0%A3%D1%A7%CF%B0%EF%BF%BD%C9%BC%EF%BF%BD%EF%BF%BD%EF%BF%BD%D1%AF'\n })\n return data\n\n def get_VIEWSTATE(self,html):\n reg = r'__VIEWSTATE\" value=\"(.*)\"'\n _VIEWSTATE = re.findall(re.compile(reg),html)\n return _VIEWSTATE[0]\n\n def get_selected(self,html):\n reg_selected = re.compile(r'selected\" value=\"(.*)\"')\n reg_option = re.compile((r'>(.*-.*)</option>'))\n selected_list = re.findall(reg_selected,html)\n option_list = re.findall(reg_option,html)\n option_dict = [[selected_list[0],selected_list[1]]]\n option = []\n for i in option_list:\n option.append(i)\n option_dict.append(option)\n return option_dict\n\n def exam_post(self,__VIEWSTATE,xnd,xqd):\n post_data = urllib.urlencode({\n '__EVENTARGUMENT':'',\n '__VIEWSTATE':__VIEWSTATE,\n 'xnd':xnd,\n 'xqd':xqd\n })\n return post_data\n\n def withdraw_data(self,response):\n reg = re.compile(r'<td>([^<]*)</td>')\n data_list = re.findall(reg,response)\n data_list = data_list[8:len(data_list)]\n data = []\n data_len = len(data_list)-1\n for i in range(0,data_len,8):\n data.append([data_list[i+1],data_list[i+3],data_list[i+4],data_list[i+5],data_list[i+6]])\n return data\n\n def withdraw_schedule(self,response):\t\t\t#There is some bug with reg\n reg1 = re.compile(r'(rowspan=\"[2-3]\".*>.*</td>)')\n reg2 = re.compile(r'\">(.*?)</td>')\n reg3 = re.compile(r'>([^&]*?)<')\n\n rough_list = re.findall(reg1,response)\n i = 1\n schedule_data = {1:{},2:{},3:{},4:{},5:{},6:{},7:{}}\n for rough in rough_list:\n col_list = re.findall(reg2,rough)\n if (i == 5 and len(col_list) > 0):\t\t\t#2015-2016 key error:8\n del col_list[0]\n j = 1\n for col in col_list:\n subject_list = re.findall(reg3,col)\n schedule_data[j][i] = subject_list\n j = j + 1\n i = i + 1\n return schedule_data\n","sub_path":"test2_main.py","file_name":"test2_main.py","file_ext":"py","file_size_in_byte":8462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"562433661","text":"\"\"\"\nCalculate ETag values for API resources.\n\"\"\"\nimport functools\nimport hashlib\n\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import models\nfrom django.http import Http404, HttpRequest\n\nfrom djangorestframework_camel_case.render import CamelCaseJSONRenderer\nfrom rest_framework import serializers\nfrom rest_framework.request import Request\nfrom rest_framework.settings import api_settings\n\nfrom ..serializers import GegevensGroepSerializer\nfrom ..utils import get_resource_for_path, get_subclasses\n\n\nclass StaticRequest(HttpRequest):\n def get_host(self) -> str:\n site = Site.objects.get_current()\n return site.domain\n\n def _get_scheme(self) -> str:\n return \"https\" if settings.IS_HTTPS else \"http\"\n\n\ndef calculate_etag(instance: models.Model) -> str:\n \"\"\"\n Calculate the MD5 hash of a resource representation in the API.\n\n The serializer for the model class is retrieved, and then used to construct\n the representation of the instance. Then, the representation is rendered\n to camelCase JSON, after which the MD5 hash is calculated of this result.\n \"\"\"\n model_class = type(instance)\n serializer_class = _get_serializer_for_models()[model_class]\n\n # build a dummy request with the configured domain, since we're doing STRONG\n # comparison. Required as context for hyperlinked serializers\n request = Request(StaticRequest())\n request.version = api_settings.DEFAULT_VERSION\n request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS()\n\n serializer = serializer_class(instance=instance, context={\"request\": request})\n\n # render the output to json, which is used as hash input\n renderer = CamelCaseJSONRenderer()\n rendered = renderer.render(serializer.data, \"application/json\")\n\n # calculate md5 hash\n return hashlib.md5(rendered).hexdigest()\n\n\ndef etag_func(request: HttpRequest, etag_field: str = \"_etag\", **view_kwargs):\n try:\n obj = get_resource_for_path(request.path)\n except ObjectDoesNotExist:\n raise Http404\n etag_value = getattr(obj, etag_field)\n if not etag_value: # calculate missing value and store it\n etag_value = obj.calculate_etag_value()\n return etag_value\n\n\n@functools.lru_cache(maxsize=None)\ndef _get_serializer_for_models():\n \"\"\"\n Map models to the serializer to use.\n\n If multiple serializers exist for a model, it must be explicitly defined.\n \"\"\"\n model_serializers = {}\n for serializer_class in get_subclasses(serializers.ModelSerializer):\n if not hasattr(serializer_class, \"Meta\"):\n continue\n\n if issubclass(serializer_class, GegevensGroepSerializer):\n continue\n\n model = serializer_class.Meta.model\n if model in model_serializers:\n continue\n\n model_serializers[model] = serializer_class\n return model_serializers\n","sub_path":"vng_api_common/caching/etags.py","file_name":"etags.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"609151752","text":"from django import forms\nfrom .models import UserModel, CocktailModel\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = UserModel\n fields = \"__all__\"\n\n def clean_username(self):\n usernameData = self.cleaned_data[\"username\"]\n\n validateData = str(usernameData).lower()\n if \"poop\" in validateData:\n raise forms.ValidationError(\"Please don't use poop...\")\n\n return usernameData\n\n def clean_age(self):\n ageData = self.cleaned_data[\"age\"]\n\n if ageData < 13:\n raise forms.ValidationError(\"Go back to Barney!!!!\")\n\n return ageData\n\n\nclass CocktailForm(forms.ModelForm):\n class Meta:\n model = CocktailModel\n fields = \"__all__\"\n # labels = {\"alcoholContent\": \"Alcohol Content (in %)\"}\n\n def clean_alcoholContent(self):\n boozeData = self.cleaned_data[\"alcoholContent\"]\n\n if boozeData<5:\n raise forms.ValidationError(\"Not enough!!\")\n\n if boozeData> 70:\n raise forms.ValidationError(\"It's too strong\")\n\n return boozeData\n","sub_path":"ValidationApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"205731256","text":"# file io\r\nfrom scipy.io import wavfile as wav\r\nfrom obspy import read\r\n\r\n# web resources\r\nfrom urllib.request import urlretrieve\r\n\r\n# filter narrowband sound\r\nfrom scipy.signal import medfilt\r\n\r\n# call detection\r\nfrom functools import reduce\r\nimport operator\r\n\r\n# specgram function\r\nfrom matplotlib import mlab\r\nimport numpy as np\r\n\r\n# helper functions\r\nfrom scripts.audiohelp import sub_avg, find_longest_sequence, group_consecutives\r\n\r\nimport warnings\r\n\r\n\r\nclass whaca:\r\n \r\n def __init__(self, db_thresh=10, time_thresh=0.5,\r\n width_thresh=1000, NFFT=512, window=None):\r\n '''\r\n Instantiate a new whaca class.\r\n\r\n Keyword arguments:\r\n db_thresh=10 : Intensity threshold for broadband noise reduction and\r\n call filtering. (DB)\r\n time_thresh=0.5 : Time duration threshold for call filtering. (seconds)\r\n width_thresh=1000 : Bandwidth threshold for broadband noise reduction. (Hz)\r\n NFFT=512 : Sample size for Fourier transform on spectrogram generation.\r\n Also roughly controls resolution of call detection.\r\n window=None : Window to be passed to Fourier transform function.\r\n\r\n '''\r\n # save threshold parameters\r\n self.db_thresh = db_thresh\r\n self.time_thresh = time_thresh\r\n self.width_thresh = width_thresh\r\n # save specgram parameters\r\n self.NFFT = NFFT\r\n self.window = window\r\n \r\n # file io\r\n \r\n def open_wav(self, f):\r\n '''Loads wav file data into class from the given file-like object or path, f.'''\r\n # call scipy module\r\n try:\r\n rate, data = wav.read(f)\r\n except ValueError:\r\n print(\"Cannot read wav. Maybe a bad url?\")\r\n\r\n rate, data = wav.read(f)\r\n if data.ndim != 1:\r\n warnings.warn(\"Only mono files are supported, using left channel.\")\r\n data = data[:, 0]\r\n self.rate = rate\r\n self.data = data\r\n \r\n def open_mseed(self, f):\r\n '''Loads mseed file data into class from the given file-like object or path, f.'''\r\n # TODO add support for multiple streams\r\n try:\r\n sound = read(f)[0]\r\n except ValueError:\r\n print(\"Cannot read mseed. Maybe a bad url?\")\r\n \r\n sound = read(f)[0]\r\n self.data = (sound.normalize() * (2 ** 31 - 1)).astype(\"int32\")\r\n self.rate = sound.stats.sampling_rate\r\n \r\n def open_url(self, url, ext):\r\n '''\r\n Loads data at specified url into class.\r\n\r\n Arguments:\r\n url: URL to be used.\r\n ext: Data type of the requested resource.\r\n Supported data types: 'wav', 'mseed'\r\n\r\n '''\r\n data_types = {\"wav\": self.open_wav,\r\n \"mseed\": self.open_mseed}\r\n # check if supported\r\n if ext in data_types.keys():\r\n f, headers = urlretrieve(url)\r\n data_types[ext](f)\r\n else:\r\n raise ValueError(ext + \" is not a valid file type!\")\r\n \r\n # audio processing functions\r\n \r\n def _bb_reduc(self, s, freq):\r\n '''\r\n Reduces broadband noise in the given spectrogram.\r\n\r\n Arguments:\r\n s: Spectrogram (2D numpy array) to be altered.\r\n freq: Frequency values corresponding to row of spectrogram.\r\n\r\n Returns:\r\n s: Altered spectrogram.\r\n\r\n '''\r\n # iterate along columns\r\n for i in range(0, np.ma.size(s, axis=1)):\r\n points = []\r\n for j, val in enumerate(s[:, i]):\r\n if val > self.db_thresh:\r\n points.append(j)\r\n long = find_longest_sequence(points)\r\n if np.absolute(freq[long[1]] - freq[long[0]]) > self.width_thresh:\r\n s[:, i] = np.zeros(len(s[:, i])) + np.min(s)\r\n return s\r\n \r\n def gen_spectro(self, process=True):\r\n \r\n s, f, t = mlab.specgram(self.data,\r\n NFFT=self.NFFT,\r\n Fs=self.rate,\r\n noverlap=self.NFFT // 2)\r\n '''\r\n Generates spectrogram from data loaded into class.\r\n\r\n Keyword Arguments:\r\n process=True : Whether to apply median filter, broadband reduction,\r\n and bin avg subtraction to spectrogram.\r\n\r\n Returns:\r\n s: Spectrogram produced from data.\r\n f: Frequency bins corresponding to rows of spectrogram.\r\n t: Timesteps corresponding to columns of spectrogram.\r\n '''\r\n # convert to db\r\n s = 10 * np.log10(s)\r\n s = np.flipud(s)\r\n if process:\r\n s = medfilt(s)\r\n s = self._bb_reduc(s, f)\r\n s = sub_avg(s)\r\n # restrict negative intensities\r\n s[s < 0] = 0\r\n return s, f, t\r\n \r\n def filter_sounds(self, spec, tstep):\r\n '''\r\n Filters spectrogram to only include potential whale calls.\r\n\r\n Arguments:\r\n spec: Spectrogram to be filtered.\r\n tstep: Difference in time between columns of spectrogram.\r\n\r\n Returns:\r\n spec: Filtered spectrogram.\r\n '''\r\n # drop values below threshold\r\n spec[spec < self.db_thresh] = 0\r\n # times containing valid intensities\r\n t = [col for col in range(0, np.ma.size(spec, axis=1))\r\n if np.nonzero(spec[:,col]) != []]\r\n # keep time groups if they meet duration threshold\r\n groups = [lis for lis in group_consecutives(t)\r\n if (len(lis) - 1) * tstep > self.time_thresh]\r\n # flatten list\r\n if groups != []:\r\n groups = reduce(operator.add, groups)\r\n # points not in groups need to be silenced\r\n silence = list(set(range(0, len(spec[0]))) - set(groups))\r\n spec[:, silence] = 0\r\n return spec\r\n \r\n # gets and sets\r\n \r\n def get_threshold_params(self):\r\n '''Returns dictionary of threshold parameters'''\r\n return {\"db_thresh\": self.db_thresh,\r\n \"time_thresh\": self.time_thresh,\r\n \"width_thresh\": self.width_thresh}\r\n \r\n def set_threshold_params(self, db_thresh=None, time_thresh=None,\r\n width_thresh=None):\r\n '''Set threshold parameters db_thresh, time_thresh, and width_thresh.'''\r\n if db_thresh:\r\n self.db_thresh = db_thresh\r\n if time_thresh:\r\n self.time_thresh = time_thresh\r\n if width_thresh:\r\n self.width_thresh = width_thresh\r\n \r\n def set_spectro_params(self, NFFT=None, window=None):\r\n '''Set spectrogram parameters NFFT and window.'''\r\n if NFFT:\r\n self.NFFT = NFFT\r\n if window:\r\n self.window = window\r\n \r\n def get_spectro_params(self):\r\n '''Returns dictioary of threshold parmeters.'''\r\n return {\"NFFT\": self.NFFT,\r\n \"window\": self.window}\r\n ","sub_path":"scripts/whaca.py","file_name":"whaca.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"594042821","text":"\nfrom acp.myforms import *\nfrom django.shortcuts import render_to_response\nfrom django.http.response import HttpResponse\npost_forms = { \n '/comment/add':TUserForm,\n# '/battery/active':DealBatteryActive,\n '/battery/sync':TBatteryInfoForm, \n# '/battery/setid':DealBatterySetid, \n '/battery/config':TBatteryconfigForm,\n '/battery/warn':TWarnForm,\n }\n\ndef process_post_form_view(request,path_info):\n if path_info in post_forms:\n# if path_info == '/comment/add':\n# aform = TUserForm()\n aform = post_forms[path_info]()\n# return HttpResponse(\"hello!!!\")\n return render_to_response('form_views.html',{'form':aform})\n ","sub_path":"acporacle/acp/formviews.py","file_name":"formviews.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"423199999","text":"#!/usr/bin/env python\nimport os, time, re, json, requests\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen, urlretrieve\nfrom sys import exit\n# from selenium import webdriver\n# from selenium.webdriver.chrome.options import Options\n# from selenium.webdriver.common.keys import Keys\nfrom web import login, read_creds, scroll, post_count, find_elements\n\ndef load_js(url):\n\n creds = read_creds()\n session = login(creds)\n loaded_page_source = scroll(session, url)\n\n return loaded_page_source\n\ndef dump(html, base_url, path):\n links = find_elements(html, base_url)\n dump_dir = path + \"/\" + base_url.split(\"/\")[3] + \"_dump\"\n os.makedirs(dump_dir)\n\n return links, dump_dir\n\ndef check_path(path):\n if os.path.exists(path):\n print(\"[x] File Exists | [!] Exiting...\")\n exit(0)\n else:\n return path\n\ndef parse_data(html):\n try:\n #print(\"[*] Parsing post data...\")\n soup = BeautifulSoup(html, 'html.parser')\n shared_data = soup.find('script', text=re.compile('window._sharedData'))\n json_raw = shared_data.text.split(' = ', 1)[1].rstrip(';')\n raw_data = json.loads(json_raw)\n base_data = raw_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']\n type_name = base_data['__typename']\n except KeyError:\n print(f\"[x] Cannot read post URL!\\n[?] URL may belong to a profile page.\")\n exit(0)\n else:\n return base_data, type_name\n\ndef get_graph_image(base_data, download_path):\n display_url, file_name = base_data['display_url'], base_data['taken_at_timestamp'] \n download_file_name = f\"{download_path}/{str(file_name)}.jpg\"\n print(f\"[*] Downloading {file_name} as {download_file_name}...\")\n urlretrieve(display_url, check_path(download_file_name))\n\ndef get_graph_video(base_data, download_path):\n video_url, file_name = base_data['video_url'], base_data['taken_at_timestamp']\n download_file_name = f\"{download_path}/{str(file_name)}.mp4\"\n print(f\"[*] Downloading {file_name} as {download_file_name}...\")\n urlretrieve(video_url, check_path(download_file_name))\n\ndef get_graph_sideCar(base_data, download_path):\n response = requests.get(f\"https://www.instagram.com/p/\" + base_data['shortcode'] + \"/?__a=1\").json()\n counter = 1\n\n for edge in response['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']:\n file_name = response['graphql']['shortcode_media']['taken_at_timestamp']\n download_file_name = f\"{download_path}/{str(file_name)}-{counter}\"\n is_video = edge['node']['is_video']\n\n if not is_video:\n display_url = edge['node']['display_url']\n download_file_name += \".jpg\"\n print(f\"[*] Downloading {file_name} as {download_file_name}...\")\n urlretrieve(display_url, check_path(download_file_name))\n else:\n video_url = edge['node']['video_url']\n download_file_name += \".mp4\"\n print(f\"[*] Downloading {file_name} as {download_file_name}...\")\n urlretrieve(video_url, check_path(download_file_name))\n counter += 1\n\n\n\n\n\n\n \n\n\n","sub_path":"scraping_poc/refactor/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"468450773","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(r, x):\n return x*r*(1 - x)\n \ndef g(r, x):\n return f(r, f(r, x))\n\ndef h(r, x):\n return f(r, f(r, f(r, x)))\n\ndef plot(r, ax, x0, fun, fun2, tangets, name):\n \n # plot web\n webx = np.zeros(1000)\n weby = np.zeros(1000)\n webx[0] = x0\n weby[0] = 0.0\n webx[1] = webx[0]\n weby[1] = fun2(r, webx[0])\n for i in range(2, len(webx), 2):\n webx[i] = weby[i-1]\n weby[i] = weby[i-1]\n webx[i+1] = webx[i]\n weby[i+1] = fun2(r, webx[i])\n ax.plot(webx, weby, \"-r\")\n\n # plot points and tangent lines\n if(tangets):\n x_n = np.zeros(10000)\n x_n[0] = x0\n for i in range(1, len(x_n)):\n x = x_n[i-1]\n x_n[i] = fun2(r, x)\n period = 0\n y = x_n[-1]\n for i in range(1, 65):\n yy = x_n[len(x_n)-1-i]\n rel_err = 1-(yy/y if (y>yy) else y/yy)\n if(rel_err < 1E-6):\n yy2 = x_n[len(x_n)-1-i*2]\n rel_err2 = 1-(yy2/y if (y>yy2) else y/yy2)\n if(rel_err2 < 1E-6):\n yy3 = x_n[len(x_n)-1-i*3]\n rel_err3 = 1-(yy3/y if (y>yy3) else y/yy3)\n if(rel_err3 < 1E-6):\n period = i\n break\n points = x_n[-1-period:-1]\n ax.plot(points, points, \"ob\", markersize=3)\n for i in range(0, len(points)):\n px = points[i]\n xa = px-0.000001\n xb = px+0.000001\n ya = fun(r, xa)\n yb = fun(r, xb)\n m = (yb-ya)/(xb-xa)\n print(px)\n a = np.arctan(m)\n tl = 0.24\n ax.plot([px-tl*np.cos(a), px+tl*np.cos(a)], [px-tl*np.sin(a), px+tl*np.sin(a)], \"--\", color=\"blue\")\n \n # plot f(x)\n x = np.linspace(-1, 2.0, 1000)\n y = fun(r, x)\n ax.plot(x, y, \"-b\", label=str(name + \" mit λ = \"+str(r)))\n ax.plot([-1, 2], [-1, 2], \"-k\")\n \n ax.set_aspect(1)\n ax.set_xlim(-0.1, 1.1)\n ax.set_ylim(0.0, 1.25)\n ax.legend(loc=\"upper left\")\n ax.grid()\n\nfig, axs = plt.subplots(1,3,sharey=True,figsize=(9,3.5))\n\n\n# plot f(x)\nx = np.linspace(-1, 2.0, 1000)\ny = f(3.35, x)\naxs[1].plot(x, y, \"-b\", alpha = 0.4)\ny = f(3.835, x)\naxs[2].plot(x, y, \"-b\", alpha = 0.4)\n\nplot(3.35, axs[0], 0.24, f, f, False, \"f(x)\")\nplot(3.35, axs[1], 0.24, g, f, True, \"f(f(x))\")\nplot(3.835, axs[2], 0.25, h, f, True, \"f(f(f(x)))\")\n\nplt.tight_layout()\nplt.savefig(\"../figures/web_2.pdf\")\nplt.show()\n","sub_path":"buch/papers/logistic/python/web_22.py","file_name":"web_22.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"547497088","text":"#!/usr/bin/env python3\n\nimport cv2\nimport numpy as np\n\n\ncap = cv2.VideoCapture(2)\n\nwhile (cap.isOpened()):\n ret, frame = cap.read()\n bw = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n img = bw[10:500,250:290]\n h, w = img.shape\n for i in range(0, h):\n if np.average(img[i] < 50):\n for j in range(0, w):\n frame[i][j][0] = 0\n frame[i][j][1] = 0\n frame[i][j][2] = 255\n break\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\n","sub_path":"scratchpad/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"312856031","text":"#!/bin/python\n\n\ndef percentageGC(dnasequence):\n realbase = \"ATCG\"\n def validitycheck(dnasequence): \n for base in dnasequence:\n if base not in realbase:\n return (\"This is an invalid dna\")\n for data in dnasequence:\n validitycheck(dnasequence)\n Gs=(dnasequence.count(\"G\"))\n Cs=(dnasequence.count(\"C\"))\n length=len(dnasequence)\n GC_content =((Gs + Cs) / length *100)\n return GC_content\n \npercentageGC(input (\"paste DNA sequence:\"))\n\nprint(\"The GC content of your DNA is %.2f\" %(GC_content))\n\n\n","sub_path":"excercise4.py","file_name":"excercise4.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"211760073","text":"from BaseVisualization import BaseVisualization\nfrom numpy import arange, pi, sin, cos\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n\nclass ColumnPictureVisualization(BaseVisualization):\n\n def __init__(self, tkRoot, row, col, rowSpan, colSpan):\n\n super().__init__(tkRoot, row, col, rowSpan, colSpan)\n\n # Create a plot of the two lines described by Ax.\n f = Figure(figsize=(2, 2), dpi=100)\n self.subPlot = f.add_subplot(111)\n x = arange(-pi, pi, 0.01)\n y0 = sin(x)\n y1 = cos(x)\n self.plt = self.subPlot.plot(x, y0, x, y1)\n\n # Add the plot to the tkinter window grid.\n self.canvas = FigureCanvasTkAgg(f, master=tkRoot)\n self.canvas.show()\n self.canvas._tkcanvas.grid(row=row,\n column=col,\n rowspan=rowSpan)\n\n def update(self, A, xhat, b):\n super().update(A, xhat, b)\n","sub_path":"ColumnPictureVisualization.py","file_name":"ColumnPictureVisualization.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"167173981","text":"\"\"\"\n==============\nGroup analysis\n==============\n\nRun the group analysis.\n\"\"\"\nimport os.path as op\n\nimport mne\n\nfrom library.config import study_path\n\nsubjects_dir = op.join(study_path, 'subjects')\nmeg_dir = op.join(study_path, 'MEG')\n\nfamous_fname = op.join(study_path, 'MEG', 'eeg_famous-ave.fif')\nfamous = mne.read_evokeds(famous_fname)[0]\n\nunfamiliar_fname = op.join(study_path, 'MEG', 'eeg_unfamiliar-ave.fif')\nunfamiliar = mne.read_evokeds(unfamiliar_fname)[0]\n\nscrambled = mne.read_evokeds(op.join(study_path, 'MEG',\n 'eeg_scrambled-ave.fif'))[0]\nscrambled.plot_joint()\n\nidx = famous.ch_names.index('EEG070')\nmne.viz.plot_compare_evokeds({'Famous': famous, 'Unfamiliar': unfamiliar,\n 'Scrambled': scrambled}, [idx])\n\nfor evoked in [famous, unfamiliar, scrambled]:\n evoked.apply_baseline()\nmne.viz.plot_compare_evokeds({'Famous': famous, 'Unfamiliar': unfamiliar,\n 'Scrambled': scrambled}, [idx])\n\nfname = op.join(study_path, 'MEG', 'contrast-average')\nstc = mne.read_source_estimate(fname, subject='fsaverage')\nbrain = stc.plot(views=['cau'], hemi='both', subject='fsaverage',\n subjects_dir=subjects_dir)\nbrain.set_data_time_index(204)\n","sub_path":"scripts/results/plot_group.py","file_name":"plot_group.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"52773360","text":"# Copyright 2020 Miljenko Šuflaj\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom sys import stdout\nfrom typing import Any, Callable, Dict, List\n\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport torch\nimport torch.utils.data\nfrom tqdm import tqdm\n\n\ndef evaluate(model: torch.nn.Module, x, y,\n loss: Callable = None, verbose: int = 1) -> Dict[str, Any]:\n \"\"\"\n Evaluates a given model given a set of inputs, outputs and a loss function.\n\n :param model:\n A torch.nn.Module representing the model you wish to evaluate.\n\n :param x:\n A set of inputs you wish to evaluate the model on.\n\n :param y:\n A set of labels you wish to evaluate the model on.\n\n :param loss:\n (Optional) A Callable representing the loss function you wish to\n evaluate the model with. Defaults to None (which will ignore loss\n calculations).\n\n :param verbose:\n (Optional) An int representing the verbosity of evaluation. Defaults to\n 1 (just above no input).\n\n\n :return:\n A Dict[str, any] mapping metric keys to the measure values.\n \"\"\"\n model.eval()\n\n y_pred = list()\n losses = list()\n\n iterator = tqdm(x, total=len(x), file=stdout) if verbose > 0 else x\n\n for _x, _y in zip(iterator, y):\n y_pred.append(model.infer(_x))\n y_pred_tensor = torch.tensor(y_pred[-1]).float().view(_y.shape)\n\n if loss is not None:\n losses.append(float(loss(_y.float(), y_pred_tensor)))\n\n cm = confusion_matrix(np.array(y, dtype=np.int32),\n np.array(y_pred, dtype=np.int32))\n cm_diag = np.diag(cm)\n\n sums = [np.sum(cm, axis=y) for y in [None, 0, 1]]\n\n sums[0] = np.maximum(1, sums[0])\n for i in range(1, len(sums)):\n sums[i][sums[i] == 0] = 1\n\n accuracy = np.sum(cm_diag) / sums[0]\n precision, recall = [np.mean(cm_diag / x) for x in sums[1:]]\n f1 = (2 * precision * recall) / (precision + recall)\n\n return {\"loss\": None if loss is None else float(np.mean(losses)),\n \"acc\": accuracy,\n \"pr\": precision,\n \"re\": recall,\n \"f1\": f1,\n \"cm\": np.ndarray.tolist(cm)}\n\n\ndef convert_timeline_to_diary(timeline: List[Dict[str, Any]]) -> Dict[str, Any]:\n \"\"\"\n Converts a list of logged data into a Dict[str, Any] containing lists of\n data instead of singular values, or in other words a diary.\n\n :param timeline:\n A List[Dict[str, Any]] containing the logged metrics you wish to\n flatten into a diary dictionary.\n\n\n :return:\n A Dict[str, Any] representing the diary dictionary.\n \"\"\"\n to_return = dict()\n\n for time_stamp in timeline:\n for metric, value in time_stamp.items():\n if metric not in to_return:\n to_return[metric] = list()\n\n to_return[metric].append(value)\n\n return to_return\n","sub_path":"LAB3/util/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"280148250","text":"# author:joketeng time:2018/12/3\r\nnums = list(map(int, input().split()))\r\nfor i in range(nums[0]):\r\n temp = list(map(int, input().split()))\r\n g1 = temp[0]\r\n temp = temp[1:]\r\n g2 = 0\r\n num1 = 0\r\n num2 = 0\r\n for c, j in enumerate(temp):\r\n if j > nums[1]:\r\n num1 += 1\r\n temp[c] = nums[1] +1\r\n elif j < 0:\r\n num2 += 1\r\n temp[c] = -1\r\n else:\r\n g2 += j\r\n temp.sort()\r\n g2 -= (temp[num2] + temp[len(temp) - num1 -1])\r\n g2 /= (len(temp) - num1 - num2 - 2)\r\n res = str((g2+g1)/2)\r\n m = res.split('.')\r\n if m[1][0] >= '5':\r\n print(int(m[0]) + 1)\r\n else:\r\n print(int(m[0]))","sub_path":"pat-simple/1077.py","file_name":"1077.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"385095895","text":"import tkinter as tk\r\n\r\nclass PlayAgain(tk.Frame):\r\n\t\r\n\tdef __init__(self, parent, Game):\r\n\t\t\r\n\t\tself.game = Game\r\n\t\tself.config = Game.config\r\n\r\n\t\tsuper().__init__(parent)\r\n\t\tself.configure(bg=\"white\")\r\n\t\tself.grid(row=0, column=0, sticky=\"nsew\")\r\n\t\tparent.grid_columnconfigure(0, weight=1)\r\n\t\tparent.grid_rowconfigure(0, weight=1)\r\n\r\n\t\t#CREATE MAIN FRAME\r\n\t\tself.main_frame = tk.Frame(self, width=self.config.side, height=self.config.side, bg=\"white\")\r\n\t\tself.main_frame.pack(expand=True)\r\n\r\n\t\t#BUTTON\r\n\t\tself.btn_play_again = tk.Button(self.main_frame, text=\"Play Again?\", font=(\"Arial\", 18, \"bold\"), command=lambda:self.game.create_board())\r\n\t\tself.btn_play_again.pack(pady=5)\r\n\r\n\t\tself.btn_main_menu = tk.Button(self.main_frame, text=\"Main Menu\", font=(\"Arial\", 18, \"bold\"), command=lambda:self.game.change_page('main_menu'))\r\n\t\tself.btn_main_menu.pack(pady=5)\r\n\r\n\t\tself.btn_exit = tk.Button(self.main_frame, text=\"Exit\", font=(\"Arial\", 18, \"bold\"), command=lambda:self.game.exit())\r\n\t\tself.btn_exit.pack(pady=5)","sub_path":"play_again.py","file_name":"play_again.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"385250081","text":"import sys\ndef bfs(y,x,space,rc):\n q = [ [y,x] ]\n\n while ( q != [] ):\n now = q.pop(0)\n for i in range(4):\n nowx = now[1] + dx[i]\n nowy = now[0] + dy[i]\n\n if 0 <= nowx < M and 0<= nowy < N and space[nowy][nowx] == 1:\n space[nowy][nowx] = rc\n q.append( [nowy,nowx] )\n\nT = int(input())\ndx = [0, 1 , 0 ,-1 ] #위, 오른쪽, 아래, 왼쪽\ndy = [-1, 0, 1, 0]\nfor i in range(T):\n M ,N, K = map(int,input().split())\n space = [ [0] * M for i in range(N)]\n for j in range(K):\n x, y = map(int,input().split())\n space[y][x] = 1\n\n color = 1000\n rcl = []\n\n for i in range(N):\n for j in range(M):\n color = color + 1\n\n if space[i][j] == 1:\n rc = color\n space[i][j] = rc\n bfs(i,j,space,rc)\n rcl.append(rc)\n \n print(len(rcl))","sub_path":"BoJ/BoJ.1012.py","file_name":"BoJ.1012.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"49705046","text":"# https://leetcode.com/problems/find-median-from-data-stream/description/\r\n\r\n\"\"\"\r\nOther solutions:\r\nhttps://discuss.leetcode.com/topic/30495/tired-of-two-heap-set-solutions-see-this-segment-dividing-solution-c (Sort just a bucket)\r\nhttps://stackoverflow.com/questions/10657503/find-running-median-from-a-stream-of-integers/10693752#10693752 (Approx. only, Reserv. Samp.)\r\n\"\"\"\r\nimport heapq\r\nclass Solution2(object): # Modified from fastest solution\r\n\r\n \"\"\"\r\n Shorter versions:\r\n https://discuss.leetcode.com/topic/27521/short-simple-java-c-python-o-log-n-o-1\r\n https://discuss.leetcode.com/topic/27541/very-short-o-log-n-o-1\r\n https://discuss.leetcode.com/topic/27522/java-python-two-heap-solution-o-log-n-add-o-1-find\r\n \"\"\"\r\n def __init__(self):\r\n self.smaller = [] # max_heap of smaller half of numbers\r\n self.larger = [] \r\n \r\n def addNum(self, num):\r\n \"\"\"\r\n This time, either smaller/larger can have more elements (by no more than one), which means less push/pop so that min is >= max\r\n \"\"\"\r\n num = float(num) # not really necessary, it means everything in heap is float \r\n if not self.smaller or num <= -self.smaller[0]:\r\n heapq.heappush(self.smaller, -num)\r\n else:\r\n heapq.heappush(self.larger, num) \r\n if len(self.smaller) - len(self.larger) > 1:\r\n heapq.heappush(self.larger, -heapq.heappop(self.smaller))\r\n if len(self.larger) - len(self.smaller) > 1:\r\n heapq.heappush(self.smaller, -heapq.heappop(self.larger))\r\n\r\n def findMedian(self):\r\n if not self.smaller and not self.larger:\r\n return 0\r\n if len(self.smaller) == len(self.larger):\r\n return (self.larger[0] - self.smaller[0]) / 2.0\r\n elif len(self.smaller) > len(self.larger):\r\n return -self.smaller[0]\r\n else:\r\n return self.larger[0]\r\n\r\nimport heapq\r\nclass Solution1(object): # Probably could make less janky with separate max_heap class\r\n\r\n def __init__(self):\r\n \"\"\"Sort of like sliding window of 2.\"\"\"\r\n self.hmin = [] # Store the half of the stream with bigger numbers\r\n self.hmax = [] # Store the half of the stream with smaller numbers\r\n\r\n def addNum(self, num):\r\n \"\"\"\r\n Favors hmin, so (1) len(hmin) >= len(hmax)\r\n Other invariants: (2) hmax[0] <= hmin[0], (3) 0 <= len(hmin) - len(hmax) <= 1 \r\n \"\"\"\r\n try:\r\n if num < -self.hmax[0]: # has to go on hmax\r\n if len(self.hmax) == len(self.hmin):\r\n heapq.heappush(self.hmin, -heapq.heappop(self.hmax))\r\n heapq.heappush(self.hmax, -num)\r\n elif num > self.hmin[0]:\r\n if len(self.hmin) > len(self.hmax):\r\n heapq.heappush(self.hmax, -heapq.heappop(self.hmin))\r\n heapq.heappush(self.hmin, num)\r\n else: # hmax[0] <= num <= hmin[0]\r\n if len(self.hmin) > len(self.hmax):\r\n heapq.heappush(self.hmax, -num)\r\n else:\r\n heapq.heappush(self.hmin, num)\r\n except IndexError: # Couldn't think of a more elegant way of doing this besides if-check, which would only occurs twice \r\n if not self.hmin:\r\n heapq.heappush(self.hmin, num)\r\n else: \r\n if num > self.hmin[0]:\r\n heapq.heappush(self.hmax, -heapq.heappop(self.hmin))\r\n heapq.heappush(self.hmin, num)\r\n else:\r\n heapq.heappush(self.hmax, -num)\r\n # print 'After:', num, list(reversed(self.hmin)), self.hmax\r\n\r\n def findMedian(self):\r\n if len(self.hmin) != len(self.hmax): # odd number\r\n return self.hmin[0] # hmin has more\r\n else:\r\n return (self.hmin[0] - self.hmax[0]) / 2.0\r\n \r\n# MedianFinder = Solution1 # 372 ms -> 89.77%\r\nMedianFinder = Solution2 # 325 ms -> 98.72%\r\n\r\n# Your MedianFinder object will be instantiated and called as such:\r\n# obj = MedianFinder()\r\n# obj.addNum(num)\r\n# param_2 = obj.findMedian()","sub_path":"leetcode/python/FindMedianDataStream.py","file_name":"FindMedianDataStream.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"485814420","text":"import cv2\nimport numpy as np\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import img_to_array\n\n\n\nclass OCR():\n\tdef __init__(self):\n\t\tself.loaded_model = None\n\t\tself.load_models()\n\t\t\n\tdef load_models(self):\n\n\t\tself.loaded_model = load_model(\"digits.h5\")\n\n\t\treturn\n\n\n\tdef prediction(self,image):\n\n\t\timage = cv2.resize(image, (28, 28))\n\t\timage = image.astype(\"float\") / 255.0\n\t\timage = img_to_array(image)\n\t\timage = np.expand_dims(image, axis=0)\n\n\t\tpredicted_val = self.loaded_model.predict(image,verbose=0).argmax(axis=1)[0]\n\n\t\treturn predicted_val\n","sub_path":"Sudoku Solver/Recognizer.py","file_name":"Recognizer.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"477734482","text":"import os\nimport numpy as np\nimport pandas as pd\nimport time\nimport copy\nimport math\nimport random \n\nimport torch\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import LambdaLR\n\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\n\nfrom datetime import datetime \nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\n\nfrom skmultilearn.model_selection import IterativeStratification\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tqdm import tqdm\nfrom sklearn.metrics import roc_auc_score\n\n \ndef handling_missing_data(dataframe, list_of_keys): \n \"find all 'nans' within the matrix and replace them by the mean (for continuous) or the most common value (for categorical features)\"\n labels_matrix = np.asarray(dataframe[list_of_keys])\n for counter, key in enumerate(list_of_keys): \n print(key)\n missing_indices = dataframe[key][pd.isnull(dataframe[key])==True].index\n print('number of missing data: ', len(missing_indices))\n if len(missing_indices) != 0:\n if key == 'age': \n age_mean = np.mean(dataframe[key][pd.isnull(dataframe[key])==False])\n print('For age, replace by the mean age: ', age_mean)\n labels_matrix[missing_indices, counter] = age_mean\n dataframe.loc[missing_indices, key] = age_mean\n #print(dataframe.loc[missing_indices,'slide_name'])\n if key == 'location':\n #print(len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1]) , len(dataframe[key][dataframe[key] == 2]))\n loc = np.argmax([len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1]) , len(dataframe[key][dataframe[key] == 2])])\n print('For location, replace by the most common location: ', loc)\n labels_matrix[missing_indices, counter] = loc\n dataframe.loc[missing_indices, key] = loc\n #print(dataframe.loc[missing_indices,'slide_name'])\n if key == 'gender':\n # print(len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1]))\n sex = np.argmax([len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1])]) \n print('For gender, replace by the most common gender: ', sex)\n labels_matrix[missing_indices, counter] = sex \n dataframe.loc[missing_indices, key] = sex\n #print(dataframe.loc[missing_indices,'slide_name'])\n if key == 'UV':\n #print(len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1]))\n uv = np.argmax([len(dataframe[key][dataframe[key] == 0]),len(dataframe[key][dataframe[key] == 1])])\n print('For location, replace by the most common location: ', uv)\n labels_matrix[missing_indices, counter] = uv\n dataframe.loc[missing_indices, key] = uv\n #print(dataframe.loc[missing_indices,'slide_name'])\n return dataframe, labels_matrix\n\ndef split_samples_with_sk_multilearn_v1(n_folds, rs, samples_list, labels_matrix, metadata, result_path=None):\n \"\"\"\n Parameters: \n n_folds: number of folds\n rs: random seed for reproducing\n samples_list: all samples in a list (slides)\n labels_matrix: all data for stratification\n metadata: necessary for plotting the distribution\n --------------------------------------------------\n Returns: \n path_set_folds: dictionary, giving for each fold (fold_0 ... fold_x) and set ('train'/'val'/'test') a list of slide paths \n path_set_folds_indices: same, but returns a list of indices for sample_list \n \"\"\"\n \n np.random.seed(rs)\n splits = int(n_folds)\n k_fold = IterativeStratification(n_splits=splits, order=1) \n folds = [x[1] for x in k_fold.split(samples_list, labels_matrix)] \n \n print('Stratified Folds (Checkpoint: Equally distributed?): ')\n for counter, fold in enumerate(folds):\n print('Fold {}:label nevi {}, label mel {}, Age mean: {}, Females: {}, Males: {}, Extremität: {}, Kopf: {}, Rumpf: {}, Lab 0: {}, Lab 1: {}'.format(counter,\n len(np.where(metadata['label'][fold]==0)[0]),\n len(np.where(metadata['label'][fold]==1)[0]), \n metadata['age'][fold].mean(), \n len(np.where(metadata['gender'][fold]==0)[0]),\n len(np.where(metadata['gender'][fold]==1)[0]), \n len(np.where(metadata['location'][fold]==0)[0]),\n len(np.where(metadata['location'][fold]==1)[0]),\n len(np.where(metadata['location'][fold]==2)[0]), \n len(np.where(metadata['lab'][fold]==0)[0]), \n len(np.where(metadata['lab'][fold]==1)[0])))\n print('*'*40)\n \n all_folds = [samples_list[x] for x in folds] \n folds_variants = np.arange(0,splits)\n images = [0]\n listOfFolds =[0]\n listOfSets = [0]\n \n # validation, testing, training\n splitting = [folds_variants[0:2], folds_variants[2:6], folds_variants[6:]]\n # validation \n val_fold = np.concatenate(([all_folds[idx] for idx in splitting[0]]))\n val_fold_indices = np.concatenate(([folds[idx] for idx in splitting[0]]))\n # testing \n test_fold = np.concatenate(([all_folds[idx] for idx in splitting[1]]))\n test_fold_indices = np.concatenate(([folds[idx] for idx in splitting[1]]))\n # training \n train_fold = np.concatenate(([all_folds[idx] for idx in splitting[2]]))\n train_fold_indices = np.concatenate(([folds[idx] for idx in splitting[2]]))\n\n path_set_folds = {'train': train_fold, 'val': val_fold, 'test': test_fold}\n path_set_folds_indices = {'train': train_fold_indices, 'val': val_fold_indices, 'test': test_fold_indices}\n\n images.extend(train_fold)\n images.extend(val_fold)\n images.extend(test_fold)\n listOfFolds.extend([fold]*(len(train_fold)+len(val_fold)+len(test_fold)))\n listOfSets.extend(['train']*(len(train_fold)))\n listOfSets.extend(['val']*(len(val_fold)))\n listOfSets.extend(['test']*(len(test_fold)))\n\n \n print('#Slides in Trainingset: {} ({} Nevi/{} Mels)'.format(len(train_fold), len(np.where(metadata['label'][train_fold_indices] == 0)[0]), len(np.where(metadata['label'][train_fold_indices] == 1)[0])))\n print('#Slides in Validationset:: {} ({} Nevi/{} Mels)'.format(len(val_fold), len(np.where(metadata['label'][val_fold_indices] == 0)[0]), len(np.where(metadata['label'][val_fold_indices] == 1)[0])))\n print('#Slides in Testset: {} ({} Nevi/{} Mels)'.format(len(test_fold), len(np.where(metadata['label'][test_fold_indices] == 0)[0]), len(np.where(metadata['label'][test_fold_indices] == 1)[0])))\n \n # save folds in a Dataframe \n if result_path != None: \n df = pd.DataFrame({\"Fold\": listOfFolds, 'Images': images, 'Set': listOfSets})\n path_saving = result_path + 'folds.csv'\n if not os.path.exists(result_path):\n os.makedirs(result_path)\n df.to_csv(path_saving, index = False)\n \n return path_set_folds, path_set_folds_indices\n\ndef encodings_v1(combined_metadata, encoding_scheme):\n \"\"\"\n Encodes the patient data depending on the selected encoding schemes\n implemented encoding schemes are:\n scale01: scales all parameters in the range of 0 and 1\n onehot: one hot encoding\n unscaled: no encoding is applied, data is directly taken from the original dataframe \n classified_2: Age is devided into two classes: older/younger than 60; remaining parameters are not changed \n classified_3: Age is devided into three classes: younger than 30, between 30 and 60, older than 60; remaining parameters are not changed \n ----------------\n returns a dataframe including the encoded patient data \n \"\"\"\n if encoding_scheme == 'scale01':\n age = np.asarray(combined_metadata['age']).reshape((-1,1))\n loc = np.asarray(combined_metadata['location']).reshape((-1,1))\n scaler = MinMaxScaler()\n scaler.fit(age)\n age_norm = scaler.transform(age)\n scaler.fit(loc)\n loc_norm = scaler.transform(loc)\n combined_metadata['age'] = age_norm\n combined_metadata['location'] = loc_norm\n \n if encoding_scheme == 'onehot': \n # age \n age = []\n for a in combined_metadata.age: \n if a <= 60:\n age.append([1,0])\n else:\n age.append([0,1]) \n # gender\n gender = []\n for g in combined_metadata.gender: \n if g == 0:\n gender.append([1,0])\n else: \n gender.append([0,1])\n \n # location\n loc = []\n for l in combined_metadata.location: \n if l == 0:\n loc.append([1,0,0])\n elif l == 1: \n loc.append([0,1,0])\n else:\n loc.append([0,0,1]) \n \n combined_metadata.age = age\n combined_metadata.gender = gender\n combined_metadata.location = loc \n \n if encoding_scheme == 'unscaled':\n print('Nothing happens')\n \n if encoding_scheme == 'classified_3': \n #age in three classes: \n age = []\n for a in combined_metadata.age: \n if a <= 30:\n age.append(int(0))\n elif a > 60: \n age.append(int(2))\n else:\n age.append(int(1))\n combined_metadata.age = age\n \n if encoding_scheme == 'classified_2': \n #age in two classes: \n age = []\n for a in combined_metadata.age: \n if a <= 60:\n age.append(int(0))\n else:\n age.append(int(1))\n combined_metadata.age = age\n \n return combined_metadata\n\ndef training_loop_v2(num_epochs, epoch_fine_tuning, lr_unfrozen, optimizer, scheduler, dataloaders, model, test_flag, device, image_datasets, criterion, best_results, fold, result_path, metric_dict, mode, hparams):\n since = time.time()\n \n lr = []\n \n trainings_loss = []\n validation_loss = []\n \n balanced_accuracy_tiles_train = []\n balanced_accuracy_slides_train = []\n balanced_accuracy_tiles_val = []\n balanced_accuracy_slides_val = []\n \n best_bal_acc = 0 # tile level \n epoch_best = 0\n lowest_validation_loss = np.inf\n best_model_wts = copy.deepcopy(model.state_dict())\n \n scheduler_counter = 0 \n for epoch in tqdm(range(num_epochs)):\n if hparams.mode in ['approach_1','approach_2','approach_3']:\n if epoch == hparams.end_epoch_p1:\n scheduler_counter = 0\n print('First Image extractor is frozen')\n for param in model.img_extractor.parameters():\n param.requires_grad = True\n for param in model.metadata_extractor.parameters():\n param.requires_grad = False\n for param in model.fc.parameters():\n param.requires_grad = True\n print('Optimizer works with Lr Image Extractor / Meta Extractor/ FC Layer: {}/- (frozen)/{}'.format(hparams.lr_unfrozen, hparams.lr_fc_unfrozen))\n optimizer = optim.SGD([\n {'params': model.img_extractor.parameters()},\n {'params': model.metadata_extractor.parameters(), 'lr': hparams.lr_meta_unfrozen}, \n {'params': model.fc.parameters(), 'lr': hparams.lr_unfrozen} \n ], lr=hparams.lr_unfrozen, momentum=0.9)\n scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr = hparams.lr_unfrozen, steps_per_epoch = len(dataloaders['train']), epochs = int(hparams.end_epoch_p2 - hparams.end_epoch_p1))\n print('Schedulers total steps: ', scheduler.total_steps)\n print('defined total steps ', len(dataloaders['train'])* int(hparams.end_epoch_p2 - hparams.end_epoch_p1))\n if epoch == hparams.end_epoch_p2:\n scheduler_counter = 0\n print('First Image extractor is frozen')\n for param in model.img_extractor.parameters():\n param.requires_grad = True\n for param in model.metadata_extractor.parameters():\n param.requires_grad = True\n for param in model.fc.parameters():\n param.requires_grad = True\n print('Optimizer works with Lr Image Extractor / Meta Extractor/ FC Layer: {}/{}/{}'.format( hparams.lr_fine, hparams.lr_fine, hparams.lr_fine))\n optimizer = optim.SGD([\n {'params': model.img_extractor.parameters()},\n {'params': model.metadata_extractor.parameters(), 'lr': hparams.lr_fine}, \n {'params': model.fc.parameters(), 'lr': hparams.lr_fine} \n ], lr=hparams.lr_fine, momentum=0.9)\n scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr = hparams.lr_fine, steps_per_epoch = len(dataloaders['train']), epochs = int(num_epochs - (hparams.end_epoch_p2)))\n print('Schedulers total steps: ', scheduler.total_steps)\n print('defined total steps ', len(dataloaders['train'])* int(num_epochs - (hparams.end_epoch_p2 + hparams.end_epoch_p1)))\n else: \n if epoch == hparams.epoch_fine_tuning: \n optimizer = optim.SGD(model.parameters(), lr = hparams.lr_unfrozen, momentum = 0.9)\n scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr = hparams.lr_unfrozen, steps_per_epoch = len(dataloaders['train']), epochs = int(num_epochs - epoch_fine_tuning))\n for param in model.parameters():\n param.requires_grad = True\n\n \n print('Epoch {}/{}'.format(epoch, num_epochs-1))\n print('-'*10)\n \n for phase in ['train', 'val']: \n if phase == 'train': \n model.train()\n else: \n model.eval()\n \n running_loss = 0.0 \n \n y_preds = []\n y_trues = []\n y_scores = []\n slide_id_list = []\n \n print('Scheduler_counter before a new run through the dataloader: ', scheduler_counter)\n for counter, (img_inputs, meta_inputs, labels_slide_id) in enumerate(dataloaders[phase]): \n if test_flag and counter >5: \n break\n \n labels = labels_slide_id[:,0] # (label, slide_id, col, row)\n slide_ids = labels_slide_id[:,1]\n cols = labels_slide_id[:,2]\n rows = labels_slide_id[:,3]\n \n img_inputs = img_inputs.to(device)\n meta_inputs = meta_inputs.to(device)\n labels = labels.to(device)\n \n optimizer.zero_grad()\n \n with torch.set_grad_enabled(phase == 'train'): \n if mode == 'base': \n outputs = model(img_inputs) # Output is the result of fully connected layer (two neurons), no softmax\n else:\n # Inportance, or Concatenation \n #print(meta_inputs.shape)\n outputs = model(img_inputs, meta_inputs) # output is a value between 0 and 1, describing the probability of melanoma\n \n if outputs.dim() == 1: # BCELoss; bei approach 1 kommt hier ein Fehler ... \n preds = 1 * (outputs >= 0.5) \n labels = labels.float()\n #print(labels)\n else:\n # if Cross Entropy \n outputs = torch.softmax(outputs,dim=1) # turning the output into 'probabilities'\n _, preds = torch.max(outputs, 1)\n \n y_preds.append(preds.detach().cpu().numpy())\n y_trues.append(labels.detach().cpu().numpy())\n slide_id_list.append(slide_ids.detach().cpu().numpy())\n y_scores.append(outputs.detach().cpu().numpy())\n \n loss = criterion(outputs, labels)\n \n if phase == 'train': \n loss.backward()\n optimizer.step()\n lr.append(scheduler.get_last_lr())\n scheduler_counter +=1 \n scheduler.step() # scheduler step after each minibatch! \n \n running_loss += loss.item()*img_inputs.size(0)\n \n \n # Balanced accuracy on tile level \n y_preds = np.concatenate(y_preds)\n y_trues = np.concatenate(y_trues)\n slide_id_list = np.concatenate(slide_id_list)\n y_scores = np.concatenate(y_scores)\n bal_acc_tiles = balanced_accuracy_score(y_trues, y_preds)\n epoch_loss = running_loss/ len(image_datasets[phase])\n bal_acc_slides = calculate_slide_acc(y_scores, slide_id_list, y_trues)\n #bal_acc_slides = calculate_slide_acc(y_preds, slide_id_list, y_trues)\n print('Phase {}, epoch loss {:.5f}, bal_acc_tiles {:.5f}, bal_acc_slides {:.5f}'.format(phase, epoch_loss, bal_acc_tiles, bal_acc_slides))\n \n # Saving epoch results \n if phase == 'train': \n trainings_loss.append(epoch_loss)\n balanced_accuracy_tiles_train.append(bal_acc_tiles)\n balanced_accuracy_slides_train.append(bal_acc_slides)\n else: \n validation_loss.append(epoch_loss)\n balanced_accuracy_tiles_val.append(bal_acc_tiles)\n balanced_accuracy_slides_val.append(bal_acc_slides)\n \n #deep copy model\n #if phase == 'val' and epoch_loss < epoch_lowest_loss: # Auf loss umsteigen?\n if phase == 'val' and bal_acc_tiles > best_bal_acc and epoch > 5: \n best_bal_acc = bal_acc_tiles\n epoch_best_acc = epoch \n best_model_wts = copy.deepcopy(model.state_dict())\n best_results['fold_'+str(fold)] = {'epoch': epoch, 'bal_acc_tiles': bal_acc_tiles, 'bal_acc_slides': bal_acc_slides}\n \n save_model_path = result_path + 'models/'\n if not os.path.exists(save_model_path): \n os.makedirs(save_model_path)\n #date = str(datetime.now().strftime(\\\"%d%m%Y\\\"))\n model_name = 'best_model_fold_'+str(fold)\n torch.save(model.state_dict(), save_model_path+model_name)\n \n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed//60, time_elapsed%60))\n #print('Best BalAcc on Validation: {:.5f} achieved in epoch {}'.format(best_bal_acc, epoch_best))\n print('Best BalAcc on Validation: {:.5f} achieved in epoch {}'.format(best_bal_acc, epoch_best_acc))\n metric_dict['fold_'+str(fold)] = {'loss_train': trainings_loss, \n 'bal_acc_tiles_train': balanced_accuracy_tiles_train, \n 'bal_acc_slides_train': balanced_accuracy_slides_train,\n 'loss_val': validation_loss, \n 'bal_acc_tiles_val': balanced_accuracy_tiles_val, \n 'bal_acc_slides_val': balanced_accuracy_slides_val, \n 'lr': lr}\n print('Loading the models best parameters')\n model.load_state_dict(best_model_wts)\n \n return model, best_results, metric_dict\n\ndef test_loop_v1(model, dataloaders, image_datasets, test_results, device, fold, mode, phase='test'):\n \n model.eval() \n \n running_loss = 0.\n y_preds = []\n y_trues = []\n slide_id_list = []\n y_scores = []\n\n for counter, (img_inputs, meta_inputs, labels_slide_id) in enumerate(dataloaders[phase]): \n labels = labels_slide_id[:,0] \n slide_ids = labels_slide_id[:,1]\n cols = labels_slide_id[:,2]\n rows = labels_slide_id[:,3]\n \n img_inputs = img_inputs.to(device)\n meta_inputs = meta_inputs.to(device)\n labels = labels.to(device)\n \n with torch.set_grad_enabled(phase == 'train'): \n if mode == 'base': \n outputs = model(img_inputs) \n else:\n # Inportance, or Concatenation, multiplication \n outputs = model(img_inputs, meta_inputs) \n \n if outputs.dim() == 1: \n # BCELoss\n preds = 1 * (outputs >= 0.5) \n labels = labels.float()\n \n else:\n # Cross Entropy\n outputs = torch.softmax(outputs,dim=1) \n _, preds = torch.max(outputs, 1)\n \n y_preds.append(preds.detach().cpu().numpy())\n y_trues.append(labels.detach().cpu().numpy())\n slide_id_list.append(slide_ids.detach().cpu().numpy())\n y_scores.append(outputs.detach().cpu().numpy()) \n \n y_preds = np.concatenate(y_preds)\n y_trues = np.concatenate(y_trues)\n slide_id_list = np.concatenate(slide_id_list)\n y_scores = np.concatenate(y_scores)\n # tile level \n bal_acc_tiles = balanced_accuracy_score(y_trues, y_preds)\n \n # slide level \n bal_acc_slides = calculate_slide_acc(y_scores, slide_id_list, y_trues)\n print('Phase {}, bal_acc_tiles {:.5f}, bal_acc_slides {:.5f}'.format(phase, bal_acc_tiles, bal_acc_slides))\n test_results['fold_'+str(fold)] = {'bal_acc_t': bal_acc_tiles, 'bal_acc_s': bal_acc_slides}\n \n return test_results \n\ndef test_loop_v2(model, dataloaders, criterion, image_datasets, test_results, device, fold, mode, phase='test'):\n \n model.eval() \n \n running_loss = 0.\n y_preds = []\n y_trues = []\n slide_id_list = []\n y_scores = []\n\n \n for img_inputs, meta_inputs, labels_slide_id in tqdm(dataloaders[phase]): \n labels = labels_slide_id[:,0] # (label, slide_id, col, row)\n slide_ids = labels_slide_id[:,1]\n cols = labels_slide_id[:,2]\n rows = labels_slide_id[:,3]\n \n img_inputs = img_inputs.to(device)\n meta_inputs = meta_inputs.to(device)\n labels = labels.to(device)\n \n with torch.set_grad_enabled(phase == 'train'): \n if mode == 'base': \n outputs = model(img_inputs) \n else:\n # Inportance, or Concatenation, multiplication \n outputs = model(img_inputs, meta_inputs) \n \n if outputs.dim() == 1: # BCELoss\n preds = 1 * (outputs >= 0.5) \n labels = labels.float()\n else:\n # if Cross Entropy \n outputs = torch.softmax(outputs,dim=1) \n _, preds = torch.max(outputs, 1)\n \n y_preds.append(preds.detach().cpu().numpy())\n y_trues.append(labels.detach().cpu().numpy())\n slide_id_list.append(slide_ids.detach().cpu().numpy())\n y_scores.append(outputs.detach().cpu().numpy()) \n \n y_preds = np.concatenate(y_preds)\n y_trues = np.concatenate(y_trues)\n slide_id_list = np.concatenate(slide_id_list)\n y_scores = np.concatenate(y_scores)\n # tile level \n bal_acc_tiles = balanced_accuracy_score(y_trues, y_preds)\n # slide level \n bal_acc_slides, slides_included, slides_label, slides_preds, slides_output = calculate_slide_acc_v1(y_scores, slide_id_list, y_trues)\n print('Phase {}, bal_acc_tiles {:.5f}, bal_acc_slides {:.5f}'.format(phase, bal_acc_tiles, bal_acc_slides))\n test_results['fold_'+str(fold)] = {'bal_acc_t': bal_acc_tiles, 'bal_acc_s': bal_acc_slides}\n \n return test_results, y_scores, slides_label, slides_preds, slides_output, slides_included\n\ndef calculate_slide_acc(y_scores, slide_id_list, y_trues): \n slides_included = np.unique(slide_id_list)\n slides_label = np.zeros(int(len(slides_included)))\n if y_scores.ndim == 1: \n slides_output = np.zeros(len(slides_included))\n for counter, slide in enumerate(slides_included): \n idx = np.where(slide_id_list == slide)[0] \n tiles_probs = y_scores[idx].sum(axis=0)/len(idx) \n slides_output[counter] = tiles_probs \n slides_label[counter] = y_trues[idx[0]]\n slides_preds = 1 * (slides_output >= 0.5)\n \n else: # base and approach 1 \n slides_output = np.zeros((len(slides_included),2))\n for counter, slide in enumerate(slides_included): \n idx = np.where(slide_id_list == slide)[0] \n tiles_probs = y_scores[idx,:].sum(axis=0)/len(idx) \n slides_output[counter] = tiles_probs \n slides_label[counter] = y_trues[idx[0]]\n slides_preds = np.argmax(slides_output, 1) \n \n bal_acc_slides = balanced_accuracy_score(slides_label, slides_preds)\n return bal_acc_slides\n\ndef calculate_slide_acc_v1(y_scores, slide_id_list, y_trues): \n slides_included = np.unique(slide_id_list)\n slides_label = np.zeros(int(len(slides_included)))\n \n if y_scores.ndim == 1: # if BCE (approach 2, appraoch 3)\n slides_output = np.zeros(len(slides_included))\n for counter, slide in enumerate(slides_included): \n idx = np.where(slide_id_list == slide)[0] \n tiles_probs = y_scores[idx].sum(axis=0)/len(idx) \n slides_output[counter] = tiles_probs \n slides_label[counter] = y_trues[idx[0]]\n slides_preds = 1 * (slides_output >= 0.5)\n \n else: # base and approach 1 \n slides_output = np.zeros((len(slides_included),2))\n for counter, slide in enumerate(slides_included): \n idx = np.where(slide_id_list == slide)[0] \n tiles_probs = y_scores[idx,:].sum(axis=0)/len(idx) \n slides_output[counter] = tiles_probs \n slides_label[counter] = y_trues[idx[0]]\n slides_preds = np.argmax(slides_output, 1) \n \n bal_acc_slides = balanced_accuracy_score(slides_label, slides_preds)\n \n return bal_acc_slides, slides_included, slides_label, slides_preds, slides_output \n \n","sub_path":"PDI_classes_and_functions/functions_v2.py","file_name":"functions_v2.py","file_ext":"py","file_size_in_byte":26575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"168271461","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n \nclass DoublyLinkedList:\n def __init__(self):\n self.head = None # if empty list, the head node is none\n\n def append(self, data):\n if self.head is None: # if the head node is none (there are no elements in the list)\n new_node = Node(data) # we'll create a new node based on the data passed into the append function\n new_node.prev = None # make sure that prev point of this new node points to none\n self.head = new_node # update status of the head pointer, ie., the head is now the new node that we just put on to that new list\n else: # if there is at least one element in the list\n new_node = Node(data) # create the new node\n cur = self.head # set cur to first node (self.head)\n while cur.next: # while not none, cur = the current node\n cur = cur.next # update the current pointer to keep going down the list\n cur.next = new_node # next pointer of that node points to the new node\n new_node.prev = cur # the new node's previous pointer points to the cur(rent) node (the last one on the list)\n new_node.next = None # new node's next is now None\n\n def prepend(self, data):\n if self.head is None:\n new_node = Node(data) # create a new node based on the data fed in\n new_node.prev = None\n self.head = new_node\n else:\n new_node = Node(data) # new_node = Node of data\n self.head.prev = new_node # we want the previous pointer of the current head to point to the new node that we just created\n new_node.next = self.head # new_node.next = head of the list\n self.head = new_node # make the new_node the head\n new_node.prev = None # make sure the new_node's prev points to None\n\n def print_list(self):\n cur = self.head # current is set to the head of the list\n while cur:\n print(cur.data)\n cur = cur.next # move that pointer right along the list\n\ndllist = DoublyLinkedList() # we've created a doubly linked list\ndllist.prepend(0)\ndllist.append(1) # append elements 1 - 4\ndllist.append(2)\ndllist.append(3)\ndllist.append(4)\ndllist.prepend(-1)\n\ndllist.print_list() # print the list out to the screen","sub_path":"doubly_linked_list/doubly_app_pre.py","file_name":"doubly_app_pre.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"543242356","text":"from tree import Tree\nfrom garden import Garden\nfrom gnome import Gnome\nfrom woodchuck import Woodchuck\nimport random\n\ngarden = Garden()\n\ndef main():\n turn_counter = 0\n while len(garden.trees) <= 10 and garden.water_level > 0:\n print(\"taking a turn now\")\n\n if \"tree death chance eequals true kill tree\":\n \"kill tree\"\n else:\n \"nothing\"\n\n if garden.check_rain() == True:\n garden.rain()\n else:\n garden.evaporate()\n \n if turn_counter % 10 == 0:\n chance = random.randint(1,2)\n if chance == 1:\n garden.get_gnome()\n else:\n garden.get_tree()\n turn_counter += 1","sub_path":"garden-sim.py","file_name":"garden-sim.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"333063656","text":"\"\"\"The analysis server. Process raw image to PDF.\"\"\"\nimport typing as tp\n\nfrom area_detector_handlers.handlers import AreaDetectorTiffHandler\nfrom bluesky.callbacks.zmq import Publisher\nfrom databroker.v1 import Broker\nfrom event_model import RunRouter\nfrom ophyd.sim import NumpySeqHandler\n\nimport pdfstream.io as io\nfrom pdfstream.callbacks.analysis import AnalysisConfig, VisConfig, ExportConfig, AnalysisStream, Exporter, \\\n Visualizer\nfrom pdfstream.callbacks.calibration import CalibrationConfig, Calibration\nfrom pdfstream.servers import CONFIG_DIR, ServerNames\nfrom pdfstream.servers.base import ServerConfig, find_cfg_file, BaseServer, StartStopCallback\n\n\nclass XPDConfig(AnalysisConfig, VisConfig, ExportConfig, CalibrationConfig):\n \"\"\"The configuration for the xpd data reduction. It consists of analysis, visualization and exportation.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(XPDConfig, self).__init__(*args, **kwargs)\n self.add_section(\"PUBLISH TO\")\n self.add_section(\"FUNCTIONALITY\")\n\n @property\n def an_db(self) -> str:\n return self.get(\"DATABASE\", \"an_db\", fallback=\"\")\n\n @property\n def publisher_config(self) -> dict:\n host = self.get(\"PUBLISH TO\", \"host\", fallback=\"localhost\")\n port = self.getint(\"PUBLISH TO\", \"port\", fallback=5567)\n prefix = self.get(\"PUBLISH TO\", \"prefix\", fallback=\"an\").encode()\n return {\n \"address\": (host, port),\n \"prefix\": prefix\n }\n\n @property\n def functionality(self) -> dict:\n return {\n \"do_calibration\": self.getboolean(\"FUNCTIONALITY\", \"do_calibration\", fallback=True),\n \"dump_to_db\": self.getboolean(\"FUNCTIONALITY\", \"dump_to_db\", fallback=True),\n \"export_files\": self.getboolean(\"FUNCTIONALITY\", \"export_files\", fallback=True),\n \"visualize_data\": self.getboolean(\"FUNCTIONALITY\", \"visualize_data\", fallback=True),\n \"send_messages\": self.getboolean(\"FUNCTIONALITY\", \"send_messages\", fallback=False)\n }\n\n\nclass XPDServerConfig(XPDConfig, ServerConfig):\n \"\"\"The configuration for xpd server.\"\"\"\n pass\n\n\nclass XPDServer(BaseServer):\n \"\"\"The server of XPD data analysis. It is a live dispatcher with XPDRouter subscribed.\"\"\"\n def __init__(self, config: XPDServerConfig):\n super(XPDServer, self).__init__(config.address, prefix=config.prefix)\n self.subscribe(StartStopCallback())\n self.subscribe(XPDRouter(config))\n\n\ndef make_and_run(\n cfg_file: str = None,\n *,\n suppress_warning: bool = True,\n test_mode: bool = False\n):\n \"\"\"Run the xpd data reduction server.\n\n The server will receive message from proxy and process the data in the message. The processed data will be\n visualized and exported to database and the file system.\n\n Parameters\n ----------\n cfg_file :\n The path to configuration .ini file. The default path is \"~/.config/acq/xpd_server.ini\".\n\n suppress_warning :\n If True, all warning will be suppressed. Turn it to False when running in a test.\n\n test_mode :\n If True, just create a server but not start. Used for test.\n \"\"\"\n if suppress_warning:\n import warnings\n warnings.simplefilter(\"ignore\")\n if not cfg_file:\n cfg_file = find_cfg_file(CONFIG_DIR, ServerNames.xpd)\n config = XPDServerConfig()\n config.read(cfg_file)\n server = XPDServer(config)\n if config.functionality[\"visualize_data\"] and not test_mode:\n server.install_qt_kicker()\n if not test_mode:\n server.start()\n\n\nclass XPDRouter(RunRouter):\n \"\"\"A router that contains the callbacks for the xpd data reduction.\"\"\"\n\n def __init__(self, config: XPDConfig):\n factory = XPDFactory(config)\n super(XPDRouter, self).__init__(\n [factory],\n handler_registry={\n \"NPY_SEQ\": NumpySeqHandler,\n \"AD_TIFF\": AreaDetectorTiffHandler\n }\n )\n\n\nclass XPDFactory:\n \"\"\"The factory to generate callback for xpd data reduction.\"\"\"\n\n def __init__(self, config: XPDConfig):\n self.config = config\n self.functionality = self.config.functionality\n self.analysis = [AnalysisStream(config)]\n self.calibration = [Calibration(config)] if self.functionality[\"do_calibration\"] else []\n if self.functionality[\"dump_to_db\"] and self.config.an_db:\n db = Broker.named(self.config.an_db)\n self.analysis[0].subscribe(db.insert)\n if self.functionality[\"export_files\"]:\n self.analysis[0].subscribe(Exporter(config))\n if self.functionality[\"visualize_data\"]:\n self.analysis[0].subscribe(Visualizer(config))\n if self.functionality[\"send_messages\"]:\n self.analysis[0].subscribe(Publisher(**self.config.publisher_config))\n\n def __call__(self, name: str, doc: dict) -> tp.Tuple[list, list]:\n if name == \"start\":\n if doc.get(self.config.dark_identifier):\n # dark frame run\n io.server_message(\"Ignore dark frame.\")\n return [], []\n elif doc.get(self.config.calib_identifier):\n # calibration run\n io.server_message(\"Start calibration.\")\n return self.calibration, []\n else:\n # light frame run\n io.server_message(\"Start data reduction.\")\n return self.analysis, []\n return [], []\n","sub_path":"pdfstream/servers/xpd_server.py","file_name":"xpd_server.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"636700742","text":"from templates.button import ButtonTemplate\n\ndef process(input, entities, sender):\n request = '''Kindly click the following button to:\\n\n - Request a new feature, by including some sample queries and their expected results.\\n\n - Report a bug (I couldn't handle the query and/or gave unexpected results), by including your search query and the expected result.'''\n template = ButtonTemplate(request)\n template.add_web_url('Request / Report', 'http://bahbi.net')\n output = {\n 'input': input,\n 'output': template.get_message(),\n 'success': True\n }\n return output\n","sub_path":"modules/src/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"401660386","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\nfrom pages import *\nfrom logger import *\ninit_logger()\n\nclass TestPages(unittest.TestCase):\n\n\n\t@classmethod\n\tdef test_1_SetUp(self):\n\t\tself.driver = webdriver.Chrome()\n\t\tself.driver.implicitly_wait(10)\n\t\tself.driver.maximize_window()\n\t\tself.driver.get(\"https://fix-online.sbis.ru/\")\n\t\tself.emplo = Emplo_page(self.driver)\n\t\tself.user = user_menu(self.driver)\n\t\tself.auth = Auth_page(self.driver)\n\t\tself.accord = accordeon(self.driver)\n\n\tdef test_2_auth(self): #contain auth page\n\t\t#page = Auth_page(self.driver)\n\t\tself.driver.implicitly_wait(10)\n\t\tself.assertTrue(\"Вход в систему/СБИС\")\n\t\tself.auth.log(\"check_rigth_user\")\n\t\tself.auth.pas(\"qwerty123\")\n\t\tself.auth.log_btn()\n\n\tdef test_3_MainTestPage(self):\n\t\tself.driver.implicitly_wait(10)\n\t\tself.accord.check_page_open()\n\t\tself.accord.emplo_click()\n\t\tself.accord.emplo2_click()\n\t\tself.emplo.check_open()\n\t\tself.emplo.org_change()\n\t\tself.emplo.org_open_check()\n\t\tself.emplo.org_select()\n\t\tself.emplo.send_empl(\"Белова Олеся Александровна\")\n\t\tself.emplo.emplo_choise()\n\t\tself.emplo.open_card_check()\n\t\tself.emplo.close_card()\n\t\tself.emplo.check_open()\n\t\tself.user.btn_self()\n\t\tself.user.btn_exit_sbis()\n\t\tself.user.check_end()\n\t\n\tdef test_4_tearDown(self):\n\t\tself.driver.close()\n\nif __name__ == '__main__':\n\t#unittest.main()\n\ttest = unittest.TestLoader().loadTestsFromTestCase(TestPages)\n\tunittest.TextTestRunner(verbosity=2).run(test)","sub_path":"Script.py","file_name":"Script.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"559035222","text":"#import pdb; pdb.set_trace()\na = \"off\"\nb = \"off\"\nc = \"off\"\n\nwhile True:\n\tprint(\"Enter a number between 1 and 3: \")\n\tx= str(input())\n\tprint(\"You just entered \" + x)\n\tif x == \"1\":\n\t\tif a==\"off\":\n\t\t\ta=\"on\"\n\t\telse:\n\t\t\ta=\"off\"\n\telif x ==\"2\":\n\t\tif b==\"off\":\n\t\t\tb=\"on\"\n\t\telse:\n\t\t\tb=\"off\"\n\telif x ==\"3\":\n\t\tif c==\"off\":\n\t\t\tc=\"on\"\n\t\telse:\n\t\t\tc=\"off\"\n\tif a==\"on\" and b==\"on\" and c==\"on\":\n\t\tprint(\"hoorah\")\n\telse:\n\t\tprint(\"meh\")","sub_path":"bulbs.py","file_name":"bulbs.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"117213536","text":"import os\nimport sys\n\ndef serepite(tupla, num): #Recibe tupla y numero, si se repite numero retorna cuantas veces, si no, retorna 0\n if tupla.count(num) <= 1:\n print('0')\n else:\n print(str(tupla.count(num)))\n\ndef regresamaymen(tupla):\n print(max(tupla),min(tupla))\n\ndef regresamaymenDif(tupla):\n\tmayor = 0\n\tmenor = tupla[0]\n\tfor i in range(len(tupla)):\n\t\tif tupla[i] > mayor:\n\t\t\tmayor = tupla[i]\n\t\tpass\n\t\tif tupla[i] < menor:\n\t\t\tmenor = tupla[i]\n\t\tpass\n\treturn(mayor, menor)\n\tpass\n\ndef creaagenda():\n dict = {}\n nombre = input(\"Ingresa un nombre: \")\n telefono = int(input(\"Ingresa el telefono: \"))\n while telefono != 0:\n dict[nombre] = telefono\n nombre = input(\"Ingresa un nombre: \")\n telefono = int(input(\"Ingresa el telefono: \"))\n print(dict)\n\ndef directorio():\n\tagenda = {'nombre': [], 'telefono' : []}\n\tnom = []\n\ttel = []\n\tnom = input(\"Dame un nombre\")\n\ttel = input(\"Dame un numero\")\n\twhile nom != '0'or tel != '0' :\n\t\tagenda['nombre'].append(nom)\n\t\tagenda['telefono'].append(tel)\n\t\tnom = input(\"Dame un nombre\")\n\t\ttel = input(\"Dame un numero\")\n\tprint (agenda)\n\ndef tupladefinida():\n tupladefinida = (1,\"hola\", [1,2], (1,2))\n num = int(input('Dame un entero: '))\n print(tupladefinida[num])\n\ndef cosapolitica(tupla):\n for i in tupla:\n print(\"Estimado \"+i+\" vote por mi\")\n\ndef propaganda(tup):\n\tfor i in range(len(tup)):\n\t\tprint('Estimado/a',tup[i], 'vote por mi.')\n\ndef inviertelista(lista):\n lista2 = []\n for i in reversed(lista):\n lista2.append(i)\n print(lista2)\n\ndef reverseList(ListReverse):\n NewList = ListReverse[::-1]\n print (NewList)\n\ndef domino(tupla,tupla2):\n if tupla[0] in tupla2 or tupla[1] in tupla2:\n print(\"Si encajan\")\n else:\n print(\"No encajan\")\n\ntuplaejercicio = (1,1,1,2,3,4,5)\ntup1 = (2,5)\ntup2 = (3,5)\ntup3 = (4,6)\ntuplanombres = (\"Hayde\", \"Viri\", \"Ali\")\nnum = 2\nlistaejercicio = [\"a\",\"b\",\"c\"]\n#serepite(tuplaejercicio,num)\n#regresamaymen(tuplaejercicio)\n#creaagenda()\n#directorio()\n#tupladefinida()\n#cosapolitica(tuplanombres)\n#propaganda(tuplanombres)\n#reverseList(listaejercicio)\n#domino(tup1, tup2)\n#domino(tup2, tup3)\n","sub_path":"Semana4/ejerciciosTarea290518.py","file_name":"ejerciciosTarea290518.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"59001630","text":"__author__ = \"Tim Pose\"\n__credits__ = [\"Peter Detzner\"]\n__maintainer__ = \"Tim Pose\"\n__status__ = \"Development\"\n\nimport functools\nimport logging\nfrom concurrent.futures import Future\nfrom os import getenv\nfrom threading import current_thread\nfrom time import time\nfrom typing import Callable, Optional, Tuple\n\nfrom logic.HeartbeatWrapper import HeartbeatWrapper\nfrom utils import Constants\nfrom utils.threading.LoopThreadWorker import LoopThreadWorker\n\n\nclass FreshnessCheck(LoopThreadWorker):\n \"\"\"Represents a ``FreshnessCheck`` thread, that takes new ``Heartbeats`` and calculates their next freshness point.\n If at those points in time, the expected ``Heartbeat`` wasn´t received, it lowers the corresponding ``Agent´s``\n status. Has the status dropped down to \"toDelete\", no next freshness points will be calculated for that ``Agent``\n and so these wont be checked anymore, because the ``Agent`` cant drift further below that level. To allow new\n ``Heartbeats``, after a dropdown to \"toDelete\" act as fresh ``Heartbeats``, their history will be deleted.\n Otherwise the history would be implicated to the next freshness point, which would then be in the past.\n\n Notes:\n Due to restrictions to a single-threaded piece of software, this module doesnt guarantee the checks to be\n run to their suited time points. They will be run then OR soon after that.\n \"\"\"\n DELETE_AGENT_AFTER_SEC = int(getenv(Constants.ENV_DELETE_AGENT_AFTER, Constants.DEFAULT_DELETE_AGENT_AFTER))\n DECIMAL_PLACES = 2\n # Slack parameters for he Heartbeat arrival time of agents, that are not using the monitoredProperty option\n JACOBSON_GAMMA = float(getenv(Constants.ENV_JACOBSON_GAMMA, Constants.DEFAULT_JACOBSON_GAMMA))\n JACOBSON_BETA = float(getenv(Constants.ENV_JACOBSON_BETA, Constants.DEFAULT_JACOBSON_BETA))\n JACOBSON_PHI = float(getenv(Constants.ENV_JACOBSON_PHI, Constants.DEFAULT_JACOBSON_PHI))\n\n\n def __init__(self, removeAgent: Callable[[Tuple[str, str]], None], locks: dict):\n \"\"\"``FreshnessCheck`` constructor.\n\n Args:\n removeAgent: Callback to remove a certain Agent from the application\n locks: Dict containing locks for every known Agent\n \"\"\"\n super().__init__()\n self.__removeAgent = removeAgent\n self.__checkTasks = {} # Tasks executed by the event loop\n self.__currentFreshnessPoint = {} # Calculated freshness points\n self.__expectedArrivalTime = {}\n self.__locks = locks\n\n def run(self):\n \"\"\"Creates a new event loop, binds it to this thread and starts it.\n \"\"\"\n super().run() # Creates a new event loop and binds it to this thread\n logging.debug(\"FreshnessCheck: %s\", current_thread())\n self.loop.run_forever()\n\n def stop(self):\n \"\"\"Stops the event loop bound to this thread and all scheduled tasks.\n \"\"\"\n logging.debug(\"FreshnessCheck: Stopping.\")\n for task in self.__checkTasks.copy().values():\n task.cancel()\n self.loop.call_soon_threadsafe(self.loop.stop)\n\n def __checkFreshnessPoint(self, heartbeatWrapper: HeartbeatWrapper):\n \"\"\"Checks if the current freshness point is old. If so the ``Agent´s`` status is lowered. Is the status above\n \"toDelete\", a new freshness point will be calculated and awaited. Else the ``Agent´s`` ``Heartbeat`` history\n will be deleted.\n\n Args:\n heartbeatWrapper: Agents Heartbeats to be checked against current freshness point\n \"\"\"\n with self.__locks[heartbeatWrapper.getAgentIdentifier()]:\n logging.debug(\"FreshnessCheck: Checking %s\", heartbeatWrapper)\n currentFreshnessPoint = self.__currentFreshnessPoint.get(heartbeatWrapper.getAgentIdentifier())\n if time() > currentFreshnessPoint:\n logging.debug(\"FreshnessCheck: Flag '%s'.\", heartbeatWrapper.getAgentIdentifier())\n heartbeatWrapper.lowerHeartbeatStatus()\n heartbeatWrapper.missingHeartbeat() # Indicate that a Heartbeat was missing\n logging.debug(\"FreshnessCheck: New status of '%s' is '%s'.\", heartbeatWrapper.getAgentIdentifier(),\n heartbeatWrapper.getHeartbeatStatusAsText())\n if not heartbeatWrapper.isToDelete():\n # The after next freshness point will be calculated, because no Heartbeat was received. Reaching\n # that point will mark the Agent as \"toDelete\"\n self.addHeartbeat(heartbeatWrapper, afterNext=True)\n else:\n # The Agent´s status is already \"toDelete\". That means the history can be deleted\n self.__currentFreshnessPoint.pop(heartbeatWrapper.getAgentIdentifier())\n heartbeatWrapper.deleteHeartbeats() # Delete the History, so that a newly received Heartbeat and\n # his corresponding freshness point wont be calculated with old Heartbeats. Otherwise the freshness\n # point would be in the past\n # Schedule the Agent to be deleted after DELETE_AGENT_AFTER_SEC seconds\n future = self.callLater(FreshnessCheck.DELETE_AGENT_AFTER_SEC,\n self.__delete, heartbeatWrapper.getAgentIdentifier())\n future.add_done_callback(functools.partial(self.__setTask, heartbeatWrapper.getAgentIdentifier()))\n logging.debug(\"FreshnessCheck: Scheduled '%s' to be deleted from the application in %d seconds.\",\n heartbeatWrapper.getAgentIdentifier(), FreshnessCheck.DELETE_AGENT_AFTER_SEC)\n\n def addHeartbeat(self, heartbeatWrapper: HeartbeatWrapper, afterNext: bool = False):\n \"\"\"Computes the next freshness point for the ``Heartbeats`` contained by ``heartbeatWrapper`` and adds a\n freshness check to be run at that point in time to the event loop.\n\n Args:\n heartbeatWrapper: Heartbeats to be used for freshness calculation\n afterNext: (default=False) Signals that the after next freshness point should be used\n \"\"\"\n agentIdentifier = heartbeatWrapper.getAgentIdentifier()\n if self.__checkTasks.get(agentIdentifier) is not None:\n self.__checkTasks[agentIdentifier].cancel()\n\n slack = 0\n if not afterNext: # If a new Heartbeat was received\n expectedArrivalTime = self.__expectedArrivalTime.get(agentIdentifier)\n slack = FreshnessCheck.calculateSlack(heartbeatWrapper, expectedArrivalTime)\n expectedArrivalTime = FreshnessCheck.computeExpectedArrivalTime(heartbeatWrapper, afterNext=afterNext)\n if not afterNext: # If a new Heartbeat was received\n self.__expectedArrivalTime[agentIdentifier] = expectedArrivalTime\n freshnessPoint = expectedArrivalTime + slack\n logging.debug(\"FreshnessCheck: Computed next freshness point for '%s' is in '%f' seconds. \"\n \"It is composed of the expected arrival time '%s' and a slack of '%s'.\",\n heartbeatWrapper.getAgentIdentifier(), freshnessPoint - time(),\n expectedArrivalTime, slack)\n self.__currentFreshnessPoint[agentIdentifier] = freshnessPoint\n future = self.callLater(freshnessPoint - time(), self.__checkFreshnessPoint, heartbeatWrapper)\n # The future returned by callLater() is instantly done, so add a callback to get the wrapped results\n future.add_done_callback(functools.partial(self.__setTask, agentIdentifier))\n\n def __setTask(self, agentIdentifier: Tuple[str, str], task: Future):\n \"\"\"Sets the ``task`` as current check for the ``Agent`` ``agentIdentifier``.\n\n Args:\n agentIdentifier: Concerned Agent\n task: Future to be set as current task\n \"\"\"\n self.__checkTasks[agentIdentifier] = task.result()\n\n def __delete(self, agentIdentifier: Tuple[str, str]):\n \"\"\"Deletes the ``Agent`` ``agentIdentifier``.\n\n Args:\n agentIdentifier: Heartbeats of the corresponding Agent to be deleted\n \"\"\"\n with self.__locks[agentIdentifier]:\n self.__removeAgent(agentIdentifier)\n\n @staticmethod\n def computeExpectedArrivalTime(heartbeatWrapper: HeartbeatWrapper, afterNext: bool = False) -> float:\n \"\"\"Computes the expected arrival time of the next Heartbeat for the concerned ``Agent`` of the ``Heartbeats``\n contained in ``heartbeatWrapper``. To calculate the after expected arrival time the argument ``afterNext`` is\n given. It is required if a ``Heartbeat`` doesnt arrive, but the next expected arrival time is needed anyway.\n\n Args:\n heartbeatWrapper: Heartbeats to be used for arrival time calculation\n afterNext: (default=False) Signals that the after next expected arrival time should be calculated\n Returns:\n Agents Heartbeats next expected arrival time\n \"\"\"\n heartbeats = heartbeatWrapper.getHeartbeats()\n receiptTimes = heartbeatWrapper.getReceiptTimes()\n notifyIntervals = heartbeatWrapper.getNotifyIntervals()\n currentNotifyInterval = heartbeatWrapper.getCurrentNotifyInterval()\n nextPoint = 1 if not afterNext else 2\n logging.debug(\"FreshnessCheck: Computes next Heartbeats expected arrival time for '%s' with receiptTimes of %s,\"\n \" notifyIntervals of %s and the currentNotifyInterval %s.\",\n heartbeatWrapper.getAgentIdentifier(), str(receiptTimes),\n str(notifyIntervals), str(currentNotifyInterval))\n\n # If the list only has one heartbeat, use that to calculate the expected arrival time\n if len(heartbeats) == 1:\n expectedArrivalTime = receiptTimes[0] + currentNotifyInterval * nextPoint\n else:\n # Discard the oldest Heartbeat in the list, because his used notify interval is not known. The attribute\n # `currentNotifyInterval` declares the interval that is used from now on to send next Heartbeats.\n # Declare Sum bounds:\n upperBound = len(heartbeats) - 1\n lowerBound = 0\n deviations = []\n sumNotifyIntervals = 0\n # Go backwards trough the list of heartbeats, because its sorted from the newest to the oldest\n for i in range(upperBound - 1, lowerBound - 1, -1):\n # Check if a sequence number (and therefore a Heartbeat) is missing\n diffSequenceNumber = heartbeats[i].sequenceNumber - heartbeats[i+1].sequenceNumber\n # Calculate the sum of the notify intervals of the Heartbeats, contained by the List \"heartbeats\",\n # up to the element i. Use the interval of the previous Heartbeat (i+1), because that indicates the\n # the used one for the current Heartbeat (i)\n sumNotifyIntervals += notifyIntervals[i+1] * diffSequenceNumber\n # Calculate the deviation of the receipt time to the should-receipt time\n item = receiptTimes[i] - sumNotifyIntervals\n deviations.append(item)\n # Sum it up\n totalDeviation = sum(deviations)\n # Compute the average of the total deviation and shift it forward\n expectedArrivalTime = totalDeviation / upperBound \\\n + sumNotifyIntervals + currentNotifyInterval * nextPoint\n return round(expectedArrivalTime, FreshnessCheck.DECIMAL_PLACES)\n\n @staticmethod\n def calculateSlack(heartbeatWrapper: HeartbeatWrapper, lastExpectedArrivalTime: Optional[float]) -> float:\n \"\"\"Calculates the slack for the next freshness point.\n\n Args:\n heartbeatWrapper: Heartbeats to be used for slack calculation\n lastExpectedArrivalTime: The expected arrival time of the last Heartbeat\n Returns:\n Calculated slack\n \"\"\"\n # If the detectionTimeUpperBound is given by the Agent and the current notify interval is also the calculated\n # one, use the detectionTimeUpperBound to calculate the slack\n if heartbeatWrapper.getDetectionTimeUpperBound() is not None \\\n and heartbeatWrapper.getCalculatedNotifyInterval() == heartbeatWrapper.getCurrentNotifyInterval():\n slack = heartbeatWrapper.getDetectionTimeUpperBound() - heartbeatWrapper.getCurrentNotifyInterval()\n else: # Else use a more general slack, calculated with Jacobson’s estimation\n lastArrivalTime = heartbeatWrapper.getReceiptTimes()[0]\n if lastExpectedArrivalTime is None:\n lastExpectedArrivalTime = lastArrivalTime\n logging.debug(\"FreshnessCheck: Computes Jacobson slack for '%s' with a delay of %s and var of %s.\",\n heartbeatWrapper.getAgentIdentifier(), heartbeatWrapper.delay, heartbeatWrapper.var)\n error = lastArrivalTime - lastExpectedArrivalTime - heartbeatWrapper.delay\n heartbeatWrapper.delay += FreshnessCheck.JACOBSON_GAMMA * error\n heartbeatWrapper.var += FreshnessCheck.JACOBSON_GAMMA * (abs(error) - heartbeatWrapper.var)\n slack = FreshnessCheck.JACOBSON_BETA * heartbeatWrapper.delay \\\n + FreshnessCheck.JACOBSON_PHI * heartbeatWrapper.var\n return round(slack, FreshnessCheck.DECIMAL_PLACES)\n\n def isFresh(self, agentIdentifier: Tuple[str, str]) -> bool:\n \"\"\"Checks if a new ``Heartbeat`` for the ``Agent`` ``agentIdentifier`` at the current time would be\n considered as fresh.\n\n Args:\n agentIdentifier: Concerned Agent\n Returns:\n True if the Heartbeat would be fresh, else False\n \"\"\"\n if time() < self.__currentFreshnessPoint.get(agentIdentifier):\n return True # Freshness point isn´t reached yet, so the Heartbeat would be fresh\n return False # Freshness point has been exceeded\n\n def removeAgent(self, agentIdentifier: Tuple[str, str]):\n \"\"\"Removes ``agentIdentifier`` from the internal freshness checks.\n\n Args:\n agentIdentifier: Concerned Agent\n \"\"\"\n\n task = self.__checkTasks.pop(agentIdentifier, None)\n if task is not None:\n task.cancel()\n self.__currentFreshnessPoint.pop(agentIdentifier, None)\n self.__expectedArrivalTime.pop(agentIdentifier, None)\n","sub_path":"src/logic/failureDetector/timing/FreshnessCheck.py","file_name":"FreshnessCheck.py","file_ext":"py","file_size_in_byte":14525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"111489421","text":"import re\nfrom subprocess import check_output\nfrom time import sleep\n\nimport pytest\nimport requests\n\nfrom .utils import get_session, get_pub_addr\n\nTFJOB = \"integration/k8s-jobs/mnist.yaml\"\nSELDONJOB = \"integration/k8s-jobs/serve-simple-v1alpha2.yml\"\n\n\ndef kubectl_create(path: str):\n \"\"\"Creates a Kubernetes resource from the given path.\n\n Uses juju kubectl plugin that introspects model and divines the proper\n kubeconfig.\n \"\"\"\n\n return check_output([\"juju\", \"kubectl\", \"--\", \"create\", \"-f\", path]).strip()\n\n\ndef validate_statuses(model):\n \"\"\"Validates that a known set of units have booted up into the correct state.\"\"\"\n\n expected_units = {\n \"ambassador-auth/0\",\n \"ambassador/0\",\n \"argo-controller/0\",\n \"argo-ui/0\",\n \"jupyter-controller/0\",\n \"jupyter-web/0\",\n \"jupyterhub/0\",\n \"katib-controller/0\",\n \"katib-manager/0\",\n \"katib-db/0\",\n \"katib-ui/0\",\n \"mariadb/0\",\n \"metacontroller/0\",\n \"minio/0\",\n \"modeldb-backend/0\",\n \"modeldb-store/0\",\n \"modeldb-ui/0\",\n \"pipelines-api/0\",\n \"pipelines-dashboard/0\",\n \"pipelines-persistence/0\",\n \"pipelines-scheduledworkflow/0\",\n \"pipelines-ui/0\",\n \"pipelines-viewer/0\",\n \"pytorch-operator/0\",\n \"redis/0\",\n \"seldon-api-frontend/0\",\n \"seldon-cluster-manager/0\",\n \"tensorboard/0\",\n \"tf-job-dashboard/0\",\n \"tf-job-operator/0\",\n }\n\n assert set(model.units.keys()) == expected_units\n\n for name, unit in model.units.items():\n assert unit.agent_status == \"idle\"\n assert unit.workload_status == \"active\"\n assert unit.workload_status_message in (\"\", \"ready\")\n\n\ndef validate_ambassador():\n \"\"\"Validates that the ambassador is up and responding.\"\"\"\n\n checks = {\n \"/ambassador/v0/check_ready\": b\"ambassador readiness check OK\",\n \"/ambassador/v0/check_alive\": b\"ambassador liveness check OK\",\n }\n\n sess = get_session()\n\n for endpoint, text in checks.items():\n resp = sess.get(f\"http://{get_pub_addr()}{endpoint}\")\n assert resp.content.startswith(text)\n\n\ndef validate_jupyterhub_api():\n \"\"\"Validates that JupyterHub is up and responding via Ambassador.\"\"\"\n\n sess = get_session()\n\n resp = sess.get(f\"http://{get_pub_addr()}/hub/api/\")\n assert list(resp.json().keys()) == [\"version\"]\n\n\ndef validate_tf_dashboard():\n \"\"\"Validates that TF Jobs dashboard is up and responding via Ambassador.\"\"\"\n\n sess = get_session()\n\n output = kubectl_create(TFJOB)\n\n assert re.match(rb\"tfjob.kubeflow.org/mnist-test-[a-z0-9]{5} created$\", output) is not None\n\n expected_jobs = [(\"PS\", 1), (\"Worker\", 1)]\n expected_conditions = [\n (\"Created\", \"True\", \"TFJobCreated\"),\n (\"Running\", \"False\", \"TFJobRunning\"),\n (\"Succeeded\", \"True\", \"TFJobSucceeded\"),\n ]\n expected_statuses = {\"PS\": {\"succeeded\": 1}, \"Worker\": {\"succeeded\": 1}}\n\n # Wait for up to 5 minutes for the job to complete,\n # checking every 5 seconds\n for i in range(60):\n resp = sess.get(f\"http://{get_pub_addr()}/tfjobs/api/tfjob/\")\n response = resp.json()[\"items\"][0]\n\n jobs = [\n (name, spec[\"replicas\"]) for name, spec in response[\"spec\"][\"tfReplicaSpecs\"].items()\n ]\n\n conditions = [\n (cond[\"type\"], cond[\"status\"], cond[\"reason\"])\n for cond in response[\"status\"][\"conditions\"] or []\n ]\n\n statuses = response[\"status\"][\"replicaStatuses\"]\n\n try:\n assert jobs == expected_jobs\n assert conditions == expected_conditions\n assert expected_statuses == statuses\n break\n except AssertionError as err:\n print(\"Waiting for TFJob to complete...\")\n print(err)\n sleep(5)\n else:\n pytest.fail(\"Waited too long for TFJob to succeed!\")\n\n\ndef validate_seldon():\n sess = get_session()\n\n output = kubectl_create(SELDONJOB)\n\n assert output == b\"seldondeployment.machinelearning.seldon.io/mock-classifier created\"\n\n for i in range(60):\n try:\n resp = sess.get(f\"http://{get_pub_addr()}/seldon/mock-classifier/\")\n resp.raise_for_status()\n assert resp.text == \"Hello World!!\"\n break\n except (AssertionError, requests.HTTPError) as err:\n print(\"Waiting for SeldonDeployment to start...\")\n print(err)\n sleep(5)\n else:\n pytest.fail(\"Waited too long for SeldonDeployment to start!\")\n","sub_path":"tests/test_kubeflow.py","file_name":"test_kubeflow.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"627567733","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 21 12:01:44 2020\n\n@author: rguil\n\"\"\"\n\nimport cold_pulses.pulse_detection as detect\nimport os\n\nlist_dirs = os.listdir()\nif 'NCEP-GODAS_ocean-temp_1980-2020.nc' not in list_dirs:\n print('NCEP-GODAS climatology file, please download it first.')\n print('If you have downloaded it, move it to the current working directory.')\n print(\"If it is in the current directory, rename it it 'NCEP-GODAS_ocean-temp_1980-2020.nc'\")\n\nelse:\n list_dirs.remove('processing_TSI.py')\n list_dirs.remove('NCEP-GODAS_ocean-temp_1980-2020.nc')\n\n for dir_name in list_dirs:\n if dir_name[-3:]!='out' and dir_name[0] != '.' and dir_name!='desktop.ini':\n print(dir_name)\n detect.upwelling_cold_pulses_detection(dir_name,auto_in=True,ignore_double=True)\n \n","sub_path":"processing_TSI.py","file_name":"processing_TSI.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"444585494","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nhttps://leetcode.com/problems/course-schedule/description/\n\nThere are a total of n courses you have to take, labeled from 0 to n - 1.\n\nSome courses may have prerequisites,\nfor example to take course 0 you have to first take course 1,\nwhich is expressed as a pair: [0,1]\n\nGiven the total number of courses and a list of prerequisite pairs,\nis it possible for you to finish all courses?\n\nFor example:\n2, [[1,0]]\nThere are a total of 2 courses to take.\nTo take course 1 you should have finished course 0. So it is possible.\n\n2, [[1,0],[0,1]]\nThere are a total of 2 courses to take.\nTo take course 1 you should have finished course 0,\nand to take course 0 you should also have finished course 1.\nSo it is impossible.\n\nNote:\nThe input prerequisites is a graph represented by a list of edges,\nnot adjacency matrices. Read more about how a graph is represented.\n\nYou may assume that there are no duplicate edges in the input prerequisites.\n\"\"\"\n\n\nclass Solution(object):\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n if numCourses and not prerequisites:\n return True\n\n if not numCourses:\n return False\n\n # build graph\n dmap = dict()\n\n courses = set(i for i in range(numCourses))\n\n for p in prerequisites:\n if p[0] < 0 or p[1] < 0 or p[0] >= numCourses or p[1] >= numCourses:\n return False\n\n if not dmap.get(p[1]):\n dmap[p[1]] = []\n\n dmap[p[1]].append(p[0])\n\n # if circle, can't finish courses.\n # use visited to avoid duplicated visit.\n visited = set()\n\n def dfs(node, cir):\n \"\"\"\n Use dfs to check circle.\n \"\"\"\n if node in cir:\n return False\n\n if node in visited:\n return True\n\n visited.add(node)\n cir.add(node)\n\n for n in dmap.get(node, []):\n if not dfs(n, cir):\n return False\n\n cir.remove(node)\n\n return True\n\n for n in courses:\n if n in dmap:\n cir = set()\n\n if not dfs(n, cir):\n return False\n\n return True\n\n\ndef build():\n return 5, [[1, 0], [2, 0], [3, 0], [3, 1], [0, 1]]\n return 8, [[1, 0], [2, 6], [1, 7], [6, 4], [7, 0], [0, 5]]\n return 2, [[1, 0], [0, 1]]\n return 5, [[1, 0], [2, 0], [3, 0], [3, 1]]\n return 2, [[1, 0]]\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.canFinish(*build()))\n","sub_path":"co_fb/207_Course_Schedule.py","file_name":"207_Course_Schedule.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"550829561","text":"from tkinter import *\nimport tkinter.ttk as ttk\nimport serial as ser\nimport serial.tools.list_ports\nimport line_compute_time\nimport math\n\n\nclass SerialConnection:\n\n def __init__(self, master):\n self.ports = serial.tools.list_ports.comports()\n self.portlist = []\n for self.p in self.ports:\n print(self.p.device)\n self.portlist.append(str(self.p.device))\n\n serframe = Frame(master)\n serframe.grid(column=0, row=0)\n\n self.lbl_srl = Label(serframe, text=\"Serial Port:\", font=(\"Arial\", 8))\n self.lbl_srl.grid(column=0, row=0)\n\n self.combo = ttk.Combobox(serframe, values=self.portlist)\n self.combo.current(0)\n self.combo.grid(column=1, row=0)\n\n self.btn_connect = Button(serframe, text=\"Connect\", command=self.clickedConnectSrl, font=(\"Arial\", 8))\n self.btn_connect.grid(column=2, row=0)\n\n self.lbl_PortConnect = Label(serframe, font=(\"Arial\", 8))\n self.lbl_PortConnect.grid(columnspan=3)\n\n def clickedConnectSrl(self):\n if self.btn_connect['text']==\"Connect\":\n global arduinosrl\n arduinosrl = ser.Serial(self.combo.get(), 9600)\n self.lbl_PortConnect.configure(text=\"Connected to \" + self.combo.get())\n self.btn_connect.configure(text=\"Disconnect\")\n else:\n arduinosrl.close()\n self.btn_connect.configure(text=\"Connect\")\n self.lbl_PortConnect.configure(text=\"Disconnected\")\n\n\nclass PointtoPoint:\n\n def __init__(self, master, scaramotor, serial1):\n\n frame_coord = Frame(master)\n frame_coord.grid(column=0, row=1)\n\n self.lbl_x_coord = Label(frame_coord, text=\"X COORDINATE (mm): \", font=(\"Arial\", 8))\n self.lbl_x_coord.grid(column=0, row=0, sticky=W)\n\n self.ent_x_coord = Entry(frame_coord, width=10)\n self.ent_x_coord.grid(column=1, row=0)\n self.ent_x_coord.focus()\n\n self.lbl_y_coord = Label(frame_coord, text=\"Y COORDINATE (mm): \", font=(\"Arial\", 8))\n self.lbl_y_coord.grid(column=0, row=1, sticky=W)\n\n self.ent_y_coord = Entry(frame_coord, width=10)\n self.ent_y_coord.grid(column=1, row=1)\n\n self.btn_compute = Button(frame_coord, text=\"Compute\", command=self.clickedComputeA, font=(\"Arial\", 8))\n self.btn_compute.grid(column=2, row=0, rowspan=2, sticky=W+N+S)\n\n self.lbl_coordmes = Label(frame_coord, font=(\"Arial\", 8), fg='red')\n self.lbl_coordmes.grid(column=0, row=2, columnspan=3, sticky=W)\n\n frame_angle = Frame(window)\n frame_angle.grid(column=1, row=1, sticky=N)\n\n self.lbl_angle_1 = Label(frame_angle, text=\"ANGLE 1 (deg): \", font=(\"Arial\", 8))\n self.lbl_angle_1.grid(column=0, row=0, sticky=W)\n\n self.ent_angle_1 = Entry(frame_angle, width=10)\n self.ent_angle_1.grid(column=1, row=0)\n\n self.lbl_angle_2 = Label(frame_angle, text=\"ANGLE 2 (deg): \", font=(\"Arial\", 8))\n self.lbl_angle_2.grid(column=0, row=1, sticky=W)\n\n self.ent_angle_2 = Entry(frame_angle, width=10)\n self.ent_angle_2.grid(column=1, row=1)\n\n self.btn_send_angle = Button(frame_angle, text=\" Send \", command=lambda: self.clickedSendAngle(scaramotor), font=(\"Arial\", 8))\n self.btn_send_angle.grid(column=2, row=0, rowspan=2, sticky=W+N+S)\n\n def clickedComputeA(self):\n if self.__is_float(self.ent_x_coord.get()) and self.__is_float(self.ent_y_coord.get()):\n pos = [float(self.ent_x_coord.get()), float(self.ent_y_coord.get())]\n self.lbl_coordmes.configure(text=str(pos))\n try:\n angle = line_compute_time.find_angles(pos)\n self.ent_angle_1.insert(0, str(angle[0]))\n self.ent_angle_2.insert(0, str(angle[1]))\n except ValueError:\n self.lbl_coordmes.configure(text=\"Out of bounds\")\n else:\n self.lbl_coordmes.configure(text=\"This is not a float\")\n print(\"wha\")\n\n def clickedSendAngle(self, scaramotor):\n current_angles = scaramotor.getAngle()\n try:\n gotoangle = [float(self.ent_angle_1.get()), float(self.ent_angle_2.get())]\n steps = [self.__steps_to_go(current_angles[0],gotoangle[0],scaramotor.getReso()[0]), self.__steps_to_go(current_angles[1],gotoangle[1],scaramotor.getReso()[1])]\n direc = self.__find_dir(current_angles, gotoangle)\n scaramotor.updateAngle(\n [current_angles[0] + scaramotor.steps_to_angle(steps[0], direc[0], scaramotor.getReso()[0]),\n current_angles[1] + scaramotor.steps_to_angle(steps[1], direc[1], scaramotor.getReso()[1])])\n except ValueError:\n print(\"ErrorAngle\")\n #print(scaramotor.getAngle())\n\n def __is_float(self, num):\n try:\n float(num)\n return True\n except ValueError:\n return False\n\n def __steps_to_go(self, angle_in, angle_fin, reso):\n return int(abs(angle_fin-angle_in)//reso)\n\n def __find_dir(self, cur_angles, gotoangle):\n direction = [0, 0]\n if gotoangle[0] >= cur_angles[0]:\n direction[0] = 1\n else:\n direction[0] = 0\n if gotoangle[1] >= cur_angles[1]:\n direction[1] = 1\n else:\n direction[1] = 0\n return direction\n\n\n\n\nclass ScaraMotors:\n\n def __init__(self, angle_init):\n self.angle_cur = angle_init\n self.resolution = [2*math.pi/200/3.70588235/8, 2*math.pi/400/2/8]\n\n def updateAngle(self, angle_updated):\n self.angle_cur = angle_updated\n\n def getAngle(self):\n return self.angle_cur\n\n def getReso(self):\n return self.resolution\n\n def steps_to_angle(self, steps, dir, reso):\n if dir:\n return steps*reso\n else:\n return -steps*reso\n\n\nwindow = Tk()\nwindow.title(\"SCARA GUI\")\n#window.geometry(\"350x250\")\nangle_in = [0,0]\nscaramotor1 = ScaraMotors(angle_in)\nserial1 = SerialConnection(window)\npointtopoint = PointtoPoint(window,scaramotor1, serial1)\nwindow.mainloop()","sub_path":"scara_gui.py","file_name":"scara_gui.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"349166659","text":"# Routine to average Rayleigh Meridional_Slices ENSTROPHY data in time\n# Created by: Loren Matilsky\n# On: 04/10/2019\n##################################################################\n# This routine computes the average in time of the ENSTROPHY values in the\n# Meridional_Slices data for a particular simulation. \n\n# By default, the routine averages over the last 100 files of datadir, though\n# the user can specify a different range in sevaral ways:\n# -n 10 (last 10 files)\n# -range iter1 iter2 (names of start and stop data files; \n# names can also be \"first\" or \"last\")\n# -centerrange iter0 nfiles (average about central file iter0 over nfiles)\n\n# Import relevant modules\nimport numpy as np\nimport pickle\nimport sys, os\nsys.path.append(os.environ['rapp'])\nsys.path.append(os.environ['raco'])\nfrom rayleigh_diagnostics import Meridional_Slices\nfrom common import *\n\n# Get the name of the run directory\ndirname = sys.argv[1]\n# Get the stripped name to use in file naming\ndirname_stripped = strip_dirname(dirname)\n\n# Find the relevant place to store the data, and create the directory if it\n# doesn't already exist\ndatadir = dirname + '/data/'\nif (not os.path.isdir(datadir)):\n os.makedirs(datadir)\n\nradatadir = dirname + '/Meridional_Slices/'\n\n# Get all the file names in datadir and their integer counterparts\nfile_list, int_file_list, nfiles = get_file_lists(radatadir)\n\n# Read in CLAs\nargs = sys.argv[2:]\nnargs = len(args)\n\nif (nargs == 0):\n index_first, index_last = nfiles - 101, nfiles - 1 \n # By default average over the last 100 files\nelse:\n index_first, index_last = get_desired_range(int_file_list, args)\n\n# Set the timeavg savename by the directory, what we are saving, and first and last\n# iteration files for the average\nsavename = dirname_stripped + '_enstrophy_from_mer_' +\\\n file_list[index_first] + '_' + file_list[index_last] + '.pkl'\nsavefile = datadir + savename \n\n# Get grid info from first mer slice file\nmer0 = Meridional_Slices(radatadir + file_list[index_first], '')\nrr = mer0.radius\nri, ro = np.min(rr), np.max(rr)\nd = ro - ri\nrr_depth = (ro - rr)/d\nrr_height = (rr - ri)/d\nsint = mer0.sintheta\ncost = mer0.costheta\ntt = np.arccos(cost)\ntt_lat = (np.pi/2 - tt)*180/np.pi\nnr = mer0.nr\nnt = mer0.ntheta\nphivals = mer0.phi\n# phiinds = mer0.phi_indices \n# This attribute of Meridional_Slices does not actually seem to be there!\nnphi = mer0.nphi\nphivals_lon = 180*phivals/np.pi\n# compute some derivative quantities for the grid\ntt_2d, rr_2d = np.meshgrid(tt, rr, indexing='ij')\nsint_2d = np.sin(tt_2d); cost_2d = np.cos(tt_2d)\nxx = rr_2d*sint_2d\nzz = rr_2d*cost_2d\n\n# Initialize the count (will rise as the averaging commences)\ncount = 0\niter1, iter2 = int_file_list[index_first], int_file_list[index_last]\n\n# Initialize empty \"vals\" array for the time average\nvals = np.zeros((nphi, nt, nr, 3))\n\n# Average over the relevant data range, summing everything and then dividing\n# by the number of \"slices\" added at the end\nprint ('Considering Meridional_Slices files %s through %s for the average ...'\\\n %(file_list[index_first], file_list[index_last]))\nfor i in range(index_first, index_last + 1):\n print ('Adding Meridional_Slices/%s to the average ...' %file_list[i])\n if i == index_first:\n mer = mer0\n else: \n mer = Meridional_Slices(radatadir + file_list[i], '')\n\n local_ntimes = mer.niter\n for j in range(local_ntimes):\n vals += (mer.vals[:, :, :,\\\n [mer.lut[301], mer.lut[302], mer.lut[303]], j])**2\n count += 1\n\nvals /= count\nprint ('Averaged over %i Meridional_Slices ...' %count)\n\n# Save the avarage\nprint ('Saving file at ' + savefile + ' ...')\nf = open(savefile, 'wb')\npickle.dump({'vals': vals, 'lut': mer0.lut, 'count': count, 'iter1': iter1, 'iter2': iter2, 'phivals': phivals, 'phivals_lon': phivals_lon, 'nphi': nphi, 'rr': rr, 'rr_depth': rr_depth, 'rr_height': rr_height, 'nr': nr, 'ri': ri, 'ro': ro, 'd': d, 'tt': tt, 'tt_lat': tt_lat, 'sint': sint, 'cost': cost,'nt': nt, 'rr_2d': rr_2d, 'tt_2d': tt_2d, 'sint_2d': sint_2d, 'cost_2d': cost_2d, 'xx': xx, 'zz': zz}, f, protocol=4)\nf.close()\n","sub_path":"zz_legacy/enstrophy_from_mer.py","file_name":"enstrophy_from_mer.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"121973764","text":"#! python\nfrom tkinter import *\nfrom random import randint\n# TO DO\n# if win => replace labels with WIN! label\n# make attempt variable work\n#globals\npossibleColors = [\"yellow\", \"red\", \"blue\", \"green\"] # can be altered\npossiblePositions = 4\n\n\ndef createHidden(possibleColors = possibleColors, possiblePositions\\\n = possiblePositions):\n hidden = {}\n for x in range(1,possiblePositions+1):# 1:n+1 för att visa 1 : yellow etc\n hidden[x] = possibleColors[randint(0,possiblePositions-1)]\n return hidden\n\n#main\nhidden = createHidden()\n\nmaster = Tk()\nmaster.geometry(\"600x250\")\nmaster.title(\"The Color Game\")\n# Instructions\ninstructions = Label(master, text=\"In how many attempts can you guess\\nwhich color\\\n is in which position? :D\", font=(\"Arial\",15))\ninstructions.grid(columnspan=8, sticky=W)\n# the 4 choices / buttons\nchoiceOne = StringVar()\nchoiceOne.set(possibleColors[0])\nmenuOne = OptionMenu(master, choiceOne, *possibleColors)\nmenuOne.grid(row=2,column=0,padx=1,sticky=E)\n\nchoiceTwo = StringVar()\nchoiceTwo.set(possibleColors[0])\nmenuTwo = OptionMenu(master, choiceTwo, *possibleColors)\nmenuTwo.grid(row=2,column=1,padx=1,sticky=W)\n \nchoiceThree = StringVar()\nchoiceThree.set(possibleColors[0])\nmenuThree = OptionMenu(master, choiceThree, *possibleColors)\nmenuThree.grid(row=2,column=2,padx=1,sticky=W)\n\nchoiceFour = StringVar()\nchoiceFour.set(possibleColors[0])\nmenuFour = OptionMenu(master, choiceFour, *possibleColors)\nmenuFour.grid(row=2,column=3,padx=1, sticky=W)\nattempts=0\nsubmitButton = Button(master, text=\"Submit\", command=\\\n lambda: doThings(choiceOne.get(), choiceTwo.get(),\\\n choiceThree.get(),\\\n choiceFour.get(), attempts=attempts))\nsubmitButton.grid(row=2,column=4,padx=5)\n \ndef getuserInput(choiceOne, choiceTwo, choiceThree, choiceFour):\n userInput = {\n 1 : choiceOne,\n 2 : choiceTwo,\n 3 : choiceThree,\n 4 : choiceFour\n }\n return userInput\ndef comparison(attempts, userInput, hidden, possibleColors = possibleColors,\\\n possiblePositions = possiblePositions):\n correctPositions = 0\n correctColors = 0\n if userInput == hidden:\n print(\"YOU WON!\")\n return\n # for loop that checks if correct position and color for each spot\n for x in range(1, possiblePositions+1):\n if userInput[x] == hidden[x]:\n correctPositions += 1\n # for loop that checks amount of correct colors\n temporär_user = []\n temporär_hidden = []\n #test\n count1 = 0\n count2 = 0\n temporär_lista = []\n for x in userInput:\n #test 2\n temporär_user.append(userInput[x]) # lista av färgval\n temporär_hidden.append(hidden[x]) # lista av färgval\n for x in temporär_user: # räkna ut hur många av en färg som är i hidden\n if x in temporär_hidden:\n if x not in temporär_lista: #only takes values that we have yet to use\n # ta count och lägg till\n count1 = temporär_user.count(x)\n count2 = temporär_hidden.count(x)\n # if statements för count\n if count1 > count2:\n correctColors += count2\n if count2 > count1:\n correctColors += count1\n if count1 == count2:\n correctColors += count1\n temporär_lista.append(x)\n # end test\n else:\n label_1 = Label(master, text=\"Correct Positions: %s Correct Colors: %s\"\\\n % (correctPositions, correctColors)).grid(row=4,column=0,columnspan=8,sticky=W)\n label_2 = Label(master, text=\"Number of attempts: %s\" % (attempts)).grid(row=5)\n\ndef doThings(choiceOne, choiceTwo, choiceThree, choiceFour,attempts):\n attempts += 1\n userInput = getuserInput(choiceOne, choiceTwo, choiceThree, choiceFour)\n #jämföra\n comparison(attempts, userInput=userInput, hidden=hidden, possibleColors = possibleColors,\\\n possiblePositions = possiblePositions)\n #label med attempts, correct colors och correct positions\n\n \nmaster.mainloop()\n\n\"\"\"\nwidget.config(bg='green',fg='black',\nactivebackground='green',\nactiveforeground='black')\n\"\"\"\n \n","sub_path":"python/old/colorGame2.py","file_name":"colorGame2.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"133812878","text":"# coding: utf-8\n# Copyright 2017 video++ Project, SJTU MediaLab\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.\nimport time\n\nfrom vpp import log\nfrom vpp.config import CONF\nfrom vpp.queue import running_queue\nfrom vpp.operator import BASE_WORK_DIR\nfrom vpp.tracker.job_tracker import JobTracker\n\n\n# use __name__ as logger name here will lead all other loggers in files of\n# this folder logging each log 2 times, so we add some suffix to it\n_logger_name = __name__ + '_any_string'\nLOG = log.get_logger(_logger_name, CONF.jobtracker_log_file)\n\n\ndef run_tracker():\n \"\"\"periodically checks on-running job status, download and merge the\n results when a job is done\n \"\"\"\n LOOP_INTERVAL = CONF.jobtracker.loop_interval\n job_tracker = JobTracker(BASE_WORK_DIR)\n\n iterations = 0\n while True:\n if iterations % 60 == 0:\n LOG.info(\"tracker iterations: %d\" % iterations)\n iterations += 1\n\n job_ids = running_queue.keys()\n if len(job_ids) == 0:\n time.sleep(1)\n continue\n\n for job_id in job_ids:\n job_tracker.track_job(job_id)\n\n time.sleep(LOOP_INTERVAL)\n","sub_path":"vpp/tracker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"39472171","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 15 01:12:02 2020\n\n@author: kuangmeng\n\"\"\"\n\nfrom tensorflow.keras.layers import Concatenate, LeakyReLU, Conv3D, LSTM, Reshape, UpSampling3D, Input, BatchNormalization, MaxPooling3D, Multiply\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nimport os\nimport tensorflow as tf\nimport sys\nsys.path.append(\".\")\nfrom .modules.losses import Loss\nfrom .modules.metrics import Metric\nstrategy = tf.distribute.MirroredStrategy()\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nclass CUBE_UNet3D:\n def __init__(self, input_shape, n_classes = 2, loss = None, metric = None, pretrained_weights = None):\n self.input_shape = input_shape\n self.layers = input_shape[0]\n self.size = input_shape[1] * input_shape[2]\n self.width = input_shape[1]\n self.height = input_shape[2]\n self.channels = input_shape[3]\n self.n_classes = n_classes\n self.pretrained_weights = pretrained_weights\n with strategy.scope():\n self.model = self.structure()\n self.model.compile(optimizer = Adam(lr = 1e-5), \n loss = Loss(loss).loss, \n metrics = [Metric(metric).metric])\n \n def LSTMLayer(self, input_tensor):\n old_shape = input_tensor.shape\n new_shape = (old_shape[1], old_shape[2] * old_shape[3] * old_shape[4])\n ret_shape = (old_shape[1], old_shape[2], old_shape[3], 1)\n tmp = Reshape(new_shape)(input_tensor)\n whole_seq_output, final_memory_state, final_carry_state = LSTM(old_shape[2] * old_shape[3], return_sequences=True, return_state=True)(tmp)\n return Reshape(ret_shape)(whole_seq_output)\n\n def Atten(self, input_tensor):\n cnn_layer = Conv3D(filters = input_tensor.shape[-1], kernel_size= (1, 3, 3), padding='same')\n query_encoding = cnn_layer(input_tensor)\n key_encoding = cnn_layer(input_tensor)\n query_value_attention = cnn_layer(Multiply()([query_encoding, key_encoding]))\n attention_score = tf.keras.activations.softmax(query_value_attention, axis = -1)\n return Multiply()([key_encoding, attention_score])\n\n def cube_structure(self, input_tensor):\n out1 = self.LSTMLayer(input_tensor)\n out2 = self.Atten(input_tensor)\n return Multiply()([out1, out2])\n\n def structure(self):\n inputs = Input(self.input_shape)\n conv1 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 32)(inputs)\n conv1 = BatchNormalization()(conv1)\n conv1 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 64)(conv1)\n conv1 = BatchNormalization()(conv1)\n meg1 = LeakyReLU()(conv1)\n conv1 = MaxPooling3D(pool_size=(1, 2, 2))(meg1)\n conv2 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 64)(conv1)\n conv2 = BatchNormalization()(conv2)\n conv2 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 128)(conv2)\n conv2 = BatchNormalization()(conv2)\n meg2 = LeakyReLU()(conv2)\n conv2 = MaxPooling3D(pool_size=(1, 2, 2))(meg2)\n conv3 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 128)(conv2)\n conv3 = BatchNormalization()(conv3)\n conv3 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 256)(conv3)\n conv3 = BatchNormalization()(conv3)\n meg3 = LeakyReLU()(conv3)\n conv3 = MaxPooling3D(pool_size=(1, 2, 2))(meg3)\n conv4 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 256)(conv3)\n conv4 = BatchNormalization()(conv4)\n conv4 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 512)(conv4)\n conv4 = BatchNormalization()(conv4)\n meg4 = LeakyReLU()(conv4)\n meg4 = self.cube_structure(meg4)\n conv4 = MaxPooling3D(pool_size=(1, 2, 2))(meg4)\n flat = Conv3D(kernel_size = (1, 1, 1), padding = 'same', filters = 512)(conv4)\n flat = self.cube_structure(flat)\n up1 = UpSampling3D(size = (1, 2, 2))(flat)\n meg4 = self.Atten(meg4)\n up1 = Concatenate(axis = -1)([meg4,up1])\n up1 = Conv3D(kernel_size = (1, 1, 1), padding = 'same', filters = 512)(up1)\n up1 = self.cube_structure(up)\n up1 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 256)(up1)\n up1 = BatchNormalization()(up1)\n up1 = self.LSTMLayer(up1)\n up1 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 256)(up1)\n up1 = BatchNormalization()(up1)\n up1 = LeakyReLU()(up1)\n up2 = UpSampling3D(size = (1, 2, 2))(up1)\n meg3 = self.Atten(meg3)\n up2 = Concatenate(axis = -1)([meg3,up2])\n up2 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 128)(up2)\n up2 = BatchNormalization()(up2)\n up2 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 128)(up2)\n up2 = BatchNormalization()(up2)\n up2 = LeakyReLU()(up2)\n up3 = UpSampling3D(size = (1, 2, 2))(up2)\n meg2 = self.Atten(meg2)\n up3 = Concatenate(axis = -1)([meg2, up3])\n up3 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 64)(up3)\n up3 = BatchNormalization()(up3)\n up3 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 64)(up3)\n up3 = BatchNormalization()(up3)\n up3 = LeakyReLU()(up3)\n up4 = UpSampling3D(size = (1, 2, 2))(up3)\n meg1 = self.Atten(meg1)\n up4 = Concatenate(axis = -1)([meg1, up4])\n up4 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 32)(up4)\n up4 = BatchNormalization()(up4)\n up4 = Conv3D(kernel_size = (3, 3, 3), padding = 'same', filters = 32)(up4)\n up4 = BatchNormalization()(up4)\n up4 = LeakyReLU()(up4)\n up5 = Conv3D(kernel_size = (1, 1, 1), padding = 'same', filters = self.n_classes)(up4)\n outputs = tf.keras.layers.Softmax(axis=-1)(up5)\n model = Model(inputs, outputs)\n model.summary()\n if(self.pretrained_weights):\n \t model.load_weights(self.pretrained_weights)\n return model\n","sub_path":"mriutils/models/cube_unet3d.py","file_name":"cube_unet3d.py","file_ext":"py","file_size_in_byte":6153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"286066719","text":"import pyuff\nimport numpy as np\n\ndef anlyze_UFF(path):\n \"\"\"anlyze_UFF\n\n function reads UFF, and prepare returns. Return are prepered for further procesing. \n\n Parameters\n ----------\n path : string\n paht of chosen UFF file you want to analyze\n\n Returns\n -------\n file: UFF class element\n UFF class element - file prepared for further usage\n uffdic: {'151':...,'15':...,...} python dictonary\n dictonary with indices of included uff datasets (file.get_sets())\n model: ({'name':..., 'descript':...,'index': i},...) array like\n array of dictonaries with name, description of model and index of native dataset\n nodes: ({'n':[x[n],y[n],z[n]],....,'index': i},...) array like\n array of dictoraries with coordinates of nodes and index of native dataset\n lines: ({'trace':number,'nodes':np.array(.....),'index': i},...) array like\n array of dictonaries with trance lines and theri nodes\n trans_matrix: ({'n': trans. matrix,....,'index': i},...) array like\n array of dictoraries with transformation matrix of local coordinate sistems in nodes and index of native dataset\n dic55: {'2':....,'3':....,....} python dictonary\n dictonary with indices of dataset type 55 refer to used analyses type\n at pyuff supported:\n '2' - norma mode\n '3' - complex eigenvalue first order (displacement)\n '5' - frequency response\n '7' - complex eigenvalue second order (velocity)\n dic58: {'1':....,'2':....,....} python dictonary\n dictonary with indices of dataset type 58 refer to used function type\n at pyuff supported:\n '0' - General or Unknown\n '1' - Time Response\n '2' - Auto Spectrum\n '3' - Cross Spectrum\n '4' - Frequency Response Function\n '6' - Coherence\n \"\"\"\n \n file = pyuff.UFF(path)\n sets = file.get_set_types()\n sup_sets = file.get_supported_sets()\n\n uffdic = {}\n for a in sup_sets:\n index = []\n for i in range(len(sets)):\n if str(int(sets[i])) == a:\n index.append(i)\n uffdic[a] = index\n\n keys_58 = ['0', '1', '2', '3', '4', '6']\n keys_55 = ['2', '3', '5', '7']\n dic58 = {}\n dic55 = {}\n lines = []\n model = []\n nodes = []\n trans_matrix = []\n\n for key in keys_55:\n index = []\n for i in uffdic['55']:\n f_typ = file.read_sets(i)['analysis_type']\n if str(f_typ) == key:\n index.append(i)\n dic55[key] = index\n\n for key in keys_58:\n index = []\n for i in uffdic['58']:\n f_typ = file.read_sets(i)['func_type']\n if str(f_typ) == key:\n index.append(i)\n dic58[key] = index\n\n for i in uffdic['151']:\n model.append({'name': file.read_sets(i)['model_name'], 'description': file.read_sets(i)['description'],'index': i})\n\n for i in uffdic['15']:\n dic = {}\n no = file.read_sets(i)['node_nums']\n x = file.read_sets(i)['x']\n y = file.read_sets(i)['y']\n z = file.read_sets(i)['z']\n for n in range(len(no)):\n dic[str(int(no[n]))] = [x[n],y[n],z[n]]\n dic['index'] = i\n nodes.append(dic)\n\n for i in uffdic['82']:\n dic = {}\n dic['trace'] = file.read_sets(i)['trace_num']\n dic['nodes'] = file.read_sets(i)['nodes']\n dic['index'] = i\n lines.append(dic)\n\n for i in uffdic['2420']:\n dic = {}\n no = file.read_sets(i)['CS_sys_labels']\n tm = file.read_sets(i)['CS_matrices']\n for n in range(len(no)):\n dic[str(int(no[n]))] = tm[n]\n dic['index'] = i\n trans_matrix.append(dic)\n\n def cleanup(dic):\n \n re_keys = []\n for key in dic.keys():\n if dic[key] == []:\n re_keys.append(key)\n for key in re_keys:\n del dic[key]\n return dic\n\n uffdic=cleanup(uffdic)\n dic55=cleanup(dic55)\n dic58=cleanup(dic58)\n\n return file,uffdic,model,nodes,lines,trans_matrix,dic55,dic58\n ","sub_path":"iPyUFFviz/analyze_UFF.py","file_name":"analyze_UFF.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"52607770","text":"#\n# @lc app=leetcode id=207 lang=python3\n#\n# [207] Course Schedule\n#\n# https://leetcode.com/problems/course-schedule/description/\n#\n# algorithms\n# Medium (37.46%)\n# Likes: 1718\n# Dislikes: 83\n# Total Accepted: 213.4K\n# Total Submissions: 565.4K\n# Testcase Example: '2\\n[[1,0]]'\n#\n# There are a total of n courses you have to take, labeled from 0 to n-1.\n# \n# Some courses may have prerequisites, for example to take course 0 you have to\n# first take course 1, which is expressed as a pair: [0,1]\n# \n# Given the total number of courses and a list of prerequisite pairs, is it\n# possible for you to finish all courses?\n# \n# Example 1:\n# \n# \n# Input: 2, [[1,0]] \n# Output: true\n# Explanation: There are a total of 2 courses to take. \n# To take course 1 you should have finished course 0. So it is possible.\n# \n# Example 2:\n# \n# \n# Input: 2, [[1,0],[0,1]]\n# Output: false\n# Explanation: There are a total of 2 courses to take. \n# To take course 1 you should have finished course 0, and to take course 0 you\n# should\n# also have finished course 1. So it is impossible.\n# \n# \n# Note:\n# \n# \n# The input prerequisites is a graph represented by a list of edges, not\n# adjacency matrices. Read more about how a graph is represented.\n# You may assume that there are no duplicate edges in the input prerequisites.\n# \n# \n#\nclass Solution:\n # My solution\n # Time Limit Exceeded\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n adj = dict()\n for c1, c2 in prerequisites:\n adj[c1] = adj.get(c1, []) + [c2]\n \n for c in adj:\n visited = []\n self.dfs(c, adj, visited)\n if c in visited:\n return False\n return True\n\n def dfs(self, start, graph, visited):\n for c in graph.get(start, []):\n if c not in visited:\n visited.append(c)\n self.dfs(c, graph, visited)\n\n # Most-voted solution\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n graph = [[] for _ in range(numCourses)]\n visited = [0 for _ in range(numCourses)]\n for x, y in prerequisites:\n graph[x].append(y)\n def dfs(i):\n if visited[i] == -1:\n return False\n if visited[i] == 1:\n return True\n visited[i] = -1\n for j in graph[i]:\n if not dfs(j):\n return False\n visited[i] = 1\n return True\n for i in range(numCourses):\n if not dfs(i):\n return False\n return True\n\n","sub_path":"207.course-schedule.py","file_name":"207.course-schedule.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"226165194","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Manually encrypt a message for WEP \"\"\"\n\n__author__ = \"Nemanja Pantic et David Simeonovic\"\n\nfrom scapy.all import *\nimport binascii\nfrom rc4 import RC4\nimport zlib\nimport struct\n\n# Cle wep AA:AA:AA:AA:AA\nkey= b'\\xaa\\xaa\\xaa\\xaa\\xaa'\n\n# Lecture de message chiffré - rdpcap retourne toujours un array, même si la capture contient un seul paquet\narp = rdpcap('arp.cap')[0] \n\n# Données à envoyer\ndata = ['123456'*6, 'abcdef'*6, 'zoulou'*6]\n\n# rc4 seed est composé de IV+clé\nseed = arp.iv+key\n\n# Initialisation de RC4\ncipher = RC4(seed, streaming=False)\n\n# Liste contenant nos paquets\npktList = []\n\nfor i in range(3):\n pkt = arp.copy()\n # Génération du ICV\n pkt.SC = i\n icv = zlib.crc32(bytes(data[i], 'UTF-8'))\n icv = struct.pack(\"<L\", icv)\n\n # Chiffrement avec RC4\n cipherText = cipher.crypt(bytes(data[i], 'UTF-8') + icv)\n\n # Remplacement des champs dans notre packet\n pkt.wepdata = cipherText[:-4]\n pkt.icv = struct.unpack(\"!L\", cipherText[-4:])[0]\n\n if(i != 2):\n pkt.FCfield = 0x0845\n else:\n pkt.FCfield = 0x0841\n\n pktList.append(pkt)\n\n# Génération du fichier pcap\nwrpcap('fragment.pcap', pktList) ","sub_path":"files/fragmentation.py","file_name":"fragmentation.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"602078363","text":"\"\"\"MIT License\r\n\r\nCopyright (c) 2019\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\"\"\"\r\n\r\nimport serial, time\r\nimport datetime as dt\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\n# function to get Emissivity from MCU\r\ndef get_emissivity():\r\n ser.write(serial.to_bytes([0xA5, 0x55, 0x01, 0xFB]))\r\n read = ser.read(4)\r\n return read[2] / 100\r\n\r\n\r\n# function to get temperatures from MCU (Celsius degrees x 100)\r\ndef get_temp_array(d):\r\n # getting ambient temperature\r\n T_a = (int(d[1540]) + int(d[1541]) * 256) / 100\r\n\r\n # getting raw array of pixels temperature\r\n raw_data = d[4:1540]\r\n T_array = np.frombuffer(raw_data, dtype=np.int16)\r\n\r\n return T_a, T_array\r\n\r\n\r\n# function to convert temperatures to pixels on image\r\ndef td_to_image(f):\r\n norm = np.uint8((f / 100 - Tmin) * 255 / (Tmax - Tmin))\r\n norm.shape = (24, 32)\r\n return norm\r\n\r\n\r\n########################### Main cycle #################################\r\n# Color map range\r\nTmax = 40\r\nTmin = 20\r\n\r\nprint('Configuring Serial port')\r\nser = serial.Serial('/dev/serial0')\r\nser.baudrate = 115200\r\n\r\n# set frequency of module to 4 Hz\r\nser.write(serial.to_bytes([0xA5, 0x25, 0x01, 0xCB]))\r\ntime.sleep(0.1)\r\n\r\n# Starting automatic data colection\r\nser.write(serial.to_bytes([0xA5, 0x35, 0x02, 0xDC]))\r\nt0 = time.time()\r\n\r\ntry:\r\n while True:\r\n # waiting for data frame\r\n data = ser.read(1544)\r\n\r\n # The data is ready, let's handle it!\r\n Ta, temp_array = get_temp_array(data)\r\n ta_img = td_to_image(temp_array)\r\n\r\n # Image processing\r\n img = cv2.applyColorMap(ta_img, cv2.COLORMAP_JET)\r\n img = cv2.resize(img, (320, 240), interpolation=cv2.INTER_CUBIC)\r\n img = cv2.flip(img, 1)\r\n\r\n text = 'Tmin = {:+.1f} Tmax = {:+.1f} FPS = {:.2f}'.format(temp_array.min() / 100, temp_array.max() / 100,\r\n 1 / (time.time() - t0))\r\n cv2.putText(img, text, (5, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 1)\r\n cv2.imshow('Output', img)\r\n\r\n # if 's' is pressed - saving of picture\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"s\"):\r\n fname = 'pic_' + dt.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.jpg'\r\n cv2.imwrite(fname, img)\r\n print('Saving image ', fname)\r\n\r\n t0 = time.time()\r\n\r\nexcept KeyboardInterrupt:\r\n # to terminate the cycle\r\n ser.write(serial.to_bytes([0xA5, 0x35, 0x01, 0xDB]))\r\n ser.close()\r\n cv2.destroyAllWindows()\r\n print(' Stopped')\r\n\r\n# just in case\r\nser.close()\r\ncv2.destroyAllWindows()","sub_path":"TempRead.py","file_name":"TempRead.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"499786978","text":"from .basements import keyboard, get_keyboard\n\nkeyboard = {**keyboard, **{\n '/Квартиры/': get_keyboard(['Планировка БТИ на квартиру', 'Фото', 'Размеры']),\n '/Квартиры/Планировка БТИ на квартиру/': get_keyboard(['Нет', 'Да']),\n '/Квартиры/Планировка БТИ на квартиру/Да/': get_keyboard(['Занести в проект', 'Сделать фото']),\n '/Квартиры/Фото/': get_keyboard(['Магистралей с описанием', 'Стояков с описанием', 'Счетчиков', 'Балконов', 'Полотенцесушителей', 'Эл счетчик', 'Зарисовки на плане всех систем']),\n '/Квартиры/Размеры/': get_keyboard(['Диаметр стояков', 'Радиаторы']),\n '/Квартиры/Размеры/Радиаторы/': get_keyboard(['Количество секций', 'Материал']),\n '/Квартиры/Размеры/Радиаторы/Материал/': get_keyboard(['Чугун', 'Биметаллические', 'Другое']),\n}}\n\n","sub_path":"keyboard/appartments.py","file_name":"appartments.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"342058092","text":"\"\"\"Sqlfluff is a SQL linter for humans.\"\"\"\r\nimport sys\r\n\r\n# Expose the public API.\r\nfrom .api import lint, fix, parse # noqa: F401\r\n\r\n# Check major python version\r\nif sys.version_info[0] < 3:\r\n raise Exception(\"Sqlfluff does not support Python 2. Please upgrade to Python 3.\")\r\n# Check minor python version\r\nelif sys.version_info[1] < 6:\r\n raise Exception(\r\n (\r\n \"Sqlfluff 0.4.0 only supports Python 3.6 and beyond. \"\r\n \"Use an earlier version of sqlfluff or a later version of Python\"\r\n )\r\n )\r\n\r\n# Set the version attribute of the library\r\nimport pkg_resources\r\nimport configparser\r\n\r\n# Get the current version\r\nconfig = configparser.ConfigParser()\r\nconfig.read([pkg_resources.resource_filename(\"sqlfluff\", \"config.ini\")])\r\n\r\n__version__ = config.get(\"sqlfluff\", \"version\")\r\n","sub_path":"src/sqlfluff/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"154847733","text":"from django.conf import settings\nfrom django.core.mail.message import EmailMessage\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.core.exceptions import ValidationError\nfrom django.core.urlresolvers import reverse\nimport django.utils.timezone as timezone\nimport re\nimport os\nfrom ..departments.models import Department, DepartAB\nfrom ..mails.models import Mail, MailTemplate\nfrom ..supervisions.models import SupervisionTemplate\nimport datetime\n\n\ndef validate_percent(value):\n if value < 0 or value > 100:\n raise ValidationError(\n _('%(value)s is not a valid number'),\n params={'value': value},\n )\n\n\nTYPE_CHOICES = (('Vital', '重要事项'), ('Feedback', _('反馈事项')), ('Submit', _('报送事项')))\nSTATUS_CHOICES = (('1', '立项'), ('2', _('督办')), ('3', _('暂停')), ('4', _('完结')))\nSTATE_CHOICES = (('Completed', _('完成')), ('Uncompleted', _('未完成')), ('Delayed', _('延期')), ('DelayCompleted', _('延期完成')))\n\n\nclass role(models.Model):\n name = models.CharField(_('项目名称'), max_length=200)\n founder = models.CharField(_('创始人'), max_length=200, editable=False)\n created_time = models.DateTimeField(_('立项时间'))\n department = models.ForeignKey(Department, verbose_name=_('department'))\n end_time = models.DateTimeField(_('项目结束时间'))\n content = models.TextField(_('项目内容'))\n type = models.CharField(_('项目类型'), choices=TYPE_CHOICES, max_length=20)\n status = models.CharField(_('status'), choices=STATUS_CHOICES, max_length=1)\n mail_templete = models.ForeignKey(MailTemplate, verbose_name=_('mail_template'))\n supervision_templete = models.ForeignKey(SupervisionTemplate, verbose_name=_('SupervisionTemplate'))\n\n # 督办模板填充字段\n send_times = models.IntegerField(_('邮件发送次数'), blank=True)\n need_feedback = models.BooleanField(_('是否需要反馈'))\n feedback_need_attachment = models.BooleanField(_('反馈上传附件'))\n\n def send_upload_to(instance, filename):\n '''set send_attachment's upload path to roles/(role.id)/send/(filename),\n for example, roles/1/send/test.txt'''\n return 'roles/' + str(instance.pk) + '/send/' + filename\n\n send_attachment = models.FileField(_('发送附件'), upload_to=send_upload_to, blank=True)\n\n class Meta:\n ordering = ['-end_time']\n verbose_name = _('role')\n verbose_name_plural = _('roles')\n\n def __str__(self):\n return self.name\n\n def save(self, using='default', *args, **kwargs):\n self.full_clean()\n if self.pk is None:\n # 选择邮件模版:\n if self.supervision_templete is not None:\n self.send_times = self.supervision_templete.send_times\n self.need_feedback = self.supervision_templete.need_feedback\n self.feedback_need_attachment = self.supervision_templete.feedback_need_attachment\n # mail_templete = self.mail_templete\n # subject = mail_templete.subject_name\n # body = self.get_created_body()\n # email = EmailMessage()\n # email.subject = subject\n # email.body = body\n # email.from_email = settings.DEFAULT_FROM_EMAIL\n # if self.feedback_need_attachment is True and self.send_attachment != '':\n # email.attach_file(self.send_attachment.path)\n # to_mails = []\n # departs = mail_templete.receive.all()\n # for item in departs:\n # for responsible in DepartAB.objects.filter(department=item):\n # to_mails += [item.email for item in responsible.responsible.all()]\n # email.to = to_mails\n # email.cc = [c.email for c in mail_templete.copyfor.all()]\n # # email.send()\n # receive_mails = '\\n'.join(to_mails)\n # mail_admin = Mail(subject=subject, sender=settings.DEFAULT_FROM_EMAIL, receive=receive_mails, content=body)\n # mail_admin.save()\n super(role, self).save(using='default', *args, **kwargs)\n # 当创建新任务同时上传了文件时, 在save方法执行前, role没有id, 此时的路径\n # 不正确, 需要对文件名和路径修改后重新保存role对象.\n if self.send_attachment != '':\n oldname = self.send_attachment.name\n oldpath = self.send_attachment.path\n p = re.compile(r'roles/None/send/')\n if p.match(oldname):\n p = re.compile(r'(?<=roles/)None(?=/send/)')\n newname = p.sub(str(self.pk), oldname)\n self.send_attachment.name = newname\n newpath = self.send_attachment.path\n p = re.compile(r'/[^/]*$')\n newpathwithoutfilename = p.sub('', newpath)\n oldpathwithoutfilename = p.sub('', oldpath)\n os.makedirs(newpathwithoutfilename)\n os.rename(oldpath, newpath)\n try:\n os.removedirs(oldpathwithoutfilename)\n except Exception as e:\n print(e)\n self.save()\n\n def get_created_body(self):\n '''根据任务设定生成邮件的内容'''\n body = '''\n {}于{}创建了项目{} \\n\n 项目类型为{} \\n\n 项目目的以及内容: {} \\n\n 项目结束时间: {} \\n\n '''.format(self.founder, timezone.localtime(self.created_time).strftime('%Y年%m月%d日%H:%M'), self.name, self.type, self.content, self.end_time)\n return body\n\n # Edison add.\n def sendmail(self, feedback):\n '''调用该方法来发送本任务的邮件'''\n\n # 选择邮件模版:\n mail_templete = self.mail_templete\n subject = mail_templete.subject_name\n body = self.get_created_body()\n email = EmailMessage()\n email.subject = subject\n email.body = body + '\\n' + 'http://' + settings.HOST_IP + ':8000' + reverse('roles:feedback', kwargs={'role_id': self.id, 'feedback_id': feedback.id})\n email.from_email = settings.DEFAULT_FROM_EMAIL\n if self.feedback_need_attachment is True and self.send_attachment != '':\n email.attach_file(self.send_attachment.path)\n to_mails = []\n departs = mail_templete.receive.all()\n for item in departs:\n for responsible in DepartAB.objects.filter(department=item):\n to_mails += [item.email for item in responsible.responsible.all()]\n email.to = to_mails\n email.cc = [c.email for c in mail_templete.copyfor.all()]\n try:\n email.send()\n except Exception as e:\n print('%s' % (e))\n return False\n return True\n\n def get_last_feedback(self):\n '''根据创建时间和id属性排序获得最新的反馈'''\n return self.role_feedback_set.order_by('create_time','id').last()\n\n def create_feedback(self):\n '''创建反馈, 该方法已经无用'''\n last_feedback = self.get_last_feedback()\n if last_feedback is None:\n percent = 0\n else:\n percent = last_feedback.percent\n feedback = role_feedback.objects.create(role=self, percent=percent)\n return feedback\n\n def _get_role_by_department(departments):\n return role.objects.filter(department__in=departments)\n\n def get_all_feedbacks(self):\n '''获得当前任务所有的反馈'''\n return self.role_feedback_set.all()\n\n def get_need_feedbacks(self):\n '''获得当前任务所有待反馈的条目'''\n return self.role_feedback_set.filter(feedback_time__isnull=True)\n\n def get_already_feedbacks(self):\n '''获得当前任务所有待反馈的条目'''\n return self.role_feedback_set.filter(feedback_time__isnull=False)\n\n def get_front_contextual_class(self):\n '''根据任务综合状况返回前端class'''\n if self.get_role_state() == 'Completed':\n return 'success'\n if self.get_role_state() == 'Uncompleted':\n if self.get_need_feedbacks().count() > 0:\n return 'warning'\n return 'info'\n if self.get_role_state() == 'Delayed':\n return 'danger'\n\n def get_role_state(self):\n '''获得任务状态'''\n if self.role_feedback_set.filter(state='Completed'):\n return 'Completed'\n if self.role_feedback_set.filter(feedback_time__gt=timezone.now()):\n return 'Delayed'\n return 'Uncompleted'\n state = property(get_role_state)\n\n def getattribute(self, attr):\n value = super(role, self).__getattribute__(attr)\n if attr == 'status':\n for element in STATUS_CHOICES:\n if value == element[0]:\n value = element[1]\n return value\n if attr == 'state':\n for element in STATE_CHOICES:\n if value == element[0]:\n value = element[1]\n return value\n if attr == 'type':\n for element in TYPE_CHOICES:\n if value == element[0]:\n value = element[1]\n return value\n if value.__class__ is datetime.datetime:\n value = timezone.localtime(value).strftime('%Y年%m月%d日%H:%M')\n return value\n\n\nclass role_feedback(models.Model):\n\n def feedback_upload_to(instance, filename):\n '''set feedback_attachment's upload path to roles/(role.id)/feedback/(feedback.id)/(filename),\n for example, roles/1/feedback/2/test.txt'''\n return 'roles/' + str(instance.role.id) + '/feedback/' + str(instance.id) + '/' + filename\n\n role = models.ForeignKey(role, on_delete=models.CASCADE)\n schedule_time = models.DateTimeField(_('发送时间'))\n schedule_sent = models.BooleanField(_('已发送'), default=False)\n percent = models.IntegerField(_('完成百分比'), validators=[validate_percent], blank=True)\n state = models.CharField(_('状态'), choices=STATE_CHOICES, max_length=20, blank=True)\n feedback_attachment = models.FileField(_('反馈附件'), upload_to=feedback_upload_to, blank=True)\n create_time = models.DateTimeField(_('创建时间'), default=timezone.now)\n feedback_time = models.DateTimeField(_('反馈时间'), blank=True, null=True)\n\n class Meta:\n ordering = ['-feedback_time']\n verbose_name = _('role_feedback')\n verbose_name_plural = _('role_feedbacks')\n\n def sendmail_to_admin(self):\n '''当用户提交反馈时从views.feedback中调用发送邮件给反馈所属任务的管理员'''\n mail_templete = self.role.mail_templete\n subject = mail_templete.subject_name\n email = EmailMessage()\n email.subject = subject + ':任务反馈'\n email.body = '完成百分比: ' + str(self.percent) + '%'\n email.body += '\\n状态: ' + self.state\n email.body += '\\n反馈时间: ' + self.feedback_time.strftime('%c')\n if self.role.feedback_need_attachment is True and self.feedback_attachment != '':\n email.body += '\\n反馈附件: ' + self.feedback_attachment.name\n email.body += '\\n反馈链接: ' + 'http://' + settings.HOST_IP + ':8000' + reverse('roles:feedback', kwargs={'role_id': self.role.id, 'feedback_id': self.id})\n email.from_email = settings.DEFAULT_FROM_EMAIL\n if self.role.feedback_need_attachment is True and self.feedback_attachment != '':\n email.attach_file(self.feedback_attachment.path)\n email.to = ['45703754@qq.com']\n email.cc = []\n try:\n email.send()\n except Exception as e:\n print('%s' % (e))\n return False\n return True\n\n def save(self, using='default', *args, **kwargs):\n # 在admin界面添加新的定时发送时, 当界面未填完成百分比时,\n # 自动填充之前最晚的反馈的百分比.\n if self.percent is None:\n last_feedback = self.role.get_last_feedback()\n if last_feedback is not None:\n self.percent = last_feedback.percent\n else:\n self.percent = 0\n super(role_feedback, self).save(using='default', *args, **kwargs)\n\n @models.permalink\n def get_absolute_url(self):\n return ('roles:feedback', None, {'role_id': self.role.id, 'feedback_id': self.id})\n\n def _get_custom_title(self):\n if self.feedback_time is not None:\n return ugettext('Feedback at') + ':' + timezone.localtime(self.feedback_time).strftime('%Y年%m月%d日%H:%M') + ',' + ugettext('status') + ':' + ugettext(self.state)\n else:\n return ugettext('Created at') + ':' + timezone.localtime(self.create_time).strftime('%Y年%m月%d日%H:%M') + ',' + ugettext('status') + ':' + ugettext('need feedback')\n custom_title = property(_get_custom_title)\n\n def get_front_contextual_class(self):\n if self.feedback_time is None:\n return 'warning'\n else:\n return 'success'\n","sub_path":"chief/apps/roles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"148112613","text":"from random import randint\r\n\r\nclass Player():\r\n\tdef __init__(self, name):\r\n\t\tself.uuid = randint(100000000, 999999999)\r\n\t\tself.name = name\r\n\r\nclass Authentication():\r\n\tdef __init__(self, games):\r\n\t\tself.games = games\r\n\r\n\tdef generate_random_code(self):\r\n\t\treturn randint(100000000, 999999999)\r\n\r\n\tdef start_game(self, player):\r\n\t\tcode = self.generate_random_code()\r\n\t\tself.games[code] = [player]\r\n\t\treturn code\r\n\r\n\tdef join_game(self, code, player):\r\n\t\tself.games[code].append(player)\r\n\r\ndef main():\r\n\tnavin = Player(\"navin\")\r\n\tjohn = Player(\"john\")\r\n\tjavier = Player(\"javier\")\r\n\tanthony = Player(\"anthony\")\r\n\tjosiah = Player(\"josiah\")\r\n\tandrew = Player(\"andrew\")\r\n\r\n\tgames = {}\r\n\tauthentication = Authentication(games)\r\n\tcode = authentication.start_game(navin)\r\n\tauthentication.join_game(code, john)\r\n\tcode = authentication.start_game(javier)\r\n\tauthentication.join_game(code, anthony)\r\n\tcode = authentication.start_game(josiah)\r\n\tauthentication.join_game(code, andrew)\r\n\tprint(authentication.games)\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"platform/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"337446136","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/hasher/apps/workflow/workflowapp/migrations/0002_trigger.py\n# Compiled at: 2016-03-04 08:11:07\nfrom __future__ import unicode_literals\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('workflowapp', '0001_initial')]\n operations = [\n migrations.CreateModel(name=b'Trigger', fields=[\n (\n b'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=b'ID')),\n (\n b'trigger_function', models.CharField(max_length=100, null=True)),\n (\n b'state_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=b'workflowapp.State'))])]","sub_path":"pycfiles/hiworkflow-3.0.tar/0002_trigger.py","file_name":"0002_trigger.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"430175751","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom unittest import mock\n\nimport oslotest.base\n\nfrom designate.common import profiler\nfrom designate import policy\nfrom designate import rpc\nfrom designate import service as designate_service\n\n\n@mock.patch.object(policy, 'init')\n@mock.patch.object(rpc, 'init')\n@mock.patch.object(profiler, 'setup_profiler')\nclass TestDesignateServiceInit(oslotest.base.BaseTestCase):\n def test_service_init(self, mock_setup_profiler, mock_rpc_init,\n mock_policy_init):\n service = designate_service.Service('test-service')\n\n mock_policy_init.assert_called_once()\n mock_rpc_init.assert_called_once()\n mock_setup_profiler.assert_called_once()\n\n self.assertEqual('test-service', service.name)\n\n def test_rpc_service_init(self, mock_setup_profiler, mock_rpc_init,\n mock_policy_init):\n service = designate_service.RPCService(\n 'test-rpc-service', 'test-topic'\n )\n\n mock_policy_init.assert_called_once()\n mock_rpc_init.assert_called_once()\n mock_setup_profiler.assert_called_once()\n\n self.assertEqual([service], service.endpoints)\n self.assertEqual('test-topic', service.rpc_topic)\n self.assertEqual('test-rpc-service', service.name)\n\n\nclass TestDesignateRpcService(oslotest.base.BaseTestCase):\n @mock.patch.object(policy, 'init')\n @mock.patch.object(rpc, 'init')\n @mock.patch.object(profiler, 'setup_profiler')\n def setUp(self, mock_setup_profiler, mock_rpc_init,\n mock_policy_init):\n super(TestDesignateRpcService, self).setUp()\n self.service = designate_service.RPCService(\n 'test-rpc-service', 'test-topic'\n )\n\n mock_policy_init.assert_called_once()\n mock_rpc_init.assert_called_once()\n mock_setup_profiler.assert_called_once()\n\n @mock.patch.object(rpc, 'get_server')\n @mock.patch.object(rpc, 'get_notifier')\n def test_rpc_service_start(self, mock_rpc_get_server,\n mock_rpc_get_notifier):\n self.assertIsNone(self.service.start())\n\n mock_rpc_get_server.assert_called_once()\n mock_rpc_get_notifier.assert_called_once()\n\n self.service.rpc_server.start.assert_called_once()\n\n @mock.patch.object(rpc, 'get_server')\n @mock.patch.object(rpc, 'get_notifier')\n def test_rpc_service_stop(self, mock_rpc_get_server,\n mock_rpc_get_notifier):\n self.assertIsNone(self.service.start())\n\n mock_rpc_get_server.assert_called_once()\n mock_rpc_get_notifier.assert_called_once()\n\n self.assertIsNone(self.service.stop())\n\n self.service.rpc_server.stop.assert_called_once()\n\n def test_rpc_service_wait(self):\n self.assertIsNone(self.service.wait())\n","sub_path":"designate/tests/unit/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"418615733","text":"\"\"\"\nSection 3\nConcurrency, CPU Bound vs I/O Bound - I/O Bound(2) - threading vs asyncio vs multiprocessing\n\n\nKeyword - I/O Bound, Threading, requests\n\n\"\"\"\n# I/O-Bound Threading 예제(https://realpython.com/python-concurrency/#synchronous-version)\n\nimport concurrent.futures\nimport threading\n# pip install requests\nimport requests\nimport time\n\n# 각 스레드에 생성되는 객체(독립된 네임스페이스)\nthread_local = threading.local()\n\n# 세션 제공\ndef get_session():\n if not hasattr(thread_local, \"session\"): # 딕셔너리 타입으로 확인\n thread_local.session = requests.Session()\n print('>>> not hasattr()')\n return thread_local.session\n\n# 실행함수1(다운로드)\ndef request_site(url):\n # 세션 획득\n session = get_session()\n\n # 세션 확인\n print(session)\n # print(session.headers)\n\n with session.get(url) as response:\n print(f\"[Read Contents : {len(response.content)}, Status Code : {response.status_code}] from {url}\")\n \n\n# 실행함수2\ndef request_all_site(urls):\n # 멀티스레드 실행\n # 반드시 max_worker 개수 조절 후 session 객체 확인\n with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:\n executor.map(request_site, urls)\n\ndef main():\n # 테스트 URLS\n urls = [\n \"https://www.jython.org\",\n \"https://www.naver.com\",\n \"https://realpython.com/\"\n ] * 3\n \n # 실행시간 측정\n start_time = time.time()\n\n # 실행\n request_all_site(urls)\n\n # 실행 시간 종료\n duration = time.time() - start_time\n\n print()\n \n # 결과 출력\n print(f\"Downloaded {len(urls)} sites in {duration} seconds\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"py_ad_3_5_1.py","file_name":"py_ad_3_5_1.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"370514305","text":"#!/usr/bin/env python2.7\n# -*- coding:UTF-8 -*-2\nu\"\"\"group.py\n\nCopyright(c)2019 Yukio Kuro\nThis software is released under BSD license.\n\nクリーチャーグループモジュール。\n\"\"\"\nimport creature as _creature\nimport material.sound as _sound\nimport utils.layouter as _layouter\n\n\nclass Group(object):\n u\"\"\"クリーチャーグループ。\n \"\"\"\n __LIMIT = 3\n\n def __init__(self, main, battle):\n u\"\"\"コンストラクタ。\n playerとidは位置・向き設定用。\n \"\"\"\n self.__player = battle.player\n self.__id = main.id\n self.__units = []\n\n def __iter__(self):\n u\"\"\"イテレータ取得。\n \"\"\"\n return iter(self.__units)\n\n def __len__(self):\n u\"\"\"len()で使用。\n \"\"\"\n return len(self.__units)\n\n def __nonzero__(self):\n u\"\"\"グループ判定。\n クリーチャが一体でも存在する場合に真。\n \"\"\"\n return bool(self.__units)\n\n def summon(self, info, packet):\n u\"\"\"召喚処理。\n \"\"\"\n if not self.is_full:\n _sound.SE.play(\"summon\")\n creature = _creature.Creature((0, 0), info, packet)\n creature.is_right = not self.__id\n self.__units.append(creature)\n _layouter.Game.set_creature_init(\n len(self.__units)-1, self.__units, self.__player)\n _layouter.Game.set_creature_dest(\n self.__units, self.__player, self.__id)\n _layouter.Game.set_creature_layer(self.__units)\n creature.flash(\"Summon\")\n\n def adapt(self, target):\n u\"\"\"融合可能クリーチャ取得。\n 融合可能クリーチャーが存在する場合、融合後クリーチャーを返す。\n \"\"\"\n for unit in self.__units:\n fusioned = unit.adapt(target)\n if fusioned:\n return fusioned\n return None\n\n def fusion(self, info, packet):\n u\"\"\"融合処理。\n \"\"\"\n for i, unit in enumerate(self.__units):\n fusioned = unit.adapt(info)\n if fusioned:\n _sound.SE.play(\"fusion\")\n unit.kill()\n new = _creature.Creature((0, 0), fusioned, packet)\n new.power = unit.power\n new.power_ups = unit.power_ups\n new.rect.midbottom = new.dest.midbottom = unit.rect.midbottom\n new.is_right = not self.__id\n self.__units[i] = new\n _layouter.Game.set_creature_layer(self.__units)\n new.flash(\"Summon\")\n return None\n\n def __poison_effect(self):\n u\"\"\"毒効果エフェクト。\n \"\"\"\n for unit in self.__units:\n if unit.is_poison:\n unit.poison_effect()\n unit.flash(\"Poison\")\n\n def __regenerate(self):\n u\"\"\"自己再生効果。\n \"\"\"\n for unit in self.__units:\n if unit.is_regeneratable:\n unit.regenerate()\n\n def destroy(self, extinction=False):\n u\"\"\"ユニット破壊処理。\n 即死魔術使用後にも使用する。\n \"\"\"\n for unit in self.__units[:]:\n if unit.is_dead or extinction:\n unit.destroy()\n self.__units.remove(unit)\n _layouter.Game.set_creature_dest(\n self.__units, self.__player, self.__id)\n _layouter.Game.set_creature_layer(self.__units)\n\n def turn(self, extinction=False):\n u\"\"\"ターン毎の処理。\n extinctionがTrueの時は全滅。\n \"\"\"\n for unit in self.__units:\n unit.count_down()\n self.__poison_effect()\n self.__regenerate()\n self.destroy(extinction)\n\n def receive(self, stroke):\n u\"\"\"攻撃を受け取る。\n \"\"\"\n if self.__units:\n return sum(\n unit.receive(unit.defense(stroke/len(self.__units))) for\n unit in self.__units)\n return stroke\n\n def charge(self, onepiece):\n u\"\"\"チャージ処理。\n \"\"\"\n for monster in self.__units:\n monster.charge(onepiece)\n\n def power_plus(self, plus):\n u\"\"\"力パワーアップ追加。\n \"\"\"\n for unit in self.__units:\n unit.power_plus(plus)\n\n def protect_plus(self, plus):\n u\"\"\"守りパワーアップ追加。\n \"\"\"\n for unit in self.__units:\n unit.protect_plus(plus)\n\n def speed_plus(self, plus):\n u\"\"\"スピードパワーアップ追加。\n \"\"\"\n for unit in self.__units:\n unit.speed_plus(plus)\n\n def power_minus(self, minus):\n u\"\"\"パワーアップ除去。\n \"\"\"\n for unit in self.__units:\n unit.power_minus(minus)\n\n def get_healthy(self, units):\n u\"\"\"回復優先度の低いユニットを取得。\n \"\"\"\n return min(\n units, key=lambda unit: unit.hialing_priority) if units else None\n\n def get_injured(self, units):\n u\"\"\"回復優先度の高いユニットを取得。\n \"\"\"\n return max(\n units, key=lambda unit: unit.hialing_priority) if units else None\n\n def get_healths(self, units):\n u\"\"\"状態異常以外のユニットを取得。\n \"\"\"\n return tuple(unit for unit in units if unit.is_healths)\n\n def is_prevents(self, new):\n u\"\"\"状態変化を防止した場合、ユニットをフラッシュして真を返す。\n new: 変化後ブロック。\n \"\"\"\n for unit in self.__units:\n if new in unit.prevents:\n unit.flash(\"Ability\")\n return True\n return False\n\n @property\n def healths(self):\n u\"\"\"状態異常以外のユニットを取得。\n \"\"\"\n return self.get_healths(self.__units)\n\n def get_damaged(self, units):\n u\"\"\"ライフ半分のユニットを取得。\n \"\"\"\n return tuple(unit for unit in units if unit.is_half)\n\n @property\n def damaged(self):\n u\"\"\"ライフ半分のユニットを取得。\n \"\"\"\n return self.get_damaged(self.__units)\n\n def get_livings(self, units):\n u\"\"\"不死属以外のクリーチャ取得。\n \"\"\"\n return tuple(unit for unit in units if not unit.is_undead)\n\n @property\n def is_full(self):\n u\"\"\"ユニットが満員状態の時に真。\n \"\"\"\n return self.__LIMIT <= len(self.__units)\n\n @property\n def recepters(self):\n u\"\"\"融合可能クリーチャー名取得。\n \"\"\"\n if self.__units:\n return set(reduce(\n lambda x, y: x+y, (unit.recepters for unit in self.__units)))\n return set()\n","sub_path":"Source/armament/units/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"242548616","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nfrom crawler.items import ProxyIPItem\n\n\nclass HidesterSpider(scrapy.Spider):\n name = \"hidester\"\n allowed_domains = [\"hidester.com\"]\n start_urls = [\n 'https://hidester.com/proxydata/php/data.php?mykey=data&offset=0&limit=10&orderBy=latest_check&sortOrder=DESC&country=&port=&type=undefined&anonymity=undefined&ping=undefined&gproxy=2',\n 'https://hidester.com/proxydata/php/data.php?mykey=data&offset=1&limit=10&orderBy=latest_check&sortOrder=DESC&country=&port=&type=undefined&anonymity=undefined&ping=undefined&gproxy=2',\n 'https://hidester.com/proxydata/php/data.php?mykey=data&offset=1&limit=10&orderBy=latest_check&sortOrder=DESC&country=&port=&type=undefined&anonymity=undefined&ping=undefined&gproxy=2',\n 'https://hidester.com/proxydata/php/data.php?mykey=data&offset=2&limit=10&orderBy=latest_check&sortOrder=DESC&country=&port=&type=undefined&anonymity=undefined&ping=undefined&gproxy=2',\n]\n headers = {\n 'Host': 'hidester.com',\n 'Connection': 'keep-alive',\n 'Accept': 'application/json, text/plain, */*',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',\n 'Referer': 'https://hidester.com/proxylist/',\n 'Accept-Encoding': 'gzip, deflate, sdch, br',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n }\n cookies = {\n '_gat': '1',\n ' _icl_current_language': 'en',\n '_ga': 'GA1.2.1804354853.1489153944',\n }\n\n def start_requests(self):\n for url in self.start_urls:\n yield scrapy.Request(url, headers=self.headers, cookies=self.cookies)\n\n def parse(self, response):\n try:\n proxies = json.loads(response.text)\n for proxy in proxies:\n item = ProxyIPItem()\n item['ip'] = proxy['IP']\n item['port'] = proxy['PORT']\n item['type'] = 'http'\n yield item\n pass\n except:\n pass\n","sub_path":"crawler/spiders/hidester.py","file_name":"hidester.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"200523276","text":"def main():\r\n kgmorango = float(input('Digite a quantidade de morangos em kg: '))\r\n kgmaca = float(input('Digite a quantidade de maçãs em kg: '))\r\n\r\n\r\n if kgmorango <= 5:\r\n valor1 = kgmorango * 2.5\r\n else:\r\n valor1 = kgmorango * 2.2\r\n if kgmaca <= 5:\r\n valor2 = kgmaca * 1.8\r\n else:\r\n valor2 = kgmaca * 1.5\r\n\r\n valor_total = valor1 + valor2\r\n\r\n if kgmorango + kgmaca > 8 or valor_total > 25:\r\n valor_total = valor_total - ((valor_total * 10) / 100)\r\n\r\n print('Valor a ser pago: R$ %.2f' % valor_total)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Python/Fabio lista 2b/Fabio_02b_Q15.py","file_name":"Fabio_02b_Q15.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"118329326","text":"from util import *\nfrom hillclimbng import hillclimb\nfrom evolutionary import *\nimport random\n\n\ndef lamarckian(distances, generation, ncities, population_size, nParents,\n mut_rate, cross_rate, learning_iteration):\n\n init_set = []\n init_size = 10\n for x in range(init_size):\n init_set.append(random.sample(range(ncities),ncities))\n\n population = [(tour_distance(p, distances),p) for p in init_set]\n\n# For plotting\n best_fit = []\n\n for x in range(generation):\n# print(\"============Generation {0} ===========\".format(x))\n\n population = lamarckian_learning(population, learning_iteration, distances)\n\n parents = select_parents(population, nParents)\n# print(parents)\n\n offspring = []\n if random.randint(0,100) <= cross_rate:\n offspring = recombine(parents)\n# print(\"crossed\",offspring)\n\n if random.randint(0,100) <= mut_rate:\n offspring = mutate(offspring)\n # print(\"mutated\",offspring)\n\n population = replacement_strategy(offspring, population, population_size, distances)\n best_fit.append(population[0][0])\n\n\n cost,path = population[0]\n return path + path[:1], cost, best_fit\n\ndef lamarckian_learning(pop, n, distances):\n for i, (a,b) in enumerate(pop):\n for x in range(n):\n (c,d) = hillclimb(b,a,distances)\n pop[i] = (c,d)\n return pop\n\n","sub_path":"Assignment1/lamarckian.py","file_name":"lamarckian.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"621402831","text":"import os, sys, getopt, time\r\n\r\nPORTLETS = [\"BASE\", \"CRUD\", \"BACKOFFICE\", \"MASSIVE\", \"CUSTOM LOGIN\", \"INTEGRATION\", \"LIFERAY TRANSLATION\", \"NOTIFICATION\", \"REPORT\", \"FRONTEND\"]\r\ndefaultDirectory = os.getcwd()\r\nwarningsFile = \"warnings.txt\"\r\nallLabelsFile = \"allLabels.txt\"\r\n\r\n\r\ndef allPortlets(list_i18n, list_language):\r\n crudCheck(list_i18n, list_language, \"CRUD\")\r\n baseCheck(list_language, \"BASE\")\r\n backOfficeCheck(list_language, \"BACKOFFICE\")\r\n massiveFirmwareUpdateCheck(list_language, \"MASSIVE\")\r\n customLoginCheck(list_language, \"CUSTOM LOGIN\")\r\n integrationCheck(list_language, \"INTEGRATION\")\r\n liferayTranslationCheck(list_language, \"LIFERAY TRANSLATION\")\r\n notificationCheck(list_language, \"NOTIFICATION\")\r\n reportCheck(list_language, \"REPORT\")\r\n v2FrontEndCheck(list_language, \"FRONTEND\")\r\n\r\ndef crudCheck (list_i18n, list_language, portletName):\r\n i18nPath = \"\\\\portlets\\\\intouch-crud-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\\"\r\n languagePath = \"\\\\portlets\\\\intouch-crud-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n if os.path.isfile(i18nPath + warningsFile):\r\n os.remove(i18nPath + warningsFile)\r\n\r\n if os.path.isfile(languagePath + warningsFile):\r\n os.remove(languagePath + warningsFile) \r\n\r\n takingAllLabels(defaultDirectory + i18nPath, list_i18n)\r\n confrontFilesWithAllLabels(defaultDirectory + i18nPath, list_i18n, portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(defaultDirectory + i18nPath + warningsFile):\r\n displayWarnings(defaultDirectory + i18nPath + warningsFile)\r\n\r\n else:\r\n print(\"\\nAll 'i18n' labels in: \" + portletName + \" are translated\")\r\n\r\n if os.path.isfile(defaultDirectory + languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n \r\n else:\r\n print(\"\\nAll 'Language' labels in: \" + portletName + \" are translated\")\r\n\r\ndef baseCheck (list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-crud-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef backOfficeCheck (list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\cobo-backoffice-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef massiveFirmwareUpdateCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-aggiornamento-massivo-firmware-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language) \r\n if os.path.isfile(defaultDirectory + allLabelsFile):\r\n print(\"FILE è PRESENTE PRIMA DI CONFRONTO\")\r\n fmassive = open(defaultDirectory + languagePath + allLabelsFile, \"r\")\r\n lines = fmassive.readlines()\r\n print(\"Ti printo contenuto del file MASSIVE\\n\\n\\n\")\r\n for k in lines:\r\n print(k)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef customLoginCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-custom-login-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef integrationCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-integration-api-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef liferayTranslationCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\hooks\\\\intouch-liferay-translation-hook\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef notificationCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-notification-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef reportCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-report-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\ndef v2FrontEndCheck(list_language, portletName):\r\n\r\n languagePath = \"\\\\portlets\\\\intouch-v2-frontend-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n print(\"Working on \" + portletName)\r\n takingAllLabels(defaultDirectory + languagePath, list_language)\r\n confrontFilesWithAllLabels(defaultDirectory + languagePath, list_language, portletName)\r\n if os.path.isfile(languagePath + warningsFile):\r\n displayWarnings(defaultDirectory + languagePath + warningsFile)\r\n\r\n else:\r\n print(\"All labels in \" + portletName + \" are translated\")\r\n\r\n\r\ndef progress(i, mainFileLen):\r\n return 100 * i / mainFileLen \r\n\r\ndef takingAllLabels(workingDirectory, list):\r\n\r\n if os.path.isfile(workingDirectory + allLabelsFile):\r\n os.remove(workingDirectory + allLabelsFile)\r\n\r\n firstWrite = True\r\n print(\"\\n\\nCopying all labels in one place\")\r\n workingDirectory = \"C:\\\\projects\\\\INTOUCH\\\\Project\\\\LIFERAY\\\\SDK\\\\portlets\\\\intouch-aggiornamento-massivo-firmware-portlet\\\\docroot\\\\WEB-INF\\\\src\\\\content\\\\\"\r\n for i in list:\r\n if firstWrite:\r\n try:\r\n lineNumbers = file_len(workingDirectory + list[0])\r\n for k in range(lineNumbers):\r\n writeFile(workingDirectory + allLabelsFile, readLineOfFile(workingDirectory + list[0], k))\r\n\r\n firstWrite = False\r\n except:\r\n print(\"FILE \" + list[0] + \" DOESN'T EXIST\")\r\n firstWrite = False\r\n\r\n else:\r\n try:\r\n mainFileLen = file_len(workingDirectory + i)\r\n for lineSecondFile in range(mainFileLen):\r\n lineOfControlledFile = readLineOfFile(workingDirectory + i, lineSecondFile)\r\n progressOfOperation = progress (lineSecondFile, mainFileLen)\r\n sys.stdout.write(\"Processing \" + i + \" %d%% \\r\" % (progressOfOperation))\r\n sys.stdout.flush()\r\n if not checkIfExist(workingDirectory + allLabelsFile, file_len(workingDirectory + allLabelsFile), lineOfControlledFile):\r\n writeFile(workingDirectory + allLabelsFile, lineOfControlledFile)\r\n except:\r\n print(\"FILE \" + workingDirectory + i + \" DOESN'T EXIST\")\r\n\r\ndef confrontFilesWithAllLabels(workingDirectory, list, portlet):\r\n try:\r\n for i in list:\r\n mainFileLen = file_len(workingDirectory + allLabelsFile)\r\n for lineAllLabelsFile in range(mainFileLen):\r\n progressOfOperation = progress (lineAllLabelsFile, mainFileLen)\r\n sys.stdout.write(\"Checking \" + portlet + \" for translations in the file: \" + i + \" %d%% \\r\" % (progressOfOperation))\r\n if progressOfOperation == 100:\r\n print(\"Check of the file: \" + i + \" in \" + portlet + \" is completed...\")\r\n sys.stdout.flush()\r\n\r\n lineOfControlledFile = readLineOfFile(workingDirectory + allLabelsFile, lineAllLabelsFile)\r\n if lineOfControlledFile == '':\r\n continue\r\n\r\n else:\r\n if not checkIfExist(workingDirectory + i, file_len(workingDirectory + i), lineOfControlledFile):\r\n foutwarnings = open(workingDirectory + warningsFile, \"a\")\r\n foutwarnings.write(\"\\n Portlet: \" + portlet + \" Translation label: \" + lineOfControlledFile + \" IS NOT present in \" + i + \" file \")\r\n os.remove(workingDirectory + allLabelsFile)\r\n except:\r\n print(\"FILE \" + workingDirectory + i + \" DOESN'T EXIST\")\r\n print(\"\\n\\nFinished to check labels in \" + portlet)\r\n \r\n\r\ndef writeFile(pathToFile, valueToWrite):\r\n if valueToWrite != \"\\n\":\r\n fwrite = open(pathToFile, \"a\")\r\n fwrite.write(valueToWrite + \"\\n\") \r\n\r\ndef file_len(fname):\r\n leng = 0\r\n with open(fname) as f:\r\n for leng, l in enumerate(f):\r\n pass\r\n\r\n if leng == 0:\r\n return leng\r\n\r\n else:\r\n return leng+1\r\n\r\ndef readLineOfFile(fileName, lineNumber):\r\n fo = open(fileName, \"r\")\r\n lines = fo.readlines()\r\n lineResult = lines[lineNumber]\r\n finalLine = \"\"\r\n for char in lineResult:\r\n if char == '=':\r\n break\r\n\r\n else:\r\n finalLine += char\r\n \r\n return finalLine.rstrip()\r\n\r\ndef checkIfExist(pathToFile, totalNumber, wordToConfront):\r\n exist = False \r\n for z in range(totalNumber):\r\n filteredLine = readLineOfFile(pathToFile, z)\r\n if wordToConfront == filteredLine or wordToConfront + \"\\n\" == filteredLine or wordToConfront + \" \\n\" == filteredLine:\r\n exist = True\r\n\r\n if exist:\r\n break\r\n\r\n return exist \r\n \r\ndef displayWarnings(pathToTheOutputFile):\r\n foutuputWarnings = open(pathToTheOutputFile)\r\n lines = foutuputWarnings.readlines()\r\n for k in lines:\r\n print(k)\r\n\r\n foutuputWarnings.close()\r\n os.remove(pathToTheOutputFile)\r\n \r\ndef main():\r\n list_i18n = [\"i18n.properties\", \"i18n_de.properties\", \"i18n_fr.properties\", \"i18n_it.properties\", \"i18n_zh.properties\", \"i18n_es.properties\"]\r\n list_language = [\"Language.properties\", \"Language_de.properties\", \"Language_es.properties\", \"Language_fr.properties\", \r\n \"Language_it.properties\"]\r\n\r\n# if len(sys.argv) < 2:\r\n# print('Need almost one parameter, example full command: python check_translation.py ' \r\n# + '[ALL | CRUD | BASE | BACKOFFICE | MASSIVE | CUSTOM LOGIN | INTEGRATION | LIFERAY TRANSLATION | NOTIFICATION| REPORT | FRONTEND]' )\r\n# exit()\r\n\r\n# portletName = sys.argv[1].upper() if sys.argv[1].upper() in PORTLETS or sys.argv[1] == \"ALL\" else None\r\n portletName = \"MASSIVE\"\r\n if portletName != \"MASSIVE\":\r\n print(portletName)\r\n# if portletName is None:\r\n# print('Not found valid portlet, must be: ' + str(PORTLETS))\r\n# portletName = \"MASSIVE\"\r\n# exit()\r\n#\r\n else:\r\n \r\n print(\"\\n\\n\\n********************* START OF SCRIPT *********************\\n\\n\\n\")\r\n\r\n if portletName == \"ALL\":\r\n allPortlets(list_i18n, list_language)\r\n\r\n else:\r\n if portletName == \"BASE\":\r\n allPortlets(list_i18n, list_language)\r\n\r\n elif portletName == \"CRUD\":\r\n crudCheck(list_i18n, list_language, portletName)\r\n\r\n elif portletName == \"BACKOFFICE\":\r\n backOfficeCheck(list_language, portletName)\r\n\r\n elif portletName == \"MASSIVE\":\r\n massiveFirmwareUpdateCheck(list_language, portletName)\r\n\r\n elif portletName == \"CUSTOM LOGIN\":\r\n customLoginCheck(list_language, portletName)\r\n\r\n elif portletName == \"INTEGRATION\":\r\n integrationCheck(list_language, portletName)\r\n\r\n elif portletName == \"LIFERAY TRANSLATION\":\r\n liferayTranslationCheck(list_language, portletName)\r\n\r\n elif portletName == \"NOTIFICATION\":\r\n notificationCheck(list_language, portletName)\r\n\r\n elif portletName == \"REPORT\":\r\n reportCheck(list_language, portletName)\r\n\r\n elif portletName == \"FRONTEND\":\r\n v2FrontEndCheck(list_language, portletName)\r\n\r\n \r\n print(\"\\n\\n\\n********************* END OF SCRIPT *********************\\n\\n\\n\")\r\n\r\nmain()","sub_path":"check_translation.py","file_name":"check_translation.py","file_ext":"py","file_size_in_byte":14248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"267412415","text":"import discord\nimport os\nimport random\nfrom discord.ext import commands, tasks\n\nclass help(commands.Cog):\n\tdef __init__(self, client):\n\t\tself.client = client\n\n\t@commands.command(help='Shows this message')\n\tasync def help(self,ctx,cog=None):\n\t\tcogs = self.client.cogs.keys() if cog == None else [cog]\n\t\tfor each in cogs:\n\t\t\tembed = discord.Embed(title=f\"Help {each}\",color = discord.Color(0x44FF44)) if each != 'help' else discord.Embed(title=f\"Help\",color = discord.Color(0x44FF44))\n\t\t\tfor command in self.client.get_cog(each).get_commands():\n\t\t\t\tcommand_value = f'{self.client.command_prefix}{command.name}'\n\t\t\t\tfor para in command.params:\n\t\t\t\t\tif '=' in str(command.params[para]):\n\t\t\t\t\t\tcommand_value += f' [{para}]'\n\t\t\t\t\telif not para in [\"self\",\"ctx\"]:\n\t\t\t\t\t\t command_value += f' <{para}>'\n\t\t\t\tembed.add_field(name=f\"`{command_value}`\",value=f\"{command.help}\",inline=False)\n\t\t\tawait ctx.send(embed=embed)\n\n\n\ndef setup(client):\n\tclient.add_cog(help(client))","sub_path":"dist/cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"347047639","text":"\"\"\" \nData structure for implementing experience replay\n\nAuthor: Patrick Emami\n\"\"\"\nfrom collections import deque\nimport random\nimport numpy as np\n\nclass ReplayBuffer(object):\n\n def __init__(self, buffer_size, random_seed=123):\n \"\"\"\n The right side of the deque contains the most recent experiences \n \"\"\"\n self.buffer_size = buffer_size\n self.count = 0\n self.buffer = deque()\n random.seed(random_seed)\n \n def store(self, s, psi, a, r):\n batch_size = s.shape[0]\n for i in range(batch_size):\n experience = (s[i], psi[i], a[i], r[i])\n if self.count < self.buffer_size: \n self.buffer.append(experience)\n self.count += 1\n else:\n self.buffer.popleft()\n self.buffer.append(experience)\n\n def size(self):\n return self.count\n\n def sample_batch(self, batch_size):\n batch = []\n if self.count < batch_size:\n batch = random.sample(self.buffer, self.count)\n else:\n batch = random.sample(self.buffer, batch_size)\n\n s_batch = [_[0] for _ in batch]\n psi_batch = [_[1] for _ in batch]\n a_batch = [_[2] for _ in batch]\n r_batch = [_[3] for _ in batch]\n\n return s_batch, psi_batch, a_batch, r_batch\n\n def clear(self):\n self.buffer.clear()\n self.count = 0\n","sub_path":"spg/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"244744407","text":"import cmath\nimport math\nimport numpy as np\n\ndef fft(signal):\n\t\"\"\"Performs a fft on a given signal.\n\n\t:param signal: signal\n\t:type signal: list, numpy array\n\t:returns:Frequency domain representation of signal\n\t:rtype: numpy array\n\t\"\"\"\n\n\treturn _fftHelper(signal, 1)\n\ndef ifft(transformed):\n\t\"\"\"Performs an inverse fft on a given transformed signal.\n\n\t:param trasnformed: transformed signal\n\t:type transformed: list, numpy array\n\t:returns: Inverted signal\n\t:rtype: numpy array\n\t\"\"\"\n\n\treturn _fftHelper(transformed, -1)/len(transformed)\n\ndef fft2(image):\n\t\"\"\"Performs a 2-dimensional fft on a given image.\n\n\t:param image: image\n\t:type image: 2-dimensional list, numpy array\n\t:returns: Frequency domain representation of image\n\t:rtype: 2-dimensional numpy array\n\t\"\"\"\n\n\treturn _fft2Helper(image, 1)\n\ndef ifft2(image):\n\t\"\"\"Performs an inverse 2-dimensional fft on a given transformed image.\n\n\t:param image: transformed image\n\t:type image: 2-dimensional list, numpy array\n\t:returns: Inverted image\n\t:rtype: 2-dimensional numpy array\n\t\"\"\"\n\n\treturn _fft2Helper(image, -1)\n\ndef fft2Helper(image, direction):\n\ttransformed = np.empty(image.shape, dtype=complex)\n\tfor k in range(len(image)):\n\t\ttransformed[k] = _fftHelper(image[k],direction)\n\tfor k in range(len(image[0])):\n\t\ttransformed[:,k] = _fftHelper(transformed[:,k],direction)\n\n\treturn transformed\n\ndef _bitReverseOrder(signal):\n\tN = len(signal)\n\tnumBits = int((N-1).bit_length())\n\tlog2 = int(math.log(N,2))\n\tnewSignal = np.empty_like(signal)\n\tfor i in range(N):\n\t\tbinary = bin(i).replace('0b', '').replace('0B', '').zfill(numBits)\n\t\treverseBinary = binary[::-1]\n\t\tnewSignal[int(reverseBinary,2)] = signal[i]\n\n\treturn newSignal\n\ndef _fftHelper(signal, direction=1):\n\tN = len(signal)\n\tlog2 = math.log(N,2)\n\tif int(log2) != log2:\n\t\tprint(\"Signal length must be a power of 2\")\n\n\tsignal = _bitReverseOrder(signal).astype(complex)\n\n\tfor level in range(1, int(log2+1)):\n\t\tn = 2**level\n\t\tOMEGA = np.complex64(cmath.exp(direction*-2*cmath.pi*1J/n))\n\t\tfor i in range(0,N,n):\n\t\t\tomega = 1\n\t\t\tfor j in range(n//2):\n\t\t\t\tfirst = signal[i + j]\n\t\t\t\tsecond = omega*signal[i + j + n/2]\n\t\t\t\tsignal[i + j] = first + second\n\t\t\t\tsignal[i + j + n/2] = first - second\n\t\t\t\tomega = omega*OMEGA\n\n\treturn signal\n","sub_path":"pygasp/fft/fftIterative.py","file_name":"fftIterative.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"101278516","text":"class InitialCondition(Expression):\n\tdef eval_cell(self, value, x, ufc_cell):\n\t\tvalue[0] = np.random.rand(1)\n\nu_D = Expression(\"rand()/100000\", degree=1)\n\n\nclass FEMMesh:\n\t'A class which should be able to incorporate all meshes, created or given, and provides all necessary parameters and values'\n\tdef __init__(self, Mesh, Name, Gender, Source, h_real, u_max_start, SaveFile): #createMesh = True):\n\t\t#if createMesh == False:\n\t\t#read in the given mesh\n\t\tself.mesh = Mesh\n\t\t#define name for FileName purposes\n\t\tself.name = Name\n\t\t#define the gender\n\t\tself.gender = Gender\n\t\t#get the h value\n\t\tself.h_real = h_real\n\t\t#make it a dolfin Constant:\n\t\tself.h = Constant(h_real)\n\t\t#define the u_max_start value, the max concentration of Cdc42, used for h calculation:\n\t\tself.u_max_start = u_max_start\n\n\t\t#create the File to save the calculated data in\n\t\ttry:\n\t\t\tself.saveFile = File(SaveFile)\n\t\texcept RuntimeError:\n\t\t\tself.saveFile = XDMFFile(SaveFile)\n\n\t\tself.mesh = Mesh\n\n\t\t#Make it an only surface mesh, unordered, meaning every normal vector points outwards\n\t\tself.boundaryMesh = BoundaryMesh(Mesh, 'exterior', False)\n\t\t#write it to File\n\t\t#self.fileName = 'mesh_%s_unordered.xml' % self.name\n\t\t#File(self.fileName) << self.boundaryMesh \n\t\t#parse it back in to extract the Orientation\n\t\t#self.tree = ET.parse(self.fileName)\n\t\t#self.triangles = self.tree.findall('mesh/cells/triangle')\n\t\t#order the mesh so it can be iterated over\n\t\tself.boundaryMesh.order()\n\t\t#get vertex coordinates for growing purposes\n\t\tself.coordinates = self.boundaryMesh.coordinates()\n\t\t#initialize vertex edge connectivity\n\t\tself.boundaryMesh.init(0,1)\n\t\t#splice the mesh into x splices and determine which vertex to put into which splice_\n\t\t#self.classArrayHoldingSlices = meshSlicing(self, amountOfSlices)\n\t\t#save every cells orientation as an array\n\t\tself.orientation = meshClassOrientation(self, straightLengthFactor)\n\t\t#self.orientation = myCellOrientation(self, amountOfSlices, straightLengthFactor)\n\t\t#get normalvector for every cell:\n\t\tself.normalVectors = cellNormals(self.boundaryMesh)\n\t\t#get the starting rmax() (inner radius of all cells, max) value to compare against to trigger Refinement\n\t\tself.start_hmax = self.boundaryMesh.hmax()\n\n\t\t#create a functionSpace, for future use\n\t\tself.functionSpace = FunctionSpace(self.boundaryMesh, 'CG', 1)\n\t\t#create trial and test-functions:\n\t\tif activeSurfaceSource == True:\n\t\t\tself.trialFunction = interpolate(Constant(0.0), self.functionSpace) #(u)\n\t\telse:\n\t\t\tself.trialFunction = interpolate(u_D, self.functionSpace) #interpolate(Constant(0.0), self.functionSpace)\n\t\tself.testFunction = TestFunction(self.functionSpace) #(v)\n\t\t#create function for solutions at current time-step: (u_1_n)\n\t\tself.currentSolutionFunction = Function(self.functionSpace)\n\n\t\t#define the meshes Source\n\t\tself.source = Source\n\t\t#define the meshes Stimulus, refers to global parameters as of now, should be changed in the future\n\t\t#Element is given so dolfin evaluates the optimal quadrature degree according to the given Expression.\n\t\t#testStimulus is for plotting in 2D\n\n\t\t#self.stimulus = Expression('(1.0-h)*Ka/std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2) + pow(x[2] - source2, 2)) * exp(-std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2) + pow(x[2] - source2, 2))/std::sqrt(Ds/kb))',\\\n \t\t#\telement = self.functionSpace.ufl_element(), Ka = Ka, Ds = Ds, kb = kb, h=Constant(self.h_real), source0=self.source[0], source1=self.source[1], source2=self.source[2])\n\t\tself.twoDStimulus = Expression('(1.0-h)*Ka/std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2)) * exp(-std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2))/std::sqrt(Ds/(kb * Ka/std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2)))))',\\\n \t\t\telement = self.functionSpace.ufl_element(), Ka = Ka, Ds = Ds, kb = kb, h=Constant(self.h_real), source0=self.source[0], source1=self.source[1])\n\t\tself.stimulus = Expression('(1.0-h)*Ka/std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2) + pow(x[2] - source2, 2)) * exp(-std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2) + pow(x[2] - source2, 2))/std::sqrt(Ds/(kb * Ka/std::sqrt(pow(x[0] - source0, 2) + pow(x[1] - source1, 2) + pow(x[2] - source2, 2)))))',\\\n \t\t\telement = self.functionSpace.ufl_element(), Ka = Ka, Ds = Ds, kb = kb, h=Constant(self.h_real), source0=self.source[0], source1=self.source[1], source2=self.source[2])\n\t\t\n\n\t\t#get the stimulusString, required for the user defined add function\n\t\tself.stimulusString = self.getStimulusString()\t\t\n\t\t#get the starting vertex and the corresponding cell:\n\t\tif activeSurfaceSource == True:\n\t\t\tself.stimulusCell = correspondingCell(self.boundaryMesh, self.coordinates[closestVertex(self.coordinates, self.source)])\n\n\n\t\t#init the PDE. Rmember that the myRefinement Function creates a new PDE so PDE and after-refinement-mesh are matching.\n\t\t#Because of lack of better knowing it is just these lines copied. Always change both if you want to make changes!\n\t\tself.PDE = inner((self.currentSolutionFunction - self.trialFunction) / k, self.testFunction)*dx - Dm*inner(nabla_grad(self.trialFunction), nabla_grad(self.testFunction))*dx \\\n\t\t - (1.0-self.h)*(nu*k0 + (nu*K*self.trialFunction**2)/(Km**2 + self.trialFunction**2))*self.testFunction*dx + eta*self.trialFunction*self.testFunction*dx - self.stimulus*self.testFunction*dx\n\n\n\n\t\t#create a variable that saves the inital u_sum, should be assigned only at n=0 of course\n\t\tself.u_sum_initial = None\n\t\t#get the needed maps:\n\t\t#get a vertex to cells map, so which vertex is part of which cells\n\t\tself.vertex_to_cells_map = vertex_to_cells_map(self)\n\t\t#create array with vertices and corresponding normals:\n\t\tself.vertex_normal_map = vertex_normal_map(self, self.vertex_to_cells_map, self.normalVectors)\n\t\t#calculate the map to get the vertices to be grown. Which cell has which vertices\n\t\tself.cell_to_vertices_map = cell_to_vertices_map(self)\n\n\t\t#initialize the gradient, for later use\n\t\tself.gradient = None\n\t\t#calculate the startingvolumes of the cells to scale u_max later on. Since the volume is expanding more Cdc42 should be available\n\t\tself.startVolume = self.getVolume()\n\n\t\t#if activeSurfaceSource == False, a growthThreshold is needed\n\t\tself.growthThreshold = None\n\t\t#initialize the cellGrowthDeterminingArray, is used in the growth\n\t\tself.cellGrowthDeterminingArray = None\n\t\t#init list of vertices to Grow\n\t\tself.verticesToGrow = None\n\t\t#create CellFunction\n\t\tself.cell_markers_boundary = MeshFunction('bool', self.boundaryMesh, self.boundaryMesh.topology().dim(), False) #CellFunction(\"bool\", self.boundaryMesh)\n\t\t#self.cell_markers_boundary.set_all(True)\n\t\tself.isThereRefinementNecessary = False\n\t\tself.hmin = self.boundaryMesh.hmin()\n\n\t\t#force on vertex:\n\n\t\tself.vertex_to_edges_map = vertex_to_edges_map(self)\n\t\tself.initial_cell_edges_and_opposite_angle_map = cell_edges_and_opposite_angle_map(self)\n\t\t#at creation these should be equal, so no need to calculate twice\n\t\tself.cell_edges_and_opposite_angle_map = None #self.initial_cell_edges_and_opposite_angle_map #cell_edges_and_opposite_angle_map(self)\n\n\t\tself.force_on_vertex_list = [None]*self.boundaryMesh.num_vertices()\n\n\t\tself.Estar = None\n\n\t\tself.turgor_pressure_on_vertex_list = [None]*self.boundaryMesh.num_vertices()\n\t\tself.cell_volumes = cell_volumes(self)\n\n\t#calculate the volume of the mesh\n\tdef getVolume(self):\n\t\treturn assemble(Constant(1)*Measure(\"dx\", domain=self.boundaryMesh))\n\n\t# helper function, the stimulus string is needed to add Stimuli and create fitting Expressions\n\tdef getStimulusString(self):\n\t\ttempStimulusString = '(1.0-%s)*Ka/std::sqrt(pow(x[0] - %f, 2) + pow(x[1] - %f, 2) + pow(x[2] - %f, 2)) * exp(-std::sqrt(pow(x[0] - %f, 2) + pow(x[1] - %f, 2) + pow(x[2] - %f, 2))/std::sqrt(Ds/kb))' %(self.name ,self.source[0],self.source[1],self.source[2],self.source[0],self.source[1],self.source[2])\n\t\treturn tempStimulusString\n\tdef getStimulusStringWithH(self):\n\t\ttempStimulusString = '(1.0-h)*Ka/std::sqrt(pow(x[0] - %f, 2) + pow(x[1] - %f, 2) + pow(x[2] - %f, 2)) * exp(-std::sqrt(pow(x[0] - %f, 2) + pow(x[1] - %f, 2) + pow(x[2] - %f, 2))/std::sqrt(Ds/kb))' %(self.source[0],self.source[1],self.source[2],self.source[0],self.source[1],self.source[2])\n\t\treturn tempStimulusString\n\n\t# ONLY USED TO ADD THE STIMULI, NOT THE WHOLE CLASS!\n\tdef __add__(self, other):\n\t\tif isinstance(self, FEMMesh):\n\t\t\tif isinstance(other, FEMMesh):\n\t\t\t\t#print 'self and other are FEMMesh'\n\t\t\t\tnewExpressionString = self.getStimulusString() + ' + ' + other.getStimulusString()\n\t\t\t\t#print(newExpressionString)\n\t\t\t\t#print(\"first source: \", self.source[:], 'second source: ', other.source[:])\n\t\t\t\tkwargs = {'element' : self.functionSpace.ufl_element() ,str(self.name) : Constant(self.h_real), str(other.name) : Constant(other.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t\t\treturn Expression(newExpressionString, **kwargs)\n\t\t\telif isinstance(other, Expression):\n\t\t\t\t#print 'self is FEMMesh, other is Expression'\n\t\t\t\tnewExpressionString = self.getStimulusString()\n\t\t\t\tkwargs = {'element' : self.functionSpace.ufl_element() ,str(self.name) : Constant(self.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t\t\treturn Expression(newExpressionString, **kwargs) + other\n\t\t\t# if the other is already a Sum of two Expressions, needed an extra case:\n\t\t\telif str(type(other)) == \"<class 'ufl.algebra.Sum'>\":\n\t\t\t\tnewExpressionString = self.getStimulusString()\n\t\t\t\tkwargs = {'element' : self.functionSpace.ufl_element() ,str(self.name) : Constant(self.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t\t\treturn Expression(newExpressionString, **kwargs) + other\n\t\t# elif isinstance(self, Expression):\n\t\t# \tif isinstance(other, FEMMesh):\n\t\t# \t\t#print 'self is Expression, other is FEMMesh'\n\t\t# \t\tnewExpressionString = other.getStimulusString()\n\t\t# \t\tkwargs = {'element' : other.functionSpace.ufl_element() ,str(other.name) : Constant(other.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t# \t\treturn Expression(newExpressionString, **kwargs) + self\n\t\t# \telif isinstance(other, Expression):\n\t\t# \t\t#print 'self and other are Expressions'\n\t\t# \t\treturn self + other\n\n\t# get the gradient of all relevant Stimuli on my mesh\n\tdef getGradient(self, usedMeshesList):\n\t\ttempCumulatedStimuli = None\n\t\tfor Mesh in usedMeshesList:\n\t\t\tif Mesh != self: #everyone but myself\n\t\t\t\tif Mesh.gender != self.gender: #everyone of the opposite gender\n\t\t\t\t\t#print self.name, self.gender,'s opposite gender:', Mesh.name, Mesh.gender\n\t\t\t\t\tif tempCumulatedStimuli == None:\n\t\t\t\t\t\ttempCumulatedStimuli = Mesh\n\t\t\t\t\telse:\n\t\t\t\t\t\ttempCumulatedStimuli = Mesh + tempCumulatedStimuli\n\t\t#if no other gender is detected, take your \"own\" stimulus. Should mean an artifical stimulus has been applied\n\t\tif tempCumulatedStimuli == None:\n\t\t\ttempCumulatedStimuli = self.stimulus\n\t\t#print tempCumulatedStimuli\n\t\t#check if the overloaded add function has been used, if not make an Expression:\n\t\ttry:\n\t\t\tself.gradient = gradient(project(tempCumulatedStimuli, self.functionSpace))\n\t\t\treturn self.gradient\n\t\texcept TypeError:\n\t\t\tif isinstance(tempCumulatedStimuli, Expression):\n\t\t\t\tprint( 'gradient creation: tempCumulatedStimuli is an Expression')\n\t\t\t\tself.gradient = gradient(interpolate(tempCumulatedStimuli, self.functionSpace))\n\t\t\t\treturn self.gradient\n\t\t\telif isinstance(tempCumulatedStimuli, self.__class__):\n\t\t\t\tprint( 'gradient creation: tempCumulatedStimuli is a Sum')\n\t\t\t\tself.gradient = gradient(interpolate(tempCumulatedStimuli, self.functionSpace))\n\t\t\t\treturn self.gradient\n\t\t\t# elif isinstance(tempCumulatedStimuli, FEMMesh): #create an Expression which can be used in the gradient function. Similar to the __add__ function, just with one class\n\t\t\t# \tprint 'gradient creation: tempCumulatedStimuli is a FEMMesh'\n\t\t\t# \tkwargs = {'element' : self.functionSpace.ufl_element() ,str(tempCumulatedStimuli.name) : Constant(tempCumulatedStimuli.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t\t# \ttempOnlyOneStimulusExpression = Expression(tempCumulatedStimuli.getStimulusString(), **kwargs)\n\t\t\t# \tself.gradient = gradient(project(tempOnlyOneStimulusExpression, self.functionSpace))\n\t\t\t# \treturn self.gradient\n\t\t\treturn self.gradient\n\t\t# if there is only one Mesh for the gradient to consider:\n\t\texcept:\n\t\t\t#kwargs = {'element' : self.functionSpace.ufl_element() ,str(tempCumulatedStimuli.name) : Constant(tempCumulatedStimuli.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\t\t#tempOnlyOneStimulusExpression = Expression(tempCumulatedStimuli.getStimulusString(), **kwargs)\n\t\t\tself.gradient = gradient(interpolate(tempCumulatedStimuli.stimulus, self.functionSpace))\n\t\t\treturn self.gradient\n\n\t#if there are no activeSurfaceAreas the stimulus for each mesh has to be precalculated after initializing all meshes.\n\t#this is achieved by adding the stimuli strings of all other FEMMeshes and compiling it into an Expression\n\tdef initSources(self, usedMeshesList):\n\t\t#i have to create a new self.stimulus which is basically all stimuli but my own added\n\t\ttempNewStimulusString = None\n\t\tfor FEMMeshes in usedMeshesList:\n\t\t\tif FEMMeshes != self and FEMMeshes.gender != self.gender:\n\t\t\t\tif tempNewStimulusString == None:\n\t\t\t\t\ttempNewStimulusString = FEMMeshes.getStimulusStringWithH()\n\t\t\t\telse:\n\t\t\t\t\ttempNewStimulusString = tempNewStimulusString + ' + ' + FEMMeshes.getStimulusStringWithH()\n\t\t#if no other gender is detected, take your \"own\" stimulus. Should mean an artifical stimulus has been applied\n\t\tif tempNewStimulusString == None:\n\t\t\ttempNewStimulusString = self.getStimulusStringWithH()\n\t\t\tprint('i am here:', tempNewStimulusString)\n\t\tkwargs = {'element' : self.functionSpace.ufl_element(), 'h' : Constant(self.h_real), \"Ka\" : Ka, 'Ds' : Ds, 'kb' : kb}\n\t\tself.stimulus = Expression(tempNewStimulusString, **kwargs)\n\n\t# used to reinitialize the PDE after initSources() was run. Updates the PDE function with the latest stimuli\n\tdef initPDE(self):\n\t\tself.PDE = inner((self.currentSolutionFunction - self.trialFunction) / k, self.testFunction)*dx - Dm*inner(nabla_grad(self.trialFunction), nabla_grad(self.testFunction))*dx \\\n\t\t - (1.0-self.h)*(nu*k0 + (nu*K*self.trialFunction**2)/(Km**2 + self.trialFunction**2))*self.testFunction*dx + eta*self.trialFunction*self.testFunction*dx - self.stimulus*self.testFunction*dx\n\n\n","sub_path":"classes_backup.py","file_name":"classes_backup.py","file_ext":"py","file_size_in_byte":14160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"73216399","text":"import json\nimport pandas as pd\n\npath = 'data/vectors.txt'\nword = 'data/vocab.txt'\nnums = 'data/vectors_num.txt'\n\ntrain_data = 'data/train_num.txt'\ntest_data = 'data/test_num.txt'\ntrain_json = 'data/train_json.json'\ntest_json = 'data/test_json.json'\ntrain_csv = 'data/train_csv.csv'\ntest_csv = 'data/test_csv.csv'\n\n# f1 = open(train_csv, 'w')\n# f2 = open(test_csv, 'w')\n\nf_train_data = open(train_data, 'r')\nf_test_data = open(test_data, 'r')\n# f_train_json = open(train_json, 'w')\n# f_test_json = open(test_json, 'w')\n\nf = open(path, 'r')\nf_w = open(word, 'r')\n\n\ncont = f_w.readline()\nword_dict = dict()\ncount = 0\nwhile cont:\n\n word = cont.split(' ')\n word_dict[word[0]] = count\n if count == 0:\n word_dict[' '] = 0\n cont = f_w.readline()\n count += 1\nprint(word_dict)\n\n\ndef v_num():\n f_n = open(nums, 'w')\n cont = f.readline()\n count = 0\n while cont:\n cont = cont.split(\" \", 1)\n res = []\n res.append(str(word_dict.get(cont[0], 126865)))\n res.append(cont[1])\n w = \" \".join(res)\n count += 1\n print(w)\n f_n.write(w)\n cont = f.readline()\n\n\ndef to_json(f_data, f_json):\n cont = f_data.readline()\n while cont:\n cont = cont.strip('\\n')\n cont = cont.split(\" \", 1)\n label = cont[0]\n vector = cont[1]\n temp = dict()\n print(label)\n temp['label'] = label\n temp['text'] = vector\n json.dump(temp, f_json)\n cont = f_data.readline()\n\n\ndef to_csv(f_data, f_csv):\n cont = f_data.readline()\n res = []\n while cont:\n cont = cont.strip('\\n')\n cont = cont.split(\" \", 1)\n label = cont[0]\n vector = cont[1]\n temp = dict()\n temp['label'] = label\n temp['text'] = vector\n res.append(temp)\n cont = f_data.readline()\n print(res)\n pd.DataFrame(res).to_csv(f_csv)\n\n\n# to_json(f_test_data, f_test_json)\n# to_json(f_train_data, f_train_json)\n#v_num()\nto_csv(f_train_data, train_csv)\nto_csv(f_test_data, test_csv)\n","sub_path":"cnn/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"204922959","text":"#coding: utf-8\nfrom django.contrib import admin\nfrom SpendControl.invoice.models import *\nfrom SpendControl.budget.widgets import *\n\nclass InvoiceAdmin(admin.ModelAdmin):\n fieldsets = (\n (u'Нэхэмжлэл', {'fields':('no', 'account', 'date_invoiced', 'deadline',\n 'amount', 'has_tax', 'discount', 'is_paid',\n 'partner', 'partner_name', 'contact', 'currency', 'language')}),\n )\n list_display = ('no', 'account', 'date_invoiced', 'deadline', 'amount', 'currency',\n 'has_tax', 'partner', 'partner_name', 'contact', 'discount', 'is_paid')\n list_filter = ('deadline', 'is_paid', 'language')\n search_fields = ('no', )\n \n def formfield_for_dbfield(self, db_field, **kwargs):\n if db_field.name == 'partner':\n db = kwargs.get('using')\n options = {\n 'display':'name',\n 'search':('name',),\n 'rowitem':('name','diamond_code',),\n 'styles':['style=\"width:70%; text-align:left;\"',\n 'style=\"width:30%; text-align:right;font-style:itallic\"'],\n 'width': 350\n }\n kwargs['widget'] = extForeignKeyFlexboxWidget(db_field.rel, options, using=db)\n try:\n del kwargs['request']\n except KeyError:\n pass\n return db_field.formfield(**kwargs)\n \n return super(InvoiceAdmin, self).formfield_for_dbfield(db_field, **kwargs)\n\nadmin.site.register(Invoice, InvoiceAdmin)\n\nclass Own_ProductAdmin(admin.ModelAdmin):\n list_display = ('name', 'description')\n search_fields = ('name', 'description')\n \nadmin.site.register(Own_Product, Own_ProductAdmin)","sub_path":"src/invoice/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"371616115","text":"\n\nfrom xai.brain.wordbase.nouns._dressmaker import _DRESSMAKER\n\n#calss header\nclass _DRESSMAKERS(_DRESSMAKER, ):\n\tdef __init__(self,): \n\t\t_DRESSMAKER.__init__(self)\n\t\tself.name = \"DRESSMAKERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dressmaker\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dressmakers.py","file_name":"_dressmakers.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"2252330","text":"#SetupRules pushes defined rules to SQL table for later use\n#insertData receives a row and inserts it into sql table\n\nimport Config.Config as config\nimport pandas as pd\nimport psycopg2\nimport Tables.CreateMatchRules as MRtable\n\n\ndef create_data_table():\n \"\"\" createDataTable creates SQL table that will hold data matching rules \"\"\"\n cur = config.conn.cursor()\n cmd = MRtable.createTable\n try:\n cur.execute(cmd)\n config.conn.commit()\n except Exception as err:\n print(err)\n config.conn.rollback()\n\n\ndef insert_data(row):\n \"\"\" insert_data inserts data into data matching table \"\"\"\n cur = config.conn.cursor()\n SQLInsert = \"\"\" INSERT INTO public.\"MatchingRules\"(columnname, replacementphrase, regexpattern) VALUES (%s, %s, %s); \"\"\"\n data = (row[0], row[1], row[2])\n try:\n cur.execute(SQLInsert, data) \n config.conn.commit()\n except Exception as err:\n print(err)\n config.conn.rollback()\n \n\ndef push_data(df):\n \"\"\" push_data iterates over df rows and calls insert_data\n to insert them into SQL table \"\"\"\n for i, row in df.iterrows():\n insert_data(row)\n\ndef push_matching_rules(mode): \n \"\"\" pushMatchingRules defines and then handles data matching rules.\n These rules are stored and then pulled when formatting CSV data later\n As wil the DZD rules table, you'd want to define these elsewhere in \n production \"\"\"\n print(\"Setting up data matching rules...\")\n #You'd probably want a different insertion method,\n #but of that implementation would be easy.\n #Define rules -> insert into SQL table\n matchDictionary = {\n 'columnname': ['antibiotic'],\n 'replacementphrase': ['Trimethoprim/Sulfamethoxazole'],\n 'regexpattern': ['/.*\\\\b(Trimeth.*|Sulfa.*)\\\\b.*'] \n }\n df = pd.DataFrame(data=matchDictionary)\n df = df.applymap(lambda x: x.strip())\n\n if(mode == 0):\n print(df)\n elif(mode == 1):\n push_data(df)\n elif(mode == 2):\n create_data_table()\n push_data(df)\n print(\"Done setting up data rules table\")\n \n","sub_path":"PythonModules/src/SetupDataRules.py","file_name":"SetupDataRules.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"111014876","text":"import unittest\nfrom question4 import Dictionary\n\nclass TestAssociation(unittest.TestCase):\n# question 4(a) -- Testing if the method can add an item\n def testAddition(self):\n data = {\"name\": \"Kamali\", \"age\": 45}\n forTest = Dictionary.addition(data)\n self.assertNotEqual(forTest, \"Karemera\")\n\n# question 4(b) -- Testing item is removed\n def testRemove(self):\n data = {\"name\": \"Kamali\", \"age\": 45}\n forTest = Dictionary.remove(data)\n self.assertEqual(forTest, \"name\")\n\n# question 4(c) -- Testing if the dictionary was modified\n def testModify(self):\n data = {\"name\": \"Kamali\", \"age\": 45}\n forTest = Dictionary.modify(data)\n self.assertEqual(forTest, 40)\n\n# question 4(d) -- Testing for checking an item\n def testLookup(self):\n data = {\"name\": \"Kamali\", \"age\": 45}\n forTest = Dictionary.lookup(data)\n self.assertEqual(forTest, 5)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"testquestion4.py","file_name":"testquestion4.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"151851422","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport os\nimport time\nimport glob\n\nAPPNAME = 'ltdc-display-2layers'\nVERSION = 'v0.2'\n\ntop\t= '.'\nout\t= 'build'\n\ndef options(opt):\n\n\topt.load('gcc gas')\n\n\topt.add_option('--toolchain', action='store', default='arm-none-eabi-', help='Set toolchain prefix')\n\ndef configure(cfg):\n\n\tprint('→ configuring the project in ' + cfg.path.abspath())\n\t# Toolchain configurations\n\tcfg.env.CC = cfg.options.toolchain + \"gcc\"\n\tcfg.env.AR = cfg.options.toolchain + \"ar\"\n\tcfg.env.AS = cfg.options.toolchain + \"gcc\"\n\t#use 'gcc' rather than 'ld'\n\tcfg.env.LD = cfg.options.toolchain + \"gcc\"\n\tcfg.env.OBJCOPY = cfg.options.toolchain + 'objcopy'\n\tcfg.env.OBJDUMP = cfg.options.toolchain + 'objdump'\n\tcfg.env.SIZE = cfg.options.toolchain + 'size'\n\tcfg.load('gcc gas')\n\n\tcfg.find_program('ld', var='LD')\n\tcfg.find_program('objcopy', var='OBJCOPY')\n\tcfg.find_program('objdump', var='OBJDUMP')\n\tcfg.find_program('size', var='SIZE')\n\tcfg.find_program('st-flash', var='st-flash')\n\t\n\n\t# Cortex-M4 implements the ARMv7E-M architecture\n\tlink_script = '../CORTEX_M4F_STM32F4/STM32F429ZI_FLASH.ld'\n\n\tcfg.env.append_unique('CFLAGS',\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\t\t'-mcpu=cortex-m4','-march=armv7e-m', '-mtune=cortex-m4', '-mlittle-endian'\n\t\t\t\t\t\t\t\t\t\t\t\t, '-mthumb','-g','-std=c99','-Wall','-mfpu=fpv4-sp-d16','-mfloat-abi=softfp'\n\t\t\t \t\t\t\t\t\t\t\t\t,'-g','-std=c99','-Wall','-O3','-ffast-math','-ffunction-sections'\n\t\t\t \t\t\t\t\t\t\t\t\t,'-fdata-sections','-Wl,--gc-sections','-fno-common'\n\t\t\t \t\t\t\t\t\t\t\t\t,'--param','max-inline-insns-single=1000'\n\t\t\t \t\t\t\t\t\t\t\t\t])\n\t# My Src File\n\tcfg.env.append_unique('FILES_STM32F429',\t['Src/*.c'])\n\t\n\t# STARTUP FILE\n\tcfg.env.append_unique('FILES_STM32F429',\t['CORTEX_M4F_STM32F4/startup_stm32f429xx.s'])\n\t\n\t# Drivers/STM32F4xx_HAL_Driver\n\tcfg.env.append_unique('FILES_LIB',\t\t\t['STM32Cube_FW_F4_V1.8.0/Drivers/STM32F4xx_HAL_Driver/Src/*.c'])\n\n\t# Drivers/BSP/STM32F429I_DISCO\n\tcfg.env.append_unique('FILES_LIB',\t\t\t['STM32Cube_FW_F4_V1.8.0/Drivers/BSP/STM32F429I-Discovery/stm32f429i_discovery.c'])\n\t\n\t# Drivers/BSP/Components\n\tcfg.env.append_unique('FILES_LIB',\t\t\t['STM32Cube_FW_F4_V1.8.0/Drivers/BSP/Components/ili9341/ili9341.c'])\n\t\n\t# My Inc File\n\tcfg.env.append_unique('INCLUDES_STM32F429',['Inc'])\n\n\t# All STM32F4 Include\n\tcfg.env.append_unique('INCLUDES_LIB',\t\t['STM32Cube_FW_F4_V1.8.0/Drivers/BSP/STM32F429I-Discovery'\n\t\t\t\t\t\t\t\t\t\t\t\t,'STM32Cube_FW_F4_V1.8.0/Drivers/BSP/Components/ili9341'\n\t\t\t\t\t\t\t\t\t\t\t\t,'STM32Cube_FW_F4_V1.8.0/Drivers/STM32F4xx_HAL_Driver/Inc'\n\t\t\t\t\t\t\t\t\t\t\t\t,'STM32Cube_FW_F4_V1.8.0/Drivers/CMSIS/Include'\n\t\t\t\t\t\t\t\t\t\t\t\t,'STM32Cube_FW_F4_V1.8.0/Drivers/CMSIS/Device/ST/STM32F4xx/Include'\n\t\t\t\t\t\t\t\t\t\t\t\t])\n\t# to run from FLASH (Wait)\n\tcfg.env.append_unique('LINKFLAGS_STM32F429',[\n\t\t\t\t\t\t\t\t\t\t\t\t'-T{0}'.format(link_script)\n\t\t\t\t\t\t\t\t\t\t\t\t,'-mthumb','-march=armv7e-m','-mfloat-abi=softfp','-mfpu=fpv4-sp-d16'\n\t\t\t\t\t\t\t\t\t\t\t\t,'-mcpu=cortex-m4','-mtune=cortex-m4'\n\t\t\t\t\t\t\t\t\t\t\t\t# Disable Semihosting\n\t\t\t\t\t\t\t\t\t\t\t\t,'--specs=nosys.specs'\n\t\t\t\t\t\t\t\t\t\t\t\t#,'--print-multi-lib'\n\t\t#,'/usr/local/gcc-arm/bin/../lib/gcc/arm-none-eabi/5.3.1/../../../../arm-none-eabi/lib/libc.a'\n\t\t#,'/usr/local/gcc-arm/bin/../lib/gcc/arm-none-eabi/5.3.1/libgcc.a'\n\t\t\t\t\t\t\t\t\t\t\t\t])\n\t\n\t#My Define\n\tcfg.env.append_unique('DEFINES_STM32F429', \n\t\t[\n\t\t'STM32F429xx',\n\t\t'VECT_TAB_FLASH',\n\t\t#'\"assert_param(expr)=((void)0)\"',\n\t\t'USE_HAL_DRIVER','USE_STM32F429I_DISCO'\n\t\t]\n\t\t)\n\ndef build(bld):\n\t\n\tprint('→ building the project in ' + bld.path.abspath())\n\t\n\tbld.program(\n source = bld.path.ant_glob(bld.env.FILES_STM32F429) + bld.path.parent.parent.ant_glob(bld.env.FILES_LIB),\n includes = bld.env.INCLUDES_STM32F429 + bld.path.parent.parent.ant_glob(bld.env.INCLUDES_LIB,dir=True, src=False),\n target ='LTDC-Display-2Layers.elf',\n defines = bld.env.DEFINES_STM32F429,\n linkflags = bld.env.LINKFLAGS_STM32F429, \n )\n\n\tbld(rule='${OBJCOPY} -O binary ${SRC} ${TGT}', source='LTDC-Display-2Layers.elf', target='LTDC-Display-2Layers.bin', name='objcopy')\n\tbld(rule='${SIZE} ${SRC}', source='LTDC-Display-2Layers.elf', always=True, name='size')\n\ndef program(pgm):\n\tpgm(rule='st-flash write ${SRC} 0x8000000', source='LTDC-Display-2Layers.bin', name='STLINK', always=True)\n\nfrom waflib.Build import BuildContext\nclass Program(BuildContext):\n\tcmd = 'program'\n\tfun = 'program'\n\t","sub_path":"LTDC_Display_2Layers/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"220023266","text":"#!/usr/bin/env python\nimport RPi.GPIO as GPIO\nimport time\n\ncolors = [0xFF00, 0x00FF, 0x0FF0, 0xF00F]\n\ndef setupPins(rPin, gPin):\n\tpins = (rPin, gPin)\n\n\tGPIO.setmode(GPIO.BOARD)\n\tGPIO.setup(pins, GPIO.OUT)\n\tGPIO.output(pins, GPIO.LOW)\n\n\tp_R = GPIO.PWM(pins[0], 2000)\n\tp_G = GPIO.PWM(pins[1], 2000)\n\n\tp_R.start(0)\n\tp_G.start(0)\n\n\treturn {\"p_R\": p_R, \"p_G\": p_G}\n\t\n\ndef map(x, in_min, in_max, out_min, out_max):\n\treturn (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n\ndef setColor(col, p_G, p_R):\n\tprint(col)\n\tR_val = col >> 8\n\tG_val = col & 0x00FF\n\n\tR_val = map(R_val, 0, 255, 0, 100)\n\tG_val = map(G_val, 0, 255, 0, 100)\n\t\n\tp_R.ChangeDutyCycle(R_val)\n\tp_G.ChangeDutyCycle(G_val)\n\t\n\treturn[p_R, p_G]\n\ndef loop(action, rPin, gPin):\n\t\n\tpins = setupPins(rPin, gPin)\n\t\n\tif action == \"ON\":\n\t\tresult = setColor(colors[0], pins.get(\"p_G\"), pins.get(\"p_R\"))\n\t\t#turn on the light\n\t\t\n\n\telif action == \"OFF\":\n\t\tdestroy(pins.get(\"p_G\"), pins.get(\"p_R\"))\n\t\tresult = False\n\n\treturn result\n\ndef destroy(p_G, p_R):\n\tp_R.stop()\n\tp_G.stop()\n\tGPIO.output(pins, GPIO.LOW)\n\tGPIO.cleanup()\n\n\n","sub_path":"prototypes/ledFix.py","file_name":"ledFix.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"205750871","text":"import numpy as np\n\nfrom snc.agents.hedgehog.asymptotic_workload_cov.\\\n compute_asymptotic_cov_bernoulli_service_and_arrivals \\\n import ComputeAsymptoticCovBernoulliServiceAndArrivals\nfrom tests.snc.agents.hedgehog.asymptotic_covariance.\\\n test_compute_asymptotic_cov_utils import perform_test as perform_test\nfrom snc.environments import examples\n\n\ndef test_compute_covariance_arrival_process():\n demand_rate = np.array([[0.2], [0.4], [0.6]])\n cov_arrival = ComputeAsymptoticCovBernoulliServiceAndArrivals.\\\n compute_covariance_arrival_process(demand_rate)\n np.testing.assert_almost_equal(cov_arrival,\n np.array([[0.16, 0, 0], [0, 0.24, 0], [0, 0, 0.24]]))\n\n\ndef test_compute_asymptotic_cov_service_process_simple_reentrant_line():\n job_gen_seed = 42\n np.random.seed(job_gen_seed + 100)\n num_batch = 400\n num_data = num_batch * 200\n env = examples.simple_reentrant_line_model(initial_state=np.zeros((3, 1)))\n perform_test(env, num_batch, num_data, ComputeAsymptoticCovBernoulliServiceAndArrivals,\n job_gen_seed)\n","sub_path":"tests/snc/agents/hedgehog/asymptotic_covariance/test_computer_asymptotic_cov_bernoulli_service_and_arrivals.py","file_name":"test_computer_asymptotic_cov_bernoulli_service_and_arrivals.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"620618188","text":"##\r\n# This module defines a spatiotemporal filter based off of the ensemble Kalman filter.\r\n#\r\n# @author Joseph Campbell <jacampb1@asu.edu>, Interactive Robotics Lab, Arizona State University\r\nimport numpy as np\r\nimport numpy.linalg\r\nimport scipy.linalg\r\n\r\nimport intprim.constants as constants\r\nfrom intprim.filter.spatiotemporal import nonlinear_system\r\n\r\n\r\n##\r\n# The EnsembleKalmanFilter class localizes an interaction in time and space via Monte Carlo approximation of the Kalman filter.\r\n# This class is a recursive filter, meaning it maintains state information between successive calls to localize().\r\n# As with the other spatiotemporal filters, the EnsembleKalmanFilter's internal state consists of (N+1) dimensions modeling\r\n# the N-th order phase system plus B dimensions modeling the latent space of the interaction.\r\n# However, unlike the ExtendedKalmanFilter, this class does not maintain a single explicit state instance.\r\n# Instead, an internal ensemble of E members is maintained, such that the ensemble matrix dimension is (N+1)+B x E.\r\n# As a result, no explicit covariance matrix is maintained. Instead, the covariance is modeled implicitly in the\r\n# ensemble via the sample covariance.\r\n# This class corresponds to an Ensemble Bayesian Interaction Primitive.\r\n#\r\n# References:\\n\r\n# Campbell, J., Stepputtis, S., & Ben Amor, H. (2019). Probabilistic Multimodal Modeling for Human-Robot Interaction Tasks.\\n\r\n# Evensen, G. (2003). The ensemble Kalman filter: Theoretical formulation and practical implementation. Ocean dynamics, 53(4), 343-367.\\n\r\n#\r\nclass EnsembleKalmanFilter(nonlinear_system.NonLinearSystem):\r\n ##\r\n # The initialization method for the EnsembleKalmanFilter. Responsible for creating the initial ensemble.\r\n #\r\n # @param basis_model The basis model corresponding to this state space.\r\n # @param initial_phase_mean Vector of dimension N corresponding to the initial mean of the constant velocity phase system. If this is a 0th order system, should contain only [phase_mean]. If this is 1st order, should contain [phase_mean, phase_velocity]. If this is 2nd order, should contain [phase_mean, phase_velocity, phase_acceleration]. Anything above 2nd order is not supported.\r\n # @param initial_phase_var Vector of dimension N corresponding to the diagonal of the initial covariance of the constant velocity phase system. If this is a 0th order system, should contain only [phase_var]. If this is 1st order, should contain [phase_var, phase_velocity_var]. If this is 2nd order, should contain [phase_var, phase_velocity_var, phase_acceleration_var]. Anything above 2nd order is not supported.\r\n # @param proc_var The process noise of the constant velocity phase system. This is a scalar value corresponding to the variance of a piecewise white noise model.\r\n # @param initial_ensemble Matrix of dimension E x B which represents an initial ensemble. Typically, this is just the set of basis weights corresponding to E training demonstrations.\r\n # @param time_delta The amount of time that elapses between time steps. This serves as a scaling factor to the constant velocity phase system. In most cases, this should be set to 1.0.\r\n # @param cyclical Indicates whether this is a cyclical primitive. If True, the internal phase state will cycle back to 0 once it exceeds 1, allowing for continuous inference of periodic interactions.\r\n #\r\n def __init__(self,\r\n basis_model,\r\n initial_phase_mean,\r\n initial_phase_var,\r\n proc_var,\r\n initial_ensemble,\r\n time_delta = 1.0,\r\n cyclical = False):\r\n super(EnsembleKalmanFilter, self).__init__(basis_model, proc_var, time_delta, len(initial_phase_mean) - 1)\r\n\r\n self.ensemble_size = initial_ensemble.shape[0]\r\n self.cyclical = cyclical\r\n\r\n initial_phase_mean = np.array(initial_phase_mean, dtype = constants.DTYPE)\r\n initial_phase_var = np.diag(initial_phase_var).astype(constants.DTYPE)\r\n\r\n self.ensemble = np.zeros((self.state_dimension, self.ensemble_size))\r\n self.ensemble[:self.system_size, :] = np.random.multivariate_normal(initial_phase_mean[:self.system_size], initial_phase_var[:self.system_size, :self.system_size], size = self.ensemble_size).T\r\n\r\n self.ensemble[self.system_size:, :] = initial_ensemble.T\r\n\r\n ##\r\n # Calculates the unbiased sample mean of the ensemble.\r\n # The formula used to compute the mean is: $$ \\\\bar{\\\\boldsymbol{X}} = \\\\frac{1}{E} \\\\sum_{j=1}^{E} \\\\boldsymbol{x}^{j}, $$\r\n # where \\f$ \\boldsymbol{x}^{j} \\in \\mathbb{R}^{N+1+B} \\f$ and \\f$ \\bar{\\boldsymbol{X}} \\in \\mathbb{R}^{N+1+B}. \\f$\r\n #\r\n # @param ensemble The ensemble from which to calculate the sample mean. If None, uses the internal state ensemble.\r\n #\r\n # @returns Vector of dimension N+1+B containing the sample mean.\r\n #\r\n def get_ensemble_mean(self, ensemble = None):\r\n if(ensemble is None):\r\n return np.sum(self.ensemble, axis = 1) / self.ensemble_size\r\n else:\r\n return np.sum(ensemble, axis = 1) / self.ensemble_size\r\n\r\n ##\r\n # Calculates the unbiased sample covariance of the ensemble.\r\n # The formula used to compute the covariance is: $$ cov(\\\\boldsymbol{X}) = \\\\frac{1}{E - 1} \\\\boldsymbol{A} \\\\boldsymbol{A}^{T}, \\\\qquad \\\\boldsymbol{A} = \\\\boldsymbol{X} - \\\\bar{\\\\boldsymbol{X}}, $$\r\n # where \\f$ cov(\\boldsymbol{X}) \\in \\mathbb{R}^{N+1+B \\times N+1+B}. \\f$\r\n #\r\n # @param ensemble The ensemble from which to calculate the sample covariance. If none, uses the internal state ensemble.\r\n #\r\n # @returns Matrix of dimension N+1+B x N+1+B containing the sample covariance.\r\n #\r\n def get_ensemble_covariance(self, ensemble = None):\r\n mean = self.get_ensemble_mean(ensemble)\r\n\r\n if(ensemble is None):\r\n deviation = (self.ensemble.T - mean).T\r\n else:\r\n deviation = (ensemble.T - mean).T\r\n\r\n # Ensemble variance is the square deviation divided by the ensemble size - 1. [1]\r\n return np.dot(deviation, deviation.T) / (self.ensemble_size - 1.0)\r\n\r\n ##\r\n # Calculates the unbiased sample mean and covariance of the ensemble projected into the observation space.\r\n # This is computed by first projecting the entire ensemble to measurement space then calculating the sample covariance.\r\n # Mathematically, calculating the sample covariance and then projecting it should be equivalent but numerical issues sometimes arise and so this method is preferred.\r\n # The formula used to compute the covariance is: $$ cov(\\\\boldsymbol{H} \\\\boldsymbol{X}) = \\\\frac{1}{E - 1} (\\\\boldsymbol{H}\\\\boldsymbol{A}) (\\\\boldsymbol{H} \\\\boldsymbol{A}^{T}), \\\\qquad \\\\boldsymbol{H} \\\\boldsymbol{A} = \\\\boldsymbol{X} - \\\\frac{1}{E} \\\\sum_{j=1}^{E}h(\\\\boldsymbol{x}^j), $$\r\n # where \\f$ cov(\\boldsymbol{H} \\boldsymbol{X}) \\in \\mathbb{R}^{D \\times D} \\f$ and \\f$ h(\\cdot) \\f$ is the nonlinear observation function.\r\n #\r\n # @param phase The phase value \\f$ \\phi \\f$ to use for the projection.\r\n # @param ensemble The ensemble from which to calculate the projected mean and covariance. If none, uses the internal state ensemble.\r\n #\r\n # @returns Vector of dimension D containing the sample mean, matrix of dimension D x D containing the sample covariance.\r\n #\r\n def get_projected_mean_covariance(self, phase, ensemble = None):\r\n if(ensemble is None):\r\n ensemble = self.ensemble\r\n\r\n if(phase is None):\r\n orig_mean = self.get_ensemble_mean(ensemble)\r\n phase = orig_mean[0]\r\n\r\n # Project ensemble to measurement dimension\r\n hx_matrix = np.zeros((self.measurement_dimension, self.ensemble_size), dtype = constants.DTYPE)\r\n for index in range(self.ensemble_size):\r\n hx_matrix[:, index] = self.basis_model.apply_coefficients(phase, ensemble[self.system_size:, index])\r\n\r\n # Calculate ensemble covariance.\r\n # Could calculate in state space then project, but should be the same.\r\n mean = np.sum(hx_matrix, axis = 1) / self.ensemble_size\r\n deviation = (hx_matrix.T - mean).T\r\n # Ensemble variance is the square deviation divided by the ensemble size - 1. [1]\r\n covariance = np.dot(deviation, deviation.T) / (self.ensemble_size - 1.0)\r\n\r\n return mean, covariance\r\n\r\n ##\r\n # The nonlinear observation function \\f$ h(\\cdot) \\f$ which maps an input state of dimension \\f$ \\mathbb{R}^{B} \\f$ to an output observation of dimension \\f$ \\mathbb{R}^D. \\f$\r\n # This is simply the dot product of the basis functions to the corresponding basis weights.\r\n # The nonlinearity comes from the usage of the phase state variable as a parameter to the basis functions.\r\n #\r\n # @param state Vector of dimension N+1+B which is the state to be projected.\r\n #\r\n # @returns Vector of dimension D containing the projected state.\r\n #\r\n def h(self, state):\r\n return self.basis_model.apply_coefficients(state[0], state[self.system_size:])\r\n\r\n ##\r\n # This method computes the projection of the ensemble to the observation space.\r\n # Each member is projected such that the input ensemble is mapped from \\f$ \\mathbb{R}^{N+1+B \\times E} \\f$ to \\f$ \\mathbb{R}^{D \\times E} \\f$.\r\n # The formula used to compute this is: $$ \\\\boldsymbol{H} \\\\boldsymbol{X} = \\\\left[h(\\\\boldsymbol{x}^1), \\\\dots, h(\\\\boldsymbol{x}^E) \\\\right]. $$\r\n #\r\n # @param output_matrix Matrix of dimension D x E in which the results should be stored.\r\n #\r\n def hx(self, output_matrix):\r\n for index in range(self.ensemble_size):\r\n output_matrix[:, index] = self.h(self.ensemble[:, index])\r\n\r\n ##\r\n # This method performs simultaneous localization of both time (phase) and space (basis weights).\r\n # This is a recursive call, which means it updates the internal state estimate based on the given observations.\r\n # For each observation given, two steps are performed recursively:\r\n # First, the current ensemble is propagated forward in time in what is known as the prediction step.\r\n # $$ \\\\boldsymbol{x}^j_{t|t-1} = \\\\boldsymbol{G} \\\\boldsymbol{x}^j_{t-1|t-1} + \\\\mathcal{N} \\\\left(0, \\\\boldsymbol{Q}_t\\\\right), \\\\quad 1 \\\\leq j \\\\leq E. $$\r\n # Note that in this case, we only apply the dot product to the first N+1 dimensions of the state. This is for computational efficiency as only the constant velocity phase system has a non-zero transition.\r\n #\r\n # Next, we integrate the observations into the current ensemble in the update step.\r\n # $$ \\\\boldsymbol{H}_t\\\\boldsymbol{A}_t = \\\\boldsymbol{H}_t \\\\boldsymbol{X}_{t|t-1} - \\\\left[ \\\\frac{1}{E} \\\\sum_{j=1}^{E}h(\\\\boldsymbol{x}^j_{t|t-1}), \\\\dots, \\\\frac{1}{E} \\\\sum_{j=1}^{E}h(\\\\boldsymbol{x}^j_{t|t-1}) \\\\right], $$\r\n # $$ \\\\boldsymbol{S}_t = \\\\frac{1}{E - 1} (\\\\boldsymbol{H}_t \\\\boldsymbol{A}_t) (\\\\boldsymbol{H}_t\\\\boldsymbol{A}_t)^T + \\\\boldsymbol{R}_t, $$\r\n # $$ \\\\boldsymbol{A}_t = \\\\boldsymbol{X}_{t|t-1} - \\\\frac{1}{E} \\\\sum_{j=1}^{E} \\\\boldsymbol{x}^j_{t|t-1}, $$\r\n # $$ \\\\boldsymbol{K}_t = \\\\frac{1}{E - 1} \\\\boldsymbol{A}_t (\\\\boldsymbol{H}_t \\\\boldsymbol{A}_t)^T \\\\boldsymbol{S}^{-1}_t. $$\r\n #\r\n # Lastly, the sample mean and covariance of the ensemble are returned.\r\n # At the end of both the prediction and update steps the internal phase value is clipped such that it falls within the range [0, 1].\r\n #\r\n # @param measurement Matrix of dimension T x D containing observations, where T is the number of timesteps that have been observed since the last call to localize() and D is the dimension of the measurement space.\r\n # @param measurement_noise Matrix of dimension D x D containing the measurement noise for the given set of measurements.\r\n # @param active_dofs Vector of dimension \\f$ D_o \\f$ containing measurement space indices of the observed degrees of freedom. Note that the measurements will also contain unobserved degrees of freedom, but their values should not be used for inference.\r\n # @param return_phase_variance True if the mean/variance for the phase system should be returned in addition to the basis weights.\r\n #\r\n # @returns Scalar value containing the inferred phase, Vector of dimension D (or N+1+D if return_phase_variance is True) containing inferred mean, Matrix of dimension D x D (or N+1+D x N+1+D if return_phase_variance is True).\r\n def localize(self, measurement, measurement_noise, active_dofs, return_phase_variance = False):\r\n transition_model = self.get_transition_model()\r\n hx_matrix = np.zeros((self.measurement_dimension, self.ensemble_size), dtype = constants.DTYPE)\r\n\r\n nonactive_dofs = np.setdiff1d(range(self.measurement_dimension), active_dofs)\r\n\r\n for measurement_idx in range(measurement.shape[0]):\r\n # Make forward prediction for each ensemble member\r\n for index in range(self.ensemble_size):\r\n self.ensemble[:self.system_size, index] = np.dot(transition_model[:self.system_size, :self.system_size], self.ensemble[:self.system_size, index])\r\n\r\n # Project the phase values to be bounded by [0, 1]\r\n self.ensemble[0, self.ensemble[0, :] > 1.0] = 1.0\r\n self.ensemble[0, self.ensemble[0, :] < 0.0] = 0.0\r\n\r\n # Add process noise to predictions\r\n self.ensemble[:self.system_size, :] += np.random.multivariate_normal(np.zeros(self.system_size), self.phase_process_noise, size = self.ensemble_size, check_valid = \"ignore\").T\r\n\r\n noisy_observations = np.zeros((self.ensemble_size, self.measurement_dimension))\r\n if(active_dofs.shape[0] > 0):\r\n noisy_observations[:, active_dofs] = np.random.normal(0, np.diagonal(measurement_noise), size = (self.ensemble_size, self.measurement_dimension))[:, active_dofs]\r\n\r\n noisy_observations[:, active_dofs] += measurement[measurement_idx][active_dofs]\r\n\r\n\r\n mean = self.get_ensemble_mean()\r\n\r\n # Calculate HX\r\n self.hx(hx_matrix)\r\n\r\n # Calculate A\r\n a = (self.ensemble.T - mean).T\r\n # Calculate HA\r\n ha = (hx_matrix.T - (np.sum(hx_matrix, axis = 1) / self.ensemble_size)).T\r\n\r\n # Calculate S\r\n covariance_residual = (1.0 / (self.ensemble_size - 1.0)) * np.dot(ha, ha.T) + measurement_noise\r\n\r\n # Calculate K\r\n kalman_gain = (1.0 / (self.ensemble_size - 1.0)) * np.dot(a, ha.T).dot(np.linalg.pinv(covariance_residual))\r\n # Zero out the Kalman gain entries for the non-active DoFs. Since we aren't considering them we don't want them to affect the update process.\r\n kalman_gain[:, nonactive_dofs] = 0.0\r\n\r\n # Update the ensemble\r\n self.ensemble += kalman_gain.dot(noisy_observations.T - hx_matrix)\r\n\r\n # If the interaction is cyclical and the mean is greater than 1.0, then subtract 1.0 from all ensemble members.\r\n # Some may be less than 0, but that is ok since the mean is still greater than 0.\r\n if(self.cyclical):\r\n mean = self.get_ensemble_mean()\r\n if(mean[0] >= 1.0):\r\n self.ensemble[0, :] -= 1.0\r\n\r\n # Project the phase values to be bounded by [0, 1]\r\n self.ensemble[0, self.ensemble[0, :] > 1.0] = 1.0\r\n self.ensemble[0, self.ensemble[0, :] < 0.0] = 0.0\r\n\r\n expected_value = self.get_ensemble_mean()\r\n expected_variance = self.get_ensemble_covariance()\r\n\r\n\r\n if(return_phase_variance is False):\r\n return expected_value[0], expected_value[self.system_size:], expected_variance[self.system_size:, self.system_size:]\r\n else:\r\n return expected_value[0], expected_value[:], expected_variance[:, :]\r\n","sub_path":"intprim/filter/spatiotemporal/enkf.py","file_name":"enkf.py","file_ext":"py","file_size_in_byte":16013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"275082440","text":"from Tkinter import *\n\n\nclass ToolsPanel(Frame):\n def __init__(self, master, *args, **kwargs):\n Frame.__init__(self, master, *args, **kwargs)\n\n self.config(bd=1, relief=RAISED, padx=2, pady=2)\n self.default_bg = self.cget('bg')\n self.columnconfigure(0, weight=1)\n self.columnconfigure(1, weight=1)\n self.columnconfigure(2, weight=1)\n self.rowconfigure(1, weight=1)\n self.rowconfigure(2, weight=1)\n self.rowconfigure(3, weight=1)\n self.rowconfigure(4, weight=1)\n\n # Title\n title_lbl = Label(self, text=\"Tools\", bd=2, relief=FLAT, fg=\"slate gray\")\n title_lbl.grid(row=0, columnspan=3, sticky='ew')\n\n Label(self, text=\"Time axis:\", fg=\"dim gray\").grid(row=1, column=0, sticky='ew')\n Label(self, text=\"Temp. axis:\", fg=\"dim gray\").grid(row=1, column=1, sticky='ew')\n\n self.x_lim_txt = StringVar()\n self.y_lim_txt = StringVar()\n self.x_lim_ent = Entry(self, textvariable=self.x_lim_txt, justify=CENTER, width=8)\n self.x_lim_ent.grid(row=2, column=0, sticky='ew')\n self.y_lim_ent = Entry(self, textvariable=self.y_lim_txt, justify=CENTER, width=8)\n self.y_lim_ent.grid(row=2, column=1, sticky='ew')\n\n self.set_axes_btn = Button(self, text=\"Set\")\n self.set_axes_btn.grid(row=2, column=2, sticky='nsew')\n\n Label(self, text=\"Text: \", fg=\"dim gray\").grid(row=3, column=0, sticky='ew')\n self.text_txt = StringVar()\n self.text_ent = Entry(self, textvariable=self.text_txt)\n self.text_ent.grid(row=4, column=0, columnspan=2, sticky='ew')\n\n self.add_text_btn = Button(self, text=\"Add\")\n self.add_text_btn.grid(row=4, column=2, sticky='nsew')\n\n self.add_txt = StringVar()\n Label(self, textvariable=self.add_txt, fg=\"dim gray\").grid(row=5, column=0, columnspan=3, sticky='ew')\n","sub_path":"gui/create_graph/ToolsPanel.py","file_name":"ToolsPanel.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"641752265","text":"# ##############################################################################\n# This file is part of Interdiode #\n# #\n# Copyright (C) 2020 Matthieu Gallet <matthieu.gallet@19pouces.net> #\n# All Rights Reserved #\n# #\n# ##############################################################################\nimport os\nimport shutil\nimport sys\n\nfrom django.core.checks import Error, register, Warning\n\nfrom df_config.guesses.pipeline import (\n available_compilers,\n available_css_compressor,\n available_js_compressors,\n)\nfrom df_config.utils import is_package_present\n\nsettings_check_results = []\n\n\ndef missing_package(package_name, desc=\"\"):\n if hasattr(sys, \"real_prefix\"): # inside a virtualenv\n cmd = \"Try 'python -m pip install %s' to install it.\" % package_name\n elif __file__.startswith(os.environ.get(\"HOME\", \"/home\")):\n cmd = \"Try 'python3 -m pip install --user %s' to install it.\" % package_name\n else:\n cmd = \"Try 'sudo python3 -m pip install %s' to install it.\" % package_name\n return Warning(\n \"Python package '%s' is required%s. %s\" % (package_name, desc, cmd),\n obj=\"configuration\",\n )\n\n\ndef get_pipeline_requirements():\n from df_config.config.base import merger\n\n engine_to_binaries = {} # engine_to_binaries[\"eng.ine\"] = \"ENGINE_BINARY\"\n engine_to_binaries.update({x[0]: x[1] for x in available_css_compressor if x[1]})\n engine_to_binaries.update({x[0]: x[1] for x in available_js_compressors if x[1]})\n engine_to_binaries.update({x[0]: x[1] for x in available_compilers if x[1]})\n engines = [\n merger.settings.get(\"PIPELINE_CSS_COMPRESSOR\", \"\"),\n merger.settings.get(\"PIPELINE_JS_COMPRESSOR\", \"\"),\n ]\n engines += merger.settings.get(\"PIPELINE_COMPILERS\", [])\n pip_packages = {\n \"pipeline.compressors.jsmin.JSMinCompressor\": (\"jsmin\", \"jsmin\"),\n \"pipeline.compressors.slimit.SlimItCompressor\": (\"slimit\", \"slimit\"),\n \"df_config.apps.pipeline.RcssCompressor\": (\"rcssmin\", \"rcssmin\"),\n \"df_config.apps.pipeline.PyScssCompiler\": (\"scss\", \"pyScss\"),\n }\n result = {\"gem\": [], \"pip\": [], \"npm\": [], \"other\": [], \"all\": []}\n for engine in engines:\n if engine in engine_to_binaries:\n name = merger.settings.get(engine_to_binaries[engine], \"program\")\n result[\"all\"].append(name)\n elif engine in pip_packages:\n result[\"pip\"].append(pip_packages[engine])\n for v in result.values():\n v.sort()\n return result\n\n\n# noinspection PyUnusedLocal\n@register()\ndef pipeline_check(app_configs, **kwargs):\n return settings_check_results\n\n\n# noinspection PyUnusedLocal\n@register()\ndef pipeline_check(app_configs, **kwargs):\n \"\"\"Check if dependencies used by `django-pipeline` are installed.\n \"\"\"\n check_results = []\n requirements = get_pipeline_requirements()\n for name in requirements[\"all\"]:\n if not shutil.which(name):\n check_results.append(\n Error(\n \"'%s' is required by 'django-pipeline' and is not found in PATH.\"\n % name,\n obj=\"configuration\",\n )\n )\n for name, package in requirements[\"pip\"]:\n if not is_package_present(name):\n check_results.append(missing_package(package, \" by 'django-pipeline'\"))\n return check_results\n","sub_path":"venv/Lib/site-packages/df_config/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"409250624","text":"# ARTICLES ADMIN:\n\nfrom django.contrib import admin\nfrom photologue.models import Photo\nfrom articles.models import Article,Column,Letter,LetterResponse\nfrom photologue.models import ArticleInlinePhoto\n\nclass ArticleInlinePhotoInline(admin.StackedInline):\n\tmodel = ArticleInlinePhoto\n\t\n\t\nclass ArticleAdmin(admin.ModelAdmin):\n\tlist_display = ('get_title', 'get_issue', 'is_featured','get_contributors','status','content_type','article_type','pub_type',)\n\tlist_editable = ('is_featured','content_type','article_type','status','pub_type',)\n\tsearch_fields = ('issue__issue_number', 'title','tagline','content') \n\tlist_filter = ('created','article_type','pub_type','content_type',)\n\tordering = ('-modified',)\n\tprepopulated_fields = {'slug': ('title',)} \n\tfieldsets = (\n\t\t(None, {\n\t\t\t'fields': ('created','issue','title', 'subtitle', 'tagline', 'introduction', 'content', 'contributors', 'photographer', 'url','slug','listen_url',)\n\t\t}),\n\t\t('Display', {\n\t\t\t'fields': ('is_featured', 'in_feed', 'status','theme','accepts_related_intro','custom_editorial_ad',)\n\t\t}),\n\t\t('Meta', {\n\t\t\t'fields': ('article_type', 'content_type', 'pub_type','parent_article',)\n\t\t}),\n\t\t('Comments', {\n\t\t\t'fields': ('allow_comments', 'comments_need_approval',)\n\t\t}),\n\t)\n\t\n\tfilter_horizontal = ('contributors',)\n\tinlines = [\n\t\tArticleInlinePhotoInline,\n\t]\n\t\n\tclass Media:\n\t\tjs = ['admin/media/tinymce/jscripts/tiny_mce/tiny_mce.js', 'admin/media/tinymce_setup/tinymce_setup.js',]\n\t\t\n\nclass LetterResponseInline(admin.StackedInline):\n\tmodel = LetterResponse\n\t\n\t\nclass LetterAdmin(admin.ModelAdmin):\n\tlist_display = ('sender_name', 'issue','get_excerpt','status','created')\n\tsearch_fields = ('issue__issue_number', 'sender_name','sender_email','content') \n\tlist_filter = ('created',)\n\tfieldsets = (\n\t\t(None, {\n\t\t\t'fields': ('issue','sender_name', 'sender_email', 'sender_url', 'sender_location', 'sender_company', 'content',)\n\t\t}),\n\t\t('Display', {\n\t\t\t'fields': ('is_featured', 'in_feed', 'status',)\n\t\t}),\n\t\t('Meta', {\n\t\t\t'fields': ('pub_type',)\n\t\t}),\n\t\t('Comments', {\n\t\t\t'fields': ('allow_comments', 'comments_need_approval',)\n\t\t}),\n\t)\n\t\n\tinlines = [\n\t\tLetterResponseInline,\n\t]\n\t\n\tclass Media:\n\t\tjs = ['admin/media/tinymce/jscripts/tiny_mce/tiny_mce.js', 'admin/media/tinymce_setup/tinymce_setup.js',]\n\t\t\n\t\t\nclass ColumnAdmin(admin.ModelAdmin):\n\tlist_display = ('issue', 'column_type','get_contributors','get_excerpt','status','created')\n\tsearch_fields = ('issue__issue_number','column_type','content',) \n\tlist_filter = ('issue',)\n\tfieldsets = (\n\t\t(None, {\n\t\t\t'fields': ('issue','column_type','title','content','contributors')\n\t\t}),\n\t\t('Display', {\n\t\t\t'fields': ('is_featured', 'in_feed', 'status',)\n\t\t}),\n\t\t('Meta', {\n\t\t\t'fields': ('pub_type',)\n\t\t}),\n\t)\n\tfilter_horizontal = ('contributors',)\n\t\n\tclass Media:\n\t\tjs = ['admin/media/tinymce/jscripts/tiny_mce/tiny_mce.js', 'admin/media/tinymce_setup/tinymce_setup.js',]\n\n\t\t\n\nadmin.site.register(Article,ArticleAdmin)\nadmin.site.register(Letter,LetterAdmin)\nadmin.site.register(Column,ColumnAdmin)\n","sub_path":"app/articles/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"593303917","text":"import os\nfrom argparse import ArgumentParser\nfrom glob import glob\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom detectron2 import model_zoo\nfrom detectron2.config import get_cfg\nfrom detectron2.data.datasets import coco, register_coco_instances\nfrom detectron2.engine import DefaultPredictor\n\nfrom constants import IMG_FORMAT, IMG_NAME_FORMAT\n\n\ndef detect_cars(image_dir_path,\n mask_img_path,\n car_predictor,\n score_thres=0.9,\n roi_thres=0.5):\n\n mask_img = cv2.imread(mask_img_path)\n dilate_kernel = np.ones((5, 5), np.uint8)\n mask_img = cv2.dilate(mask_img, dilate_kernel, iterations=5)\n mask_img = mask_img.astype(np.float32) / 255\n\n detection_list = []\n img_array = sorted(glob(image_dir_path + \"/*.\" + IMG_FORMAT))\n num_frames = len(img_array)\n for idx in tqdm(range(num_frames)):\n frame_id = idx + 1\n img_name = IMG_NAME_FORMAT % frame_id\n img_path = os.path.join(image_dir_path, img_name)\n img = cv2.imread(img_path)\n outputs = predictor(img)\n predictions = outputs[\"instances\"].to(\"cpu\")\n\n boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n scores = predictions.scores if predictions.has(\"scores\") else None\n num_instances = 0\n if boxes is not None:\n boxes = boxes.tensor.numpy()\n num_instances = len(boxes)\n if scores is not None:\n scores = scores.numpy()\n\n frame_detections = []\n if num_instances > 0:\n for i in range(num_instances):\n x1, y1, x2, y2 = boxes[i]\n score = scores[i]\n if score > score_thres:\n box = (x1, y1, x2, y2, score)\n masked = mask_img[int(y1):int(y2), int(x1):int(x2), :]\n mean = np.mean(masked)\n if mean > roi_thres:\n frame_detections.append(box)\n\n detection_list.append(frame_detections)\n\n return detection_list\n\n\ndef save_detection_result(detection_list, out_file_path):\n with open(out_file_path, 'w') as f:\n for i, bbox_list in enumerate(detection_list):\n for bbox in bbox_list:\n f.write(\"%d,%f,%f,%f,%f,%f\\n\" %\n (i + 1, bbox[0], bbox[1], bbox[2], bbox[3], bbox[4]))\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"image_dir_path\", help=\"Path to background image directory\")\n parser.add_argument(\"mask_base_path\", help=\"Path to ROI mask\")\n parser.add_argument(\"out_base_path\", help=\"Path to store detection result\")\n parser.add_argument(\"pretrained_model_path\", help=\"Path to pretrained car detection model\")\n args = parser.parse_args()\n\n cfg = get_cfg()\n cfg.merge_from_file(model_zoo.get_config_file(\"Misc/cascade_mask_rcnn_R_50_FPN_3x.yaml\"))\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1\n cfg.MODEL.MASK_ON = False\n cfg.MODEL.WEIGHTS = args.pretrained_model_path\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7\n\n vid_name = os.path.basename(args.image_dir_path)\n mask_img_path = os.path.join(args.mask_base_path, vid_name, \"mask.png\")\n predictor = DefaultPredictor(cfg)\n detection_list = detect_cars(args.image_dir_path, mask_img_path, predictor)\n\n out_dir_path = os.path.join(args.out_base_path, \"bg_detections\")\n if not os.path.exists(out_dir_path):\n os.mkdir(out_dir_path)\n out_file_path = os.path.join(out_dir_path, \"bg_test_%s.txt\" % vid_name)\n save_detection_result(detection_list, out_file_path)\n","sub_path":"detect_cars.py","file_name":"detect_cars.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"17062720","text":"'''\nCopyright 2015 Singapore Management University\n\nThis Source Code Form is subject to the terms of the\nMozilla Public License, v. 2.0. If a copy of the MPL was\nnot distributed with this file, You can obtain one at\nhttp://mozilla.org/MPL/2.0/.\n'''\n\n\"\"\"Notifications Module\n\n@created: Goh Kian Wei (Brandon), Kevin Koh, Shannon Lim, Tony Tran, Samantha Wee, Wong Si Hui\n@code_adapted_from: Chris Boesch, Daniel Tsou\n\"\"\"\n\"\"\"\nNote to self: json.loads = json string to objects. json.dumps is object to json string.\n\"\"\" \nimport datetime\nimport os\nimport urllib\nimport urllib2\n\nimport webapp2\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import db, webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nimport json\n\n#Handles Notification creation and retrieval\nclass Notification(db.Model):\n user_id = db.IntegerProperty(required=True) #ID of the User receiving the Notification\n notification_date = db.DateTimeProperty(auto_now_add=True) #The time that the model was created\n \n notification_type = db.StringProperty() #Type of Notification\n other_user = db.IntegerProperty() #The other User involved in the Notification (if applicable)\n # other_info = db.StringProperty()\n relevant_id = db.IntegerProperty() #Relevant information for the Notification\n message = db.StringProperty() #Notification message\n\n def to_dict(self):\n d = dict([(p, unicode(getattr(self, p))) for p in self.properties()])\n d[\"id\"] = self.key().id()\n return d\n \n #Adds a particular type of Notification\n @staticmethod\n def add(u_id=-1, type=\"\", o_user = 0, o_info = \"\", r_id = 0):\n if u_id != -1 and type != \"\":\n #Notification creation\n o_user_name = User.get_name(o_user)\n verify = False\n if type == \"GROUPINVITE\": #Group invitation for a User\n u_g = UserGroupMgmt.get_by_id(r_id)\n if u_g:\n relevant = Group.get_name(u_g.group_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has invited you to the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPACCEPT\": #Informs Group Founder of accepted invite\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has accepted your invitation to the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPREJECT\": #Informs Group Founder of rejected invite\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has rejected your invitation to the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPLEAVE\": #Informs Group Founder of a member who has left the Group\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has left the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPJOINCFM\": #Confirms to a User they have joined a Group\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = 0,\n relevant_id = r_id,\n message = \"You have joined the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPPASSFOUNDER\": #Informs User they are now the Founder of a Group\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has made you the Founder of the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPEXPEL\": #Informs User they have been expelled from a Group\n relevant = Group.get_name(r_id)\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = r_id,\n message = o_user_name + \" has kicked you from the group \" + relevant + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPDELETE\": #Informs all Users in a Group of its deletion\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = 0,\n message = o_user_name + \" has deleted the group \" + o_info + \".\")\n notify.put()\n verify = True\n elif type == \"GROUPDELCANCEL\": #Informs a User pending an invite that said Group was deleted\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = o_user,\n relevant_id = 0,\n message = o_user_name + \" has cancelled your invite and deleted the group \" + o_info + \".\")\n notify.put()\n verify = True \n elif type == \"ADMINDELETE\": #Informs a User that an administrator has deleted their sketch\n notify = Notification(user_id = u_id,\n notification_type = type,\n other_user = 0,\n relevant_id = 0,\n message = \"An administrator has deleted your sketch '\" + o_info + \"'.\")\n notify.put()\n verify = True\n return verify\n \n #Gets Notifications for a User, bounded by limits.\n @staticmethod\n def get_entities(user_id=-1, limit=0):\n #update ModelCount when adding\n u_id = int(user_id)\n theQuery = Notification.all()\n theQuery.order('-notification_date')\n\n objects = theQuery.run()\n utc = UTC()\n entities = []\n count = 0\n for object in objects:\n if object.user_id == int(user_id):\n n_date = object.notification_date.replace(tzinfo=utc).strftime(\"%d %b %Y %H:%M:%S\")\n o_user = User.get_name(object.other_user)\n \n entity = {'n_date':n_date,\n 'id': object.key().id(),\n 'n_message': object.message,\n 'n_type': object.notification_type,\n 'n_relevant': object.relevant_id,\n 'user_id': object.user_id}\n entities.append(entity) \n count += 1\n #Cutoff if limit was defined\n if limit != 0:\n if count == int(limit):\n break\n \n result = {'method':'get_entities',\n 'en_type': 'Notification',\n 'entities': entities,\n 'retrieved': count} \n return result\n \n#Imports placed below to avoid circular imports\nfrom rpx import User, UTC\nfrom sketches import Sketch\nfrom permissions_groups import Group, UserGroupMgmt\nfrom notifications import Notification \n ","sub_path":"notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":7884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"616558623","text":"# -*- coding: utf-8 -*-\n\nfrom decimal import Decimal\nfrom sqlalchemy.ext.associationproxy import association_proxy\n\nfrom . import db\nfrom .entity import Entity\nfrom .fiscal import FiscalData\nfrom .document import Document\n#from .product import ProductSupplierInfo\n\nclass Supplier(Entity):\n __tablename__ = 'supplier'\n __mapper_args__ = {'polymorphic_identity': 'supplier'}\n\n TYPE_PRODUCTS = 'TYPE_PRODUCTS'\n TYPE_SERVICES = 'TYPE_SERVICES'\n TYPE_SUPPLIES = 'TYPE_SUPPLIES'\n\n _sup_type = {\n TYPE_PRODUCTS: 'Productos',\n TYPE_SERVICES: 'Servicios',\n TYPE_SUPPLIES: 'Insumos',\n }\n\n supplier_id = db.Column(db.Integer, db.ForeignKey('entity.id'),\n primary_key=True)\n rz = Entity._name_1\n name = Entity._name_2\n web = db.Column(db.Unicode, default=None)\n\n sup_type = db.Column(db.Enum(*_sup_type.keys(), name='supplier_type'),\n default=TYPE_PRODUCTS)\n\n fiscal_data_id = db.Column(db.Integer, db.ForeignKey('fiscal_data.id'))\n fiscal_data = db.relationship(FiscalData,\n backref=db.backref('entity', uselist=False))\n\n payment_term = db.Column(db.Integer) # in days\n leap_time = db.Column(db.Integer) # in days\n delivery_included = db.Column(db.Boolean)\n\n supplier_contacts = db.relationship('SupplierContact',\n cascade='all, delete-orphan',\n backref='supplier')\n contacts = association_proxy('supplier_contacts', 'contact')\n\n debt = db.Column(db.Numeric(10, 2))\n expired = db.Column(db.Numeric(10, 2))\n expiration_date = db.Column(db.DateTime, default=None)\n\n #: 'bank_accounts' attribute added by BankAccount.supplier relation\n #: 'orders' attribute added by PurchaseOrder.supplier relation\n #: 'documents' attribute added by Document.supplier relation\n\n #: Inherited from Entity\n #: - address (collection)\n #: - email (collection)\n #: - phone (collection)\n #: - extra field (collection)\n\n# products = association_proxy('products_info', 'product')\n\n\n def add_contact(self, contact, role):\n self.supplier_contacts.append(SupplierContact(contact, role))\n\n# def add_product(self, product, **kwargs):\n# self.products_info.append(ProductSupplierInfo(product=product, **kwargs))\n\n @property\n def type(self):\n return self._sup_type.get(self.sup_type)\n\n @property\n def full_name(self):\n n = \" ({0})\".format(self.name) if self.name else ''\n return \"{0}{1}\".format(self.rz, n)\n\n def _update_expiration_date(self):\n doc = self.documents\\\n .filter(Document.doc_status.in_([Document.STATUS_PENDING,\n Document.STATUS_EXPIRED]))\\\n .order_by(Document.expiration_date.asc())\\\n .first()\n if doc:\n self.expiration_date = doc.expiration_date\n else:\n self.expiration_date = None\n\n@db.event.listens_for(Supplier, \"init\")\ndef supplier_init(target, args, kwargs):\n # Sets defaults to instance\n if 'delivery_included' not in kwargs:\n target.delivery_included = False\n if 'debt' not in kwargs:\n target.debt = Decimal(0)\n if 'expired' not in kwargs:\n target.expired = Decimal(0)\n\n\nclass SupplierContact(db.Model):\n __tablename__ = 'supplier_contact'\n supplier_id = db.Column(db.Integer, db.ForeignKey('supplier.supplier_id'),\n primary_key=True)\n contact_id = db.Column(db.Integer, db.ForeignKey('contact.contact_id'),\n primary_key=True)\n role = db.Column(db.Unicode)\n\n contact = db.relationship('Contact', backref='supplier_contacts',\n lazy='joined')\n\n def __init__(self, contact, role):\n self.contact = contact\n self.role = role\n","sub_path":"nas/models/supplier.py","file_name":"supplier.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"635874675","text":"import re\nfrom django.conf import settings\n\n\nclass RegisteredSitesMiddleware(object):\n\n def process_request(self, request):\n sites = getattr(settings, 'REGISTERED_SITES', None)\n if sites:\n host = request.get_host()\n for (regex, value) in sites:\n if re.search(regex, host):\n request.site = value\n break\n else:\n raise Exception('Missing REGISTERED_SITES setting')","sub_path":"apps/core/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"545572896","text":"class Solution:\n \"\"\"\n @param A : a list of integers\n @param target : an integer to be searched\n @return : an integer\n \"\"\"\n\n def search(self, A, target):\n # write your code here\n if len(A) == 0:\n return -1\n\n start, end = 0, len(A) - 1\n\n while start + 1 < end:\n mid = (start + end) // 2\n # judge the position\n if A[start] < A[mid]:\n if A[start] <= target and target <= A[mid]:\n end = mid\n else:\n start = mid\n else:\n # [mid, end] 是单调区间\n if A[mid] <= target and target <= A[end]:\n start = mid\n else:\n end = mid\n\n if A[start] == target:\n return start\n if A[end] == target:\n return end\n return -1\n\nres = Solution().search([4, 5, 1, 2, 3], 1)\nprint(res) # 2\n\nres = Solution().search([4, 5, 1, 2, 3], 0)\nprint(res) # -1\n\nres = Solution().search([0,1,2,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1], -9)\nprint(res) # 4\n\n","sub_path":"lintcode/二分法/62-search-in-rotated-sorted-array.py","file_name":"62-search-in-rotated-sorted-array.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"574352153","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport logging\n\n# reconfigure path to import modules from modules subfolder\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), \"../pylib\"))\n\nfrom ecmascript.frontend import tree, Comment\n\n\n\n\n\n\ndef getAssignment(elem):\n if elem.parent.type == \"right\" and elem.parent.parent.type == \"assignment\":\n return elem.parent.parent\n\n return None\n\n\ndef getName(elem):\n # find last identifier\n last = elem.getLastChild(False, True)\n\n if last.type == \"identifier\":\n return last.get(\"name\")\n\n\ndef getMode(var, classname):\n # find last identifier\n last = var.getLastChild(False, True)\n prev = last.getPreviousSibling(False, True)\n\n if not prev:\n return None\n\n if prev.type == \"identifier\":\n mode = prev.get(\"name\")\n\n if mode == \"Proto\":\n return \"members\"\n elif mode == \"Clazz\":\n return \"statics\"\n\n combined = []\n length = var.getChildrenLength(True)\n pos = length - 1\n for iden in var.children:\n if iden.type == \"identifier\":\n combined.append(iden.get(\"name\"))\n\n # if variable starts with the classname and has one unique identifier afterwards\n if \".\".join(combined) == classname and pos == 1:\n return \"statics\"\n\n pos -= 1\n\n return None\n\n\ndef getNameOfAssignment(elem):\n name = None\n\n if elem.hasChild(\"left\"):\n left = elem.getChild(\"left\")\n\n if left.hasChild(\"variable\"):\n name = getName(left.getChild(\"variable\"))\n\n return name\n\n\ndef getModeOfAssignment(elem, classname):\n mode = None\n\n if elem.hasChild(\"left\"):\n left = elem.getChild(\"left\")\n\n if left.hasChild(\"variable\"):\n var = left.getChild(\"variable\")\n mode = getMode(var, classname)\n\n return mode\n\n\ndef getAndRemovePropertyName(definition):\n for keyValue in definition.children:\n if keyValue.type == \"keyvalue\" and keyValue.get(\"key\") == \"name\":\n name = keyValue.getChild(\"value\").getChild(\"constant\").get(\"value\")\n keyValue.parent.removeChild(keyValue)\n return name\n\n logging.warn(\" * Could not extract property name!\")\n return None\n\n\ndef replaceMapKey(definition, searchKey, replaceKey):\n for keyValue in definition.children:\n if keyValue.type == \"keyvalue\" and keyValue.get(\"key\") == searchKey:\n keyValue.set(\"key\", replaceKey)\n return\n\n logging.warn(\" * Could not replace key %s with %s\" % (searchKey, replaceKey))\n\n\n\ndef createPair(key, value, commentParent=None):\n par = tree.Node(\"keyvalue\")\n sub = tree.Node(\"value\")\n\n par.set(\"key\", key)\n par.addChild(sub)\n sub.addChild(value)\n\n if commentParent and commentParent.hasChild(\"commentsBefore\"):\n par.addChild(commentParent.getChild(\"commentsBefore\"))\n\n return par\n\n\ndef patch(id, node):\n if not node.hasChildren():\n return False\n\n classDefine, className, classMap, settingsMap, variantsMap, propertiesMap, membersMap, staticsMap = createClassDefine(id)\n errorCounter = 0\n pos = 0\n\n while node.hasChildren() and pos < len(node.children):\n child = node.children[pos]\n breakBefore = child.get(\"breakBefore\", False)\n if breakBefore == None:\n breakBefore = False\n\n pos += 1\n\n # Add instance and static methods\n if child.type == \"assignment\":\n if child.hasChild(\"right\"):\n right = child.getChild(\"right\")\n elem = right.getFirstChild(True, True)\n\n name = getNameOfAssignment(child)\n mode = getModeOfAssignment(child, id)\n\n if mode in [ \"members\", \"statics\" ]:\n if mode == \"members\":\n pair = createPair(name, elem, child)\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n membersMap.addChild(pair)\n\n elif mode == \"statics\":\n # Special Handling of old singleton definition\n if name == \"getInstance\":\n pair = createPair(\"type\", createConstant(\"string\", \"singleton\"))\n #pair.addChild(createBlockComment(\"type\"))\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n classMap.addChild(pair, 0)\n\n else:\n pair = createPair(name, elem, child)\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n staticsMap.addChild(pair)\n\n node.removeChild(child)\n pos -= 1\n\n elif child.type == \"call\":\n oper = child.getChild(\"operand\")\n var = oper.getChild(\"variable\", False)\n\n if var:\n lastIdentifier = var.getLastChild(False, True)\n if lastIdentifier.type == \"identifier\":\n name = lastIdentifier.get(\"name\")\n params = child.getChild(\"arguments\")\n\n if name in [ \"addProperty\", \"changeProperty\", \"addCachedProperty\", \"addFastProperty\", \"addPropertyGroup\" ]:\n definition = params.getFirstChild(False, True)\n\n if definition.type == \"map\":\n if lastIdentifier.get(\"name\") == \"addFastProperty\":\n definition.addChild(createPair(\"_fast\", createConstant(\"boolean\", \"true\")), 0)\n elif lastIdentifier.get(\"name\") == \"addCachedProperty\":\n definition.addChild(createPair(\"_cached\", createConstant(\"boolean\", \"true\")), 0)\n elif lastIdentifier.get(\"name\") == \"addProperty\" or lastIdentifier.get(\"name\") == \"changeProperty\":\n definition.addChild(createPair(\"_legacy\", createConstant(\"boolean\", \"true\")), 0)\n elif lastIdentifier.get(\"name\") == \"addPropertyGroup\":\n replaceMapKey(definition, \"members\", \"group\")\n\n name = getAndRemovePropertyName(definition)\n pair = createPair(name, definition, child)\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n propertiesMap.addChild(pair)\n\n node.removeChild(child)\n pos -= 1\n\n elif name == \"setDefault\":\n nameNode = params.getChildByPosition(0, True)\n valueNode = params.getChildByPosition(1, True)\n\n name = nameNode.get(\"value\")\n\n pair = createPair(name, valueNode, child)\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n settingsMap.addChild(pair)\n\n node.removeChild(child)\n pos -= 1\n\n elif name == \"defineClass\":\n if params.getFirstChild(False, True).get(\"value\") != id:\n logging.warn(\" - The class seems to have a wrong definition!\")\n\n # 3 params = name, superclass, constructor\n # 2 params = name, map\n # 1 param = name\n\n # Move class comment\n if child.hasChild(\"commentsBefore\"):\n classDefine.addChild(child.getChild(\"commentsBefore\"))\n\n childrenLength = params.getChildrenLength(True)\n\n if childrenLength == 1:\n node.removeChild(child)\n pos -= 1\n\n elif childrenLength == 2:\n statics_new = params.getChildByPosition(1, True, True)\n\n while statics_new.hasChildren():\n staticsMap.addChild(statics_new.getFirstChild())\n\n node.removeChild(child)\n pos -= 1\n\n elif childrenLength == 3:\n ext = params.getChildByPosition(1, True, True)\n construct = params.getChildByPosition(2, True, True)\n\n extendPair = createPair(\"extend\", ext)\n constructPair = createPair(\"construct\", construct)\n\n # extendPair.addChild(createBlockComment(\"superclass\"))\n constructPair.addChild(createBlockComment(\"constructor\"))\n\n classMap.addChild(extendPair, 0)\n classMap.addChild(constructPair, 1)\n\n node.removeChild(child)\n pos -= 1\n\n elif name == \"define\":\n prev = lastIdentifier.getPreviousSibling(False, True)\n\n if prev.type == \"identifier\":\n if prev.get(\"name\") in [\"Class\", \"Mixin\", \"Interface\", \"Theme\", \"Locale\"]:\n logging.debug(\" - Class is already up-to-date.\")\n return False\n\n elif prev.get(\"name\") == \"Setting\":\n nameNode = params.getChildByPosition(0, True)\n valueNode = params.getChildByPosition(1, True)\n\n name = nameNode.get(\"value\")\n\n pair = createPair(name, valueNode, child)\n pair.set(\"quote\", \"doublequotes\")\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n settingsMap.addChild(pair)\n\n node.removeChild(child)\n pos -= 1\n\n elif prev.get(\"name\") == \"Variant\":\n nameNode = params.getChildByPosition(0, True)\n allowedNode = params.getChildByPosition(1, True)\n defaultNode = params.getChildByPosition(2, True)\n\n name = nameNode.get(\"value\")\n\n variantDef = tree.Node(\"map\")\n variantDef.addChild(createPair(\"allowedValues\", allowedNode))\n variantDef.addChild(createPair(\"defaultValue\", defaultNode))\n\n pair = createPair(name, variantDef, child)\n pair.set(\"quote\", \"doublequotes\")\n\n if breakBefore:\n pair.set(\"breakBefore\", True)\n\n variantsMap.addChild(pair)\n\n node.removeChild(child)\n pos -= 1\n\n # Post-Check\n if child.parent == node:\n logging.warn(\" - Could not move element %s at line %s\" % (child.type, child.get(\"line\")))\n errorCounter += 1\n\n\n # Remove empty maps\n if settingsMap.getChildrenLength() == 0:\n keyvalue = settingsMap.parent.parent\n classMap.removeChild(keyvalue)\n\n if variantsMap.getChildrenLength() == 0:\n keyvalue = variantsMap.parent.parent\n classMap.removeChild(keyvalue)\n\n if propertiesMap.getChildrenLength() == 0:\n keyvalue = propertiesMap.parent.parent\n classMap.removeChild(keyvalue)\n\n if membersMap.getChildrenLength() == 0:\n keyvalue = membersMap.parent.parent\n classMap.removeChild(keyvalue)\n\n if staticsMap.getChildrenLength() == 0:\n keyvalue = staticsMap.parent.parent\n classMap.removeChild(keyvalue)\n\n # Add new class definition\n node.addChild(classDefine, 0)\n\n\n\n\n if errorCounter > 0:\n logging.info(\" - Could not convert %s elements.\" % errorCounter)\n\n # Debug\n #print compiler.compile(node)\n #print tree.nodeToXmlString(node)\n\n # Return Modification\n return True\n\n\ndef createConstant(type, value):\n constant = tree.Node(\"constant\")\n constant.set(\"constantType\", type)\n constant.set(\"value\", value)\n\n if type == \"string\":\n constant.set(\"detail\", \"doublequotes\")\n\n return constant\n\n\n\ndef createVariable(l):\n var = tree.Node(\"variable\")\n\n for name in l:\n iden = tree.Node(\"identifier\")\n iden.set(\"name\", name)\n var.addChild(iden)\n\n return var\n\ndef createClassDefineCore(id):\n call = tree.Node(\"call\")\n oper = tree.Node(\"operand\")\n para = tree.Node(\"arguments\")\n con = createConstant(\"string\", id)\n args = tree.Node(\"map\")\n\n call.addChild(oper)\n call.addChild(para)\n\n oper.addChild(createVariable([\"qx\", \"Class\", \"define\"]))\n\n para.addChild(con)\n para.addChild(args)\n\n return call, con, args\n\n\ndef createClassDefine(id):\n classDefine, className, classMap = createClassDefineCore(id)\n\n settingsMap = tree.Node(\"map\")\n settingsPair = createPair(\"settings\", settingsMap)\n\n variantsMap = tree.Node(\"map\")\n variantsPair = createPair(\"variants\", variantsMap)\n\n propertiesMap = tree.Node(\"map\")\n propertiesPair = createPair(\"properties\", propertiesMap)\n\n membersMap = tree.Node(\"map\")\n membersPair = createPair(\"members\", membersMap)\n\n staticsMap = tree.Node(\"map\")\n staticsPair = createPair(\"statics\", staticsMap)\n\n propertiesPair.addChild(createBlockComment(\"properties\"))\n membersPair.addChild(createBlockComment(\"members\"))\n staticsPair.addChild(createBlockComment(\"statics\"))\n settingsPair.addChild(createBlockComment(\"settings\"))\n variantsPair.addChild(createBlockComment(\"variants\"))\n\n classMap.addChild(staticsPair)\n classMap.addChild(propertiesPair)\n classMap.addChild(membersPair)\n classMap.addChild(settingsPair)\n classMap.addChild(variantsPair)\n\n return classDefine, className, classMap, settingsMap, variantsMap, propertiesMap, membersMap, staticsMap\n\n\ndef createBlockComment(txt):\n l = \"*****************************************************************************\"\n\n s = \"\"\n s += \"/*\\n\"\n s += \"%s\\n\" % l\n s += \" %s\\n\" % txt.upper()\n s += \"%s\\n\" % l\n s += \"*/\"\n\n bef = tree.Node(\"commentsBefore\")\n com = tree.Node(\"comment\")\n\n bef.addChild(com)\n\n com.set(\"multiline\", True)\n com.set(\"connection\", \"before\")\n com.set(\"text\", s)\n com.set(\"detail\", Comment.Comment(s).getFormat())\n\n return bef\n\n\n","sub_path":"tool/data/migration/0.7-beta1/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":14855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"180511103","text":"# https://atcoder.jp/contests/abc022/tasks/abc022_c\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda:sys.stdin.readline().rstrip()\ndef resolve():\n n,m=map(int,input().split())\n E=[[] for _ in range(n)]\n for _ in range(m):\n u,v,l=map(int,input().split())\n u-=1; v-=1\n E[u].append((v,l))\n E[v].append((u,l))\n\n # 最小コストの0 -> 0ループを見つけたい\n # (0,u)があるとして、uから0までの(0,u)を除いた最短距離を全て求める\n # pure DijkstraでO(n^3)\n def calc(x):\n assert(x!=0)\n dist=[INF]*n\n dist[x]=0\n calculated=[0]*n\n for _ in range(n-1):\n v=min((dist[v],v) for v in range(n) if(not calculated[v]))[1]\n calculated[v]=1\n for nv,l in E[v]:\n if((min(v,nv),max(v,nv))==(0,x)): continue\n if(dist[nv]>dist[v]+l):\n dist[nv]=dist[v]+l\n return dist[0]\n\n ans=INF\n for x,l in E[0]:\n ans=min(ans,l+calc(x))\n print(ans if(ans!=INF) else -1)\nresolve()\n","sub_path":"ABC022/c_blue_bird.py","file_name":"c_blue_bird.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"161867899","text":"import os\nimport json\nimport pymongo\n\n\nPROJECT_ID = os.environ.get('PROJECT_ID')\n\nMONGODB_HOST = \"mongo-db.hyperfaas.svc.cluster.local\"\nMONGODB_PORT = 27017\nMONGODB_DATABASE = \"{}-lab2\".format(PROJECT_ID)\nMONGODB_COLLECTION = \"recognizedLabels\"\nMONGODB_URL = \"mongodb://{}\".format(MONGODB_HOST)\n\n\ndef main():\n client = pymongo.MongoClient(MONGODB_URL, MONGODB_PORT)\n\n collection = client[MONGODB_DATABASE][MONGODB_COLLECTION]\n\n documents_cursor = collection.find({})\n\n return json.dumps([{\n \"image\": document['image'],\n \"labels\": document['labels']\n } for document in documents_cursor], indent=2)\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"lab2/functions/fetch-results/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"76375096","text":"from src.run import Command\nfrom src.core import Bullet,bulletFromHash\n\ndef funct(h, alg, **options):\n bullet = bulletFromHash(h)\n a = bullet.get(\"a\")\n if (not type(a)==list and not alg==a) or (type(a)==list and not alg in a):\n try:\n bullet.writeToBin(alg)\n except:\n print(\"Error pushing bullet to bin '\" + alg + \"'. Are you sure this bin exists?\")\n return False\n\n bullet.addAllegiance(alg)\n bullet.write()\n return True\n\ncmd = Command(\"push\",2,funct,2)\n","sub_path":"src/Push.py","file_name":"Push.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"202275687","text":"\n# Copyright 2017-present Open Networking Foundation\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\nKIND=\"generic\"\n\ndef __init__(self, *args, **kwargs):\n # for subclasses, set the default kind appropriately\n self._meta.get_field(\"kind\").default = self.KIND\n super(Tenant, self).__init__(*args, **kwargs)\n\n@property\ndef tenantattribute_dict(self):\n attrs = {}\n for attr in self.tenantattributes.all():\n attrs[attr.name] = attr.value\n return attrs\n\n# helper function to be used in subclasses that want to ensure\n# service_specific_id is unique\ndef validate_unique_service_specific_id(self):\n if self.pk is None:\n if self.service_specific_id is None:\n raise XOSMissingField(\"subscriber_specific_id is None, and it's a required field\", fields={\n \"service_specific_id\": \"cannot be none\"})\n\n conflicts = self.__class__.objects.filter(\n service_specific_id=self.service_specific_id)\n if conflicts:\n raise XOSDuplicateKey(\"service_specific_id %s already exists\" % self.service_specific_id, fields={\n \"service_specific_id\": \"duplicate key\"})\n\ndef __xos_save_base(self, *args, **kwargs):\n subCount = sum([1 for e in [self.subscriber_service, self.subscriber_tenant,\n self.subscriber_user, self.subscriber_root] if e is not None])\n if (subCount > 1):\n raise XOSConflictingField(\n \"Only one of subscriber_service, subscriber_tenant, subscriber_user, subscriber_root should be set\")\n\n\ndef get_subscribed_tenants(self, tenant_class):\n ids = self.subscribed_tenants.filter(kind=tenant_class.KIND)\n return tenant_class.objects.filter(id__in=ids)\n\ndef get_newest_subscribed_tenant(self, kind):\n st = list(self.get_subscribed_tenants(kind))\n if not st:\n return None\n return sorted(st, key=attrgetter('id'))[0]\n\n","sub_path":"xos/core/models/attic/tenant_model.py","file_name":"tenant_model.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"432883671","text":"import os\n\n# apath = str(input('Insert a path here: '))\npath_search = '/Users/WICTOR/Downloads/Compra de ações'\n# print(path_search)\nitem = 'VID'\n\nfor root, directories, arquives in os.walk(path_search):\n for arquive in arquives:\n complete_path = os.path.join(root, arquive)\n print(complete_path)","sub_path":"01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"76922813","text":"# -*- coding: utf-8 -*-\nimport select\nimport socket\nimport errno\n\nStopCharacter = \"\\r\\n\\r\\n\"\n\ndef start():\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(('', 2048))\n s.listen(64)\n s.setblocking(0)\n\n ep = select.epoll()\n ep.register(s)\n\n fd_map = {s.fileno(): s}\n fd_data = {}\n\n while True:\n events = ep.poll()\n for fd, event in events:\n\n if fd is s.fileno():\n cli, addr = s.accept()\n cli.setblocking(0)\n print(\"get connection from {}\".format(addr))\n ep.register(cli)\n fd_map[cli.fileno()] = cli\n\n elif event & select.EPOLLIN:\n\n try:\n cur_data = fd_map[fd].recv(4)\n if not cur_data:\n print(\"disconnected from client\")\n ep.unregister(fd)\n fd_map[fd].close()\n del fd_map[fd]\n del fd_data[fd]\n else:\n if len(cur_data) > 0:\n print(\"recv data [{}]\".format(cur_data))\n if fd in fd_data:\n fd_data[fd] += cur_data\n else:\n fd_data[fd] = cur_data\n recv_end = fd_data[fd].find(StopCharacter)\n if recv_end != -1:\n ep.modify(fd, select.EPOLLOUT)\n else:\n print(\"cur_data is empty\")\n\n except socket.error as e:\n\n #non-blocking socket\n if e[0] in (errno.EWOULDBLOCK, errno.EAGAIN):\n print(\"this is not error: {}\".format(e))\n return\n else:\n print(\"got error: {}\".format(e))\n ep.unregister(fd)\n fd_map[fd].close()\n del fd_map[fd]\n if fd in fd_data:\n del fd_data[fd]\n\n elif event & select.EPOLLOUT:\n\n recv_data = fd_data.get(fd, \"\")\n if len(recv_data) > 0:\n send_data = \"py resp:\" + fd_data[fd] + StopCharacter\n print(\"send data {}\".format(send_data))\n fd_map[fd].send(send_data)\n del fd_data[fd]\n ep.modify(fd, select.EPOLLIN)\n\n elif event & select.EPOLLERR:\n print(\"got epoll err\")\n ep.unregister(fd)\n if fd in fd_map:\n del fd_map[fd]\n if fd in fd_data:\n del fd_data[fd]\n\nif __name__ == '__main__':\n\n start()\n","sub_path":"MyTool/epollsrv.py","file_name":"epollsrv.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"416732996","text":"from unittest.mock import patch\nfrom django.test import Client, TestCase, override_settings\nfrom django.contrib.sites.models import Site\nfrom django.urls import reverse\n\nfrom robots.models import Rule, Url\n\n\ndef create_rules(current_site):\n site_1 = Site.objects.get(domain=current_site)\n site_2 = Site.objects.create(domain='sub.example.com')\n\n url_check = Url.objects.create(pattern='/malware-bot-test')\n url_root = Url.objects.create(pattern='/')\n url_media = Url.objects.create(pattern='/media')\n\n rule_1 = Rule.objects.create(site=site_1, user_agent='*', crawl_delay=10)\n rule_2 = Rule.objects.create(site=site_2, user_agent='*', crawl_delay=10)\n rule_3 = Rule.objects.create(user_agent='Bing', crawl_delay=20)\n rule_4 = Rule.objects.create(user_agent='Googlebot')\n\n rule_1.allowed_urls.add(url_root)\n for url in [url_check, url_media]:\n rule_1.disallowed_urls.add(url)\n\n rule_2.allowed_urls.add(url_root)\n rule_3.disallowed_urls.add(url_media)\n rule_4.disallowed_urls.add(url_media)\n\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"597261148","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cvxpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize\nfrom scipy.optimize import curve_fit\nfrom cnn import *\n\n\"\"\" Uniform collection: collects similar amounts of data per slice \"\"\"\n\nclass Uniform:\n def __init__(self, train, val, val_data_dict, data_num_array, num_class, add_data_dict):\n \"\"\"\n Args:\n train: Training data and label\n val: Valiation data and label\n val_data_dict: Validation data per each slice\n data_num_array: Initial slice sizes\n num_class: Number of class\n add_data_dict: Data assumed to be collected\n \"\"\"\n \n self.train = train\n self.val = val\n self.val_data_dict = val_data_dict\n self.data_num_array = data_num_array\n self.add_data_dict = add_data_dict\n\n self.num_class = num_class\n self.loss_output = []\n self.slice_num = []\n \n def performance(self, budget, cost_func, num_iter):\n \"\"\" \n Args: \n budget: Data collection budget\n cost_func: Represents the effort to collect an example for a slice\n num_iter: Number of training times\n \"\"\"\n \n method = \"Uniform\"\n self.budget = budget\n self.cost_func = cost_func\n\n num_examples = (np.ones(self.num_class)*(self.budget/np.sum(self.cost_func))).astype(int)\n self.train_after_collect_data(num_examples, num_iter)\n \n print(\"Method: %s, Budget: %s\" % (method, budget))\n print(\"======= Collect Data =======\")\n print(num_examples)\n print(\"======= Performance =======\")\n print(\"Loss: %.5f, Average EER: %.5f, Max EER: %.5f\\n\" % tuple(self.show_performance()))\n\n\n def train_after_collect_data(self, num_examples, num_iter):\n \"\"\" Trains the model after we collect num_examples of data\n \n Args:\n num_examples: Number of examples to collect per slice \n num_iter: Number of training times\n \"\"\"\n \n self.batch_size = self.train[0].shape[0]\n self.collect_data(num_examples)\n for i in range(num_iter):\n network = CNN(self.train[0], self.train[1], self.val[0], self.val[1], self.val_data_dict, \n self.batch_size, epoch=500, lr = 0.001, num_class = self.num_class)\n loss_dict, slice_num = network.cnn_train()\n\n for j in range(self.num_class):\n if i == 0:\n self.loss_output.append(loss_dict[j] / num_iter) \n else:\n self.loss_output[j] += (loss_dict[j] / num_iter)\n \n \n def collect_data(self, num_examples):\n \"\"\" \n Collects num_examples of data from add_data_dict\n add_data_dict could be changed to any other data collection tool\n \n Args:\n num_examples: Number of examples to collect per slice \n \"\"\"\n \n def shuffle(data, label):\n shuffle = np.arange(len(data))\n np.random.shuffle(shuffle)\n data = data[shuffle]\n label = label[shuffle]\n return data, label\n\n train_data = self.train[0]\n train_label = self.train[1]\n for i in range(self.num_class):\n train_data = np.concatenate((train_data, self.add_data_dict[i][0][:num_examples[i]]), axis=0)\n train_label = np.concatenate((train_label, self.add_data_dict[i][1][:num_examples[i]]), axis=0) \n self.add_data_dict[i]= (np.concatenate((self.add_data_dict[i][0][num_examples[i]:], self.add_data_dict[i][0][:num_examples[i]]), axis=0), \n np.concatenate((self.add_data_dict[i][1][num_examples[i]:], self.add_data_dict[i][1][:num_examples[i]]), axis=0))\n \n self.train = (train_data, train_label)\n \n \n def show_performance(self):\n \"\"\" Average validation loss, Average equalized error rate(Avg. EER), Maximum equalized error rate (Max. EER) \"\"\"\n \n print(self.loss_output)\n final_loss = []\n num = 0\n max_eer = 0\n avg_eer =0\n \n for i in range(self.num_class):\n final_loss.append(self.loss_output[i])\n \n for i in range(self.num_class):\n diff_eer = ((np.sum(final_loss) - final_loss[i]) / (self.num_class-1) - final_loss[i]) * (-1)\n if diff_eer > 0:\n if max_eer < diff_eer:\n max_eer = diff_eer\n \n avg_eer += diff_eer\n num += 1\n \n avg_eer = avg_eer / num\n \n return np.average(final_loss), avg_eer, max_eer \n \n","sub_path":"uniform.py","file_name":"uniform.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"639688884","text":"'''\n###############################################################################\n###############################################################################\nTHE FOLLOWING CONTAINS ROMS AND PARTICLES SETTINGS TO BE EDITED BY USER\n###############################################################################\n###############################################################################\n\n'''\n##############################################################################\n# Import some libraries\n##############################################################################\nimport sys\nimport os\nimport numpy as np\nfrom copy import *\nimport time as tm\n\nsys.path.append(\"../Modules/\")\nfrom R_files import load\n\n##############################################################################\n\ndebug = True # Increase verbosity to help debug\n\n################################################################################\n# ROMS INPUTS\n################################################################################\n# if meanflow = True Roms data are not updated (used for climatology)\nmeanflow = False\n# in case of periodic channel\nx_periodic = False\ny_periodic = False\n\nng = 1\n\n# dfile is frequency for the use of the ROMS outputs\n# (default is 1 = using all outputs files)\ndfile = 1\nstart_file = 1000\nend_file = 1010\n\n######\n# only if part_trap=True, time index in trap_file to start backward simulation\n# itime_trap = -1 : last time index in forward simulation\nitime_trap = -11 \ntrap_file = '/home/jeremy/Bureau/Data/Pyticles/Trap_fwd/' \\\n + 'Case_1_Trap_fwd_adv200.0m_6_1510.nc'\n\n###### Restart from a Pyticles output file\n# user should not change start_file\n# restart_time : number of time step since start_file\nrestart = False\nrestart_time = 7 #nb of time steps in the restart_file\nrestart_file = '/home/jeremy/Bureau/Data/Pyticles/' \\\n +'/Cubic_adv/Case_1_Cubic_adv_4_1510.nc'\n\nif not restart:\n restart_time = 0\nelse:\n start_file += restart_time\n\n# Load simulation\n# parameters = my_simul + [0,nx,0,ny,[1,nz,1]] ; nx, ny, nz Roms domain's shape \n# user may add my_simul in Module/R_files.py to indicate roms output path and\n# parameters\nmy_simul = 'lwang'\nparameters = my_simul + ' [0,10000,0,10000,[1,100,1]] '+ format(start_file)\nsimul = load(simul = parameters, floattype=np.float64)\n\n##############################################################################\n# Pyticles numerical schemes (TO BE EDITED)\n#\n#time-stepping Default is RK4\ntimestep = 'RK4' # Choices are\n # FE (forward-Euler)\n # RK2, RK4 (Runge-Kutta 2nd and 4th order)\n # AB2, AB3, AB4 (Adams-Bashforth 2,3,4th order)\n # ABM4 (Adams-Bashforth 4th order + Adams-Moulton corrector).\n\nnsub_steps = 360 # Number of time steps between 2 roms time steps\n\n# Spatial interpolation\n# Default is linear\n# Available : #define CUBIC_INTERPOLATION\n# #define CRSPL_INTERPOLATION\n# #define WENO_INTERPOLATION\n# Beware these higher order schemes have not been rigorously tested\n# To define them, in Modules/interp_3d_for_pyticles.F\n# Activate ccp keys : NEW_VERSION and chosen numerical scheme\n# Compile cpp keys use make command\n\nnadv = 1 # deprecated\n\n\n##############################################################################\n# Particles Dynamics\n##############################################################################\n# 3D advection\nadv3d = True\nadvzavg = False\n\nif advzavg:\n z_thick = 100. # water column thickness to average 2D velocity field around\n # Around advdepth\n# Else 2D advection using (u,v) interpolated at advdepth \nif not adv3d:\n advdepth = -200.\n\n'''\n NOTE that advdepths is used as follows:\n\n advdepth <= 0 means depths in meters\n advdepth = 0 means surface\n advdepth > 0 means sigma-level (1 = bottom [0 in netcdf file],...\n ..., Nz = surface [Nz-1 in netcdf file])\n'''\n# sedimentation of denser particles (not supported in 2D case)\nsedimentation = False\nw_sed0 = -40 # vertical velocity for particles sedimentation (m/s)\n\nif not adv3d:\n sedimentation = False\n w_sed0 = 0. # JC no sedimentation for 2D advection\n\n##############################################################################\n# Pyticles Outputs\n##############################################################################\n\n#Write lon,lat,topo,depth\nwrite_lonlat = True\nwrite_depth = True\nwrite_topo = True\nif advzavg: \n write_topo = True # Needed to keep track when water column intersects with\n # bathymetry (topo > |advdepth| - z_thick/2)\nwrite_uv = True\nwrite_ts = True\nwrite_uvw = True\nif write_uvw:\n write_uv = False\n\n#Write only Temperature (for simulations with no S)\nwrite_t = False\nif write_t: write_ts = False\n\n# name of your configuration (used to name output files)\nconfig = 'high_density_part'\nfolderout = '/scratch/Jcollin/Pyticles/' + config + '/'\n# create folder if does not exist\nif not os.path.exists(folderout):\n os.makedirs(folderout)\n\n#################################################################\n# This section should not be edited by users\n#################################################################\n#name of the simulation (used for naming plots and output files)\nsimulname = '_' + config\nif (not adv3d) and (advdepth > 0):\n simulname = simulname + '_adv' + '{0:04}'.format(advdepth) + 'sig'\nelif (not adv3d) and (advdepth <= 0):\n simulname = simulname + '_adv' + '{0:04}'.format(-advdepth) + 'm'\n write_depth = False\n\n####\nsimulname = simul.simul + simulname\nsimul.dtime = np.sign(dfile) * np.ceil(np.abs(dfile))\n# Resolution (dx,dy)\ndx, dy = 1./np.mean(simul.pm), 1./np.mean(simul.pn)\n# Total size of the domain (nx,ny,nz)\n(nx, ny) = simul.pm.shape\nnx += 2*ng; ny += 2*ng # add ghost points to array size\ndepths = simul.coord[4]\nnz = len(depths)\nk0 = 0\nmask = simul.mask\nmaskrho = np.copy(mask)\nmaskrho[np.isnan(maskrho)] = 0.\nnsub_x, nsub_y = 1,1 #subtiling, will be updated later automatically\n\nif not adv3d: maskrho[simul.topo<-advdepth] = 0.\n\ntopo = simul.topo\nfiletime = simul.filetime\ntimerange = np.round(np.arange(start_file,end_file,dfile),3)\n#for timing purpose\ntstart = tm.time()\n#Time all subparts of the code \ntiming = True\nsubtstep = np.int(nsub_steps * np.abs(dfile))\n\n################################################################################\n# Define Particle seeding (to be edited)\n################################################################################\n\n#Initial Particle release\nnqmx = 100000 # maximum number of particles\nmaxvel0 = 5 # Expected maximum velocity (will be updated after the first time step)\n\n###########\n# Patch's center in grid points \n# (if continuous injection: user may vary its center Directly in Pyticles.py) \n[ic, jc] = [800, 400] #= part.find_points(simul.x,simul.y,-32.28,37.30)\n\nbarycentric = False # Automatically modifies patch's center to previsously seeded\n # Particles After being advected over one time step \n\n# Size of the patch and distance between particles in meters are conserved\n# even when box's center moves during simulation\npreserved_meter = True\n\nif preserved_meter:\n dx_box = 100 # horizontal particles spacing meters\n nx_box = 10*2 + 1 # number of intervals in x-dir\n ny_box = 10*2 \n nnlev = 1 \nelse:\n dx_m = 2000. # distance between 2 particles [in m]\n dx0 = dx_m * simul.pm[ic,jc] # conversion in grid points\n dx0 = 1\n iwd = 1* dx0 # half width of seeding patch [in grid points\n jwd = 1* dx0 # half width of seeding patch [in grid points]\n # density of pyticles (n*dx0: particle every n grid points)\n nnx = 1/10 * dx0\n nny = 1/10 * dx0\n nnlev = 1\n\n#########\n# define initial vertical position using:\n# - depth if initial_depth = True\n# - if initial_cond you have to define your condition directly in Pyticles.py\n# - if initial_surf (seeding particles on isosurface of a variable) \n# Typically on isopycnal surface, define isopycnal initial value rho0\n# surface is retrieved using potential density anomy with rho1_eos from ROMS \n\n# Initialize seeding particles using a boolean condition ini_cond\n# Inside a box_grid as usual\n# Box grid supports: an horizontal (ic, jc), denisty nnx, nny\n# minimum maximum sigma levels \n# Ex : temp < 5°C \n# Does not support vertical condition\n# i.e can't state pcond = True and depth = z0\n# Therefore if ini_cond = True: initial_depth = False\n\ninitial_cond = False # 1036 in Pyticles.py\ninitial_depth = True\ninitial_surf = False\n\n# start from a Pyticles netcdf file, with forward advection\n# runs backward 3D advection from here\n# Option to choose are left to user\npart_trap = False \n\nif initial_cond:\n initial_depth = False\n\ndepths0 = [-100]\nrho0 = [-1.5]\n\n# if True release particles continuously\n# if False only one release at initial time-step\ncontinuous_injection = True\nif continuous_injection:\n dt_injection = 1 #(1 = injection every time step,\n # 10 = injection every 10 time steps)\n N_injection = 1 + np.int(timerange.shape[0] / dt_injection)\n\n#########################################\n# NOT TO BE EDITED\n#########################################\n# bottom to top vertical levels in sigma coordinate\nlev0= 0\nlev1= len(depths)\n\n##########\n# 2D advection at advdepth \nif not adv3d:\n initial_depth = True\n lev0 = -1\n lev1 = lev0\n depths0 = [advdepth]\n write_uvw = False\n write_uv = True\n\n#########\n# define initial vertical position using depth\nif initial_depth:\n lev1 = lev0 + len(depths0) - 1\n nnlev = 1\n\n#########\n# boolean matrix condition to define seeding patch\nif initial_cond:\n lev1 = len(depths)\n nnlev = 1\n\n\n\n\n","sub_path":"Inputs/input_file.py","file_name":"input_file.py","file_ext":"py","file_size_in_byte":9750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"404290777","text":"from rest_framework import serializers\n\nfrom api.serializers import QuestionSerializer\nfrom course.models.models import MultipleChoiceQuestion, MultipleChoiceSubmission\n\n\nclass MultipleChoiceQuestionSerializer(serializers.ModelSerializer):\n class Meta:\n model = MultipleChoiceQuestion\n fields = ['id', 'title', 'text', 'answer', 'max_submission_allowed', 'time_created', 'time_modified', 'author',\n 'category', 'difficulty', 'is_verified', 'variables', 'choices', 'visible_distractor_count',\n 'token_value', 'success_rate', 'type_name', 'event', 'is_sample', 'category_name',\n 'parent_category_name', 'course_name', 'event_name', 'author_name', 'is_checkbox']\n\n choices = serializers.JSONField()\n variables = serializers.JSONField()\n\n\nclass MultipleChoiceSubmissionSerializer(serializers.ModelSerializer):\n class Meta:\n model = MultipleChoiceSubmission\n fields = ['pk', 'submission_time', 'answer', 'grade', 'is_correct', 'is_partially_correct', 'finalized',\n 'status', 'tokens_received', 'token_value', 'question', 'answer_display', 'show_answer',\n 'show_detail', 'status_color']\n\n question = QuestionSerializer()\n","sub_path":"api/serializers/multiple_choice_question.py","file_name":"multiple_choice_question.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"364993970","text":"import torch\nimport torch.nn as nn\nimport torch.distributions as Dis\n\n# Neural Network Layers from Prior Distribution\nclass Gaussian_layer_prior(nn.Module):\n def __init__(self, input_dim, output_dim, scale):\n super(Gaussian_layer_prior, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.scale = scale\n\n def forward(self, x):\n beta = torch.randn(self.input_dim, self.output_dim) * self.scale\n return torch.mm(x, beta)\n\n\nclass SS_layer_prior(nn.Module):\n def __init__(self, input_dim, output_dim, scale, prob):\n super(SS_layer_prior, self).__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.scale = scale\n self.prior_p = Dis.bernoulli.Bernoulli(probs=prob)\n\n def forward(self, x):\n beta = torch.randn(self.input_dim, self.output_dim) * self.scale\n indentity = self.prior_p.sample(sample_shape=torch.tensor([self.input_dim]))\n return torch.mm(x * indentity, beta)\n\n# Neural Network priors\nclass Main_Prior(nn.Module):\n def __init__(self, num_feature, scale, num_output = 1):\n super(Main_Prior, self).__init__()\n self.num_feature = num_feature\n self.scale = scale\n self.Layer1 = Gaussian_layer_prior(num_feature, num_output, scale)\n\n def forward(self, x):\n x = self.Layer1(x)\n\n return x\n\nclass SparseBNN_Prior(nn.Module):\n def __init__(self, encoder_prior, predictor_prior):\n super(SparseBNN_Prior, self).__init__()\n self.encoder = encoder_prior\n self.predictor = predictor_prior\n \n def forward(self, x):\n x1 = self.encoder(x)\n x2 = self.predictor(x1)\n return x2 \n\nclass Predictor_wide_Prior(nn.Module):\n def __init__(self, num_feature, scale, prob = 0.1, num_hidden_nodes = 100):\n super(Predictor_wide_Prior, self).__init__()\n self.num_feature = num_feature\n self.scale = scale\n self.Layer1 = Gaussian_layer_prior(num_feature, num_hidden_nodes, scale)\n self.Layer2 = SS_layer_prior(num_hidden_nodes, 1, scale, prob)\n self.f = nn.Softplus(beta = 10)\n\n def forward(self, x):\n x1 = self.f(self.Layer1(x))\n x2 = self.Layer2(x1)\n return x2\n \nclass Encoder_Prior(nn.Module):\n def __init__(self, gene_size, sigma):\n super(Encoder_Prior, self).__init__()\n self.dim_gene = gene_size\n self.sigma = sigma\n self.layers = nn.ModuleList([Gaussian_layer_prior(gene_size[i], 1, sigma) for i in range(len(gene_size))]) \n \n def forward(self, data_list):\n output = torch.zeros(data_list[0].shape[0], len(data_list))\n \n for i, j in enumerate(self.layers):\n # forward passing for each gene\n output_i = j(data_list[i])\n \n index_i = torch.zeros(data_list[0].shape[0], len(data_list))\n index_i[:, i] = 1\n output = output + index_i * output_i\n \n return output\n","sub_path":"prior_NNs.py","file_name":"prior_NNs.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"78131889","text":"########\n#Solved#\n########\n\n#By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n#3\n#7 4\n#2 4 6\n#8 5 9 3\n\n#That is, 3 + 7 + 4 + 9 = 23.\n\n#Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.\n\n#NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)\n\n\ngrid = open('67.txt')\ngrid = grid.read().rstrip()\ngrid = grid.split('\\n')\n\nfor x in range(0,len(grid)):\n grid[x] = grid[x].split(' ')\n for y in range(0,int(len(grid[x]))):\n grid[x][y] = int(grid[x][y])\n\nfor x in range(len(grid)-2,-1,-1):\n for num in range(0,len(grid[x])):\n if grid[x+1][num] > grid[x+1][num+1]:\n grid[x][num] += grid[x+1][num]\n else:\n grid[x][num] += grid[x+1][num+1]\n\nprint(grid[0][0])\n","sub_path":"67.py","file_name":"67.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"416028264","text":"#!/usr/bin/env python\n# coding: utf-8\n# Copyright (c) Qotto, 2019\n\n\"\"\" BaseStoreManager\n\nAll store manager must be inherit form this class\n\"\"\"\nfrom asyncio import AbstractEventLoop\nfrom logging import Logger\nfrom abc import ABCMeta, abstractmethod\n\nfrom tonga.services.consumer.base import BaseConsumer\nfrom tonga.services.producer.base import BaseProducer\nfrom tonga.services.coordinator.client.base import BaseClient\nfrom tonga.services.serializer.base import BaseSerializer\nfrom tonga.stores.local_store import LocalStore\nfrom tonga.stores.global_store import GlobalStore\nfrom tonga.models.structs.persistency_type import PersistencyType\n\n__all__ = [\n 'BaseStoreManager'\n]\n\n\nclass BaseStoreManager(metaclass=ABCMeta):\n \"\"\" Base store manager, all store manager must be inherit form this class\n \"\"\"\n _local_store: LocalStore\n _global_store: GlobalStore\n _client: BaseClient\n _serializer: BaseSerializer\n _store_consumer: BaseConsumer\n _store_producer: BaseProducer\n _loop: AbstractEventLoop\n _rebuild: bool\n _persistency_type: PersistencyType\n _logger: Logger\n\n @abstractmethod\n async def _initialize_stores(self) -> None:\n \"\"\" This method initialize stores (construct, pre-build)\n\n Abstract method\n\n Returns:\n NOne\n \"\"\"\n raise NotImplementedError\n\n def _initialize_local_store(self) -> None:\n \"\"\" This protected method set local store initialize flag to true\n\n Returns:\n None\n \"\"\"\n self._local_store.get_persistency().__getattribute__('_set_initialize').__call__()\n\n def _initialize_global_store(self) -> None:\n \"\"\" This protected method set global store initialize flag to true\n\n Returns:\n None\n \"\"\"\n self._global_store.get_persistency().__getattribute__('_set_initialize').__call__()\n\n def get_local_store(self) -> LocalStore:\n return self._local_store\n\n def get_global_store(self) -> GlobalStore:\n return self._global_store\n\n # Store function\n @abstractmethod\n async def set_entry_in_local_store(self, key: str, value: bytes) -> None:\n \"\"\" Set an entry in local store\n\n This method send an StoreRecord in event bus and store entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n value (bytes): Value as bytes\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def get_entry_in_local_store(self, key: str) -> bytes:\n \"\"\" Get an entry by key in local store\n\n This method try to get an entry in local store asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n\n Returns:\n bytes: return value as bytes\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def delete_entry_in_local(self, key: str) -> None:\n \"\"\" Delete an entry in local store\n\n This method send an StoreRecord in event bus and delete entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def get_entry_in_global_store(self, key: str) -> bytes:\n \"\"\" Get an entry by key in global store\n\n This method try to get an entry in global store asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n\n Returns:\n bytes: return value as bytes\n \"\"\"\n raise NotImplementedError\n\n # Storage builder part\n @abstractmethod\n async def _build_set_entry_in_global_store(self, key: str, value: bytes) -> None:\n \"\"\" Set an entry in global store\n\n This protected method store an entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n value (bytes): Value as bytes\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def _build_delete_entry_in_global_store(self, key: str) -> None:\n \"\"\" Delete an entry in global store\n\n This method delete an entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def _build_set_entry_in_local_store(self, key: str, value: bytes) -> None:\n \"\"\" Set an entry in local store\n\n This protected method store an entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n value (bytes): Value as bytes\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n async def _build_delete_entry_in_local_store(self, key: str) -> None:\n \"\"\" Delete an entry in local store\n\n This method delete an entry asynchronously\n\n Abstract method\n\n Args:\n key (str): Key entry as string\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError\n","sub_path":"tonga/stores/manager/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"629433580","text":"import json\nimport time\n\nfrom django.core.mail import mail_admins\nfrom django.db import IntegrityError, models, transaction\nfrom django.utils import timezone\n\nfrom establishment.errors.errors import BaseError\nfrom establishment.webapp.base_views import login_required, login_required_ajax, ajax_required, \\\n superuser_required, single_page_app\nfrom establishment.webapp.state import State\nfrom .errors import ContentError\nfrom .models import TermDefinition, ArticleEdit, UserFeedback, Article, Questionnaire, QuestionnaireQuestion, \\\n QuestionnaireInstance, QuestionnaireQuestionResponse, QuestionnaireQuestionOption\n\n\n@superuser_required\n@single_page_app\ndef article_manager_view(request):\n articles = Article.get_editable_articles(request.user)\n return State(articles)\n\n\n@login_required_ajax\ndef create_article(request):\n # TODO: check a limit here\n if not request.user.is_superuser:\n return BaseError.NOT_ALLOWED\n\n name = request.POST.get(\"name\", \"Untitled Article \" + str(time.time()))\n dependency = request.POST.get(\"dependency\", \"\")\n language_id = request.POST.get(\"languageId\", 1)\n is_public = json.loads(request.POST[\"isPublic\"])\n owner_id = request.user.id\n if \"userCreatedId\" in request.POST:\n owner_id = int(request.POST[\"userCreatedId\"])\n\n article = Article(author_created_id=owner_id, name=name, dependency=dependency, language_id=language_id,\n is_public=is_public)\n if \"baseArticleId\" in request.POST:\n article.base_article_id = int(request.POST[\"baseArticleId\"])\n try:\n article.save()\n except IntegrityError as e:\n # TODO: really @Rocky, 23505????\n if e.__cause__.pgcode == '23505':\n return ContentError.TRANSLATION_EXISTS\n raise\n\n if \"markup\" in request.POST:\n article.edit(request.user, request.POST[\"markup\"], )\n\n state = State(article)\n\n return state.to_response({\"article\": article})\n\n\n@ajax_required\ndef fetch_article(request):\n article_ids = request.GET.getlist(\"ids[]\")\n article_ids = [int(x) for x in article_ids]\n if len(article_ids) > 128:\n return ContentError.REQUESTED_TOO_MANY_ARTICLES\n articles = Article.objects.filter(id__in=article_ids)\n\n state = State()\n\n for article in articles:\n if article.is_available_to(request.user):\n state.add(article)\n\n return state.to_response()\n\n\n@login_required_ajax\ndef get_available_articles(request):\n articles = Article.get_editable_articles(request.user)\n return State(articles)\n\n\n# TODO: should be renamed to get_article_translations\n@login_required_ajax\ndef get_translations(request, article_id):\n article = Article.objects.get(id=article_id)\n if not request.user.is_superuser and article.author_created_id != request.user.id:\n return BaseError.NOT_ALLOWED\n\n translations = Article.objects.filter(base_article_id=article.id)\n return State(translations, TermDefinition.objects.all())\n\n\n@login_required\ndef full_article(request):\n article = Article.objects.get(id=int(request.GET[\"articleId\"]))\n\n # Permission checking to access all edits for this article\n if not request.user.is_superuser and article.author_created != request.user:\n return BaseError.NOT_ALLOWED\n\n state = State()\n\n article.add_to_state(state, True)\n\n return state\n\n\ndef check_article_change(request, article):\n need_save = False\n if \"dependency\" in request.POST:\n # Right now regular users can't add js dependencies to an article\n if not request.user.is_superuser:\n return BaseError.NOT_ALLOWED\n article.dependency = request.POST[\"dependency\"]\n need_save = True\n if \"languageId\" in request.POST:\n article.language_id = int(request.POST[\"languageId\"])\n need_save = True\n if \"name\" in request.POST:\n article.name = request.POST[\"name\"]\n need_save = True\n if \"isPublic\" in request.POST:\n article.is_public = json.loads(request.POST[\"isPublic\"])\n need_save = True\n if \"markup\" in request.POST:\n with transaction.atomic():\n article.edit(request.user, request.POST[\"markup\"], )\n need_save = False\n return need_save\n\n\ndef get_article_state(article):\n article_edits = ArticleEdit.objects.filter(article=article)\n\n state = State()\n state.add(article)\n state.add(article_edits)\n\n # TODO: Language should be loaded in PublicState\n from establishment.content.models import Language\n state.add(Language.objects.all())\n return state\n\n\n@login_required\n@single_page_app\ndef edit_article(request, article_id):\n article = Article.objects.get(id=article_id)\n\n if not request.user.is_superuser and request.user.id != article.author_created_id:\n return BaseError.NOT_ALLOWED\n\n # TODO: throttle the number of edits an article can have here\n # TODO: keep only a limited number of versions for the edits for non-admin users\n # TODO: article sizes should be limited\n\n need_save = check_article_change(request, article)\n if need_save:\n try:\n article.save()\n except IntegrityError as e:\n if e.__cause__.pgcode == '23505':\n return ContentError.TRANSLATION_EXISTS\n raise\n return {\"success\": True}\n else:\n state = get_article_state(article)\n return state.to_response({\"articleId\": article.id, \"success\": True})\n\n\n# TODO: this logic should be merged into edit_article\n@ajax_required\n@superuser_required\ndef set_article_owner(request, article_id):\n article = Article.objects.get(id=article_id)\n\n new_owner_id = int(request.POST[\"newOwner\"])\n article.author_created_id = new_owner_id\n article.save()\n\n return State(article)\n\n\n@login_required_ajax\ndef delete_article(request, article_id):\n article = Article.objects.get(id=article_id)\n if not request.user.is_superuser and request.user.id != article.author_created_id:\n return BaseError.NOT_ALLOWED\n\n try:\n article.delete()\n except models.ProtectedError:\n return ContentError.PROTECTED_ARTICLE\n\n return {\"success\": True}\n\n\ndef send_feedback(request):\n if not request.visitor.get_throttler(\"postFeedback\", (24 * 60 * 60, 5)).increm():\n return ContentError.TOO_MUCH_FEEDBACK\n\n message = request.POST[\"message\"]\n client_message = request.POST.get(\"clientMessage\", \"{}\")\n\n user_feedback = UserFeedback(message=message, client_message=client_message)\n\n if request.user.is_authenticated:\n user_feedback.user = request.user\n name = request.user.get_full_name()\n user_feedback.sender_email = request.user.email\n else:\n name = request.POST[\"name\"]\n user_feedback.sender_email = request.POST[\"email\"]\n\n user_feedback.save()\n\n mail_admins(\n \"Feedback from %s (%s)\" % (name, user_feedback.sender_email),\n message,\n user_feedback.sender_email\n )\n\n return {\"success\": True, \"feedbackId\": user_feedback.id}\n\n\n@login_required_ajax\ndef questionnaire_state(request):\n questionnaire_id = int(request.POST[\"questionnaireId\"])\n questionnaire = Questionnaire.objects.get(id=questionnaire_id)\n\n if not request.user.is_superuser and not questionnaire.visible and questionnaire.owner_id != request.user.id:\n return ContentError.QUESTIONNAIRE_NOT_AVAILABLE\n\n state = State()\n questionnaire.add_to_state(state, request.user)\n return state\n\n\n@login_required_ajax\ndef questionnaire_all_answers(request):\n questionnaire_id = int(request.GET[\"questionnaireId\"])\n questionnaire = Questionnaire.objects.get(id=questionnaire_id)\n\n if not request.user.is_superuser and questionnaire.owner_id != request.user.id:\n return BaseError.NOT_ALLOWED\n\n state = State()\n questionnaire.add_to_state(state)\n\n answers = QuestionnaireInstance.objects.filter(questionnaire=questionnaire).prefetch_related(\"question_answers__choices\")\n for answer in answers:\n answer.add_to_state(state)\n\n return state\n\n\n@login_required_ajax\ndef questionnaire_answer(request):\n questionnaire_id = int(request.POST[\"questionnaireId\"])\n\n questionnaire = Questionnaire.objects.get(id=questionnaire_id)\n if not request.user.is_superuser and not questionnaire.visible:\n return ContentError.QUESTIONNAIRE_NOT_AVAILABLE\n\n question = QuestionnaireQuestion.objects.get(id=int(request.POST[\"questionId\"]))\n if question.questionnaire_id != questionnaire.id:\n return BaseError.NOT_ALLOWED\n\n instance = QuestionnaireInstance.objects.get(user=request.user, questionnaire=questionnaire)\n # if instance.date_submitted:\n # return BaseError.NOT_ALLOWED\n\n question_response, created = QuestionnaireQuestionResponse.objects.get_or_create(instance=instance, question=question)\n\n question_response.text = request.POST.get(\"text\", None)\n\n if question.type == 2: # Single choice\n choice_id = request.POST.getlist(\"choiceIds[]\", [])\n print(choice_id)\n if len(choice_id):\n choice_id = choice_id[0]\n question_choice = QuestionnaireQuestionOption.objects.get(id=choice_id)\n if question_choice.question_id != question.id:\n return BaseError.NOT_ALLOWED\n question_response.choices.set([question_choice])\n else:\n question_response.choices.set([])\n if question.type == 3: # Multiple choice\n choice_ids = request.POST.getlist(\"choiceIds[]\", [])\n question_choices = QuestionnaireQuestionOption.objects.filter(id__in=choice_ids)\n if len(question_choices) != len(choice_ids):\n return BaseError.NOT_ALLOWED\n for question_choice in question_choices:\n if question_choice.question_id != question.id:\n return BaseError.NOT_ALLOWED\n question_response.choices.set(list(question_choices))\n question_response.save()\n return State(question_response)\n\n\n@login_required_ajax\ndef questionnaire_submit(request):\n questionnaire_id = int(request.POST[\"questionnaireId\"])\n\n questionnaire = Questionnaire.objects.get(id=questionnaire_id)\n if not request.user.is_superuser and not questionnaire.visible:\n return ContentError.QUESTIONNAIRE_NOT_AVAILABLE\n\n instance = QuestionnaireInstance.objects.get(user=request.user, questionnaire=questionnaire)\n # if instance.date_submitted:\n # return BaseError.NOT_ALLOWED\n\n instance.date_submitted = timezone.now()\n instance.save()\n\n return State(instance)\n","sub_path":"content/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"243431827","text":"import os\nimport subprocess\n\ndef assemble_and_link(asm_file, runtime_file, debug=False):\n \"\"\"Run gcc on `asm_file' and `runtime_file' to create a suitable\n executable file. If `debug' is True, then also send the `­g' option\n to gcc that will store debugging information useful for gdb.\"\"\"\n cmd = [\"gcc\"]\n if debug: cmd.append(\"-g\")\n assert asm_file.endswith('.s')\n exe_file = asm_file[:-1] + 'exe'\n cmd.extend([\"-o\", exe_file, asm_file, runtime_file])\n result = subprocess.run(cmd)\n return result.returncode # 0 on success, non­zero on failure\n\ndef main():\n print(\"* Testing files\")\n print(\"* Please note that no output after 'Testing: filename' = success\")\n # Files to run tests on\n tests = [\"add\",\"bitop\",\"bool_simple\",\"copy\",\"div\",\n \"if\",\"jumps\",\"minmax\",\"mod\",\"mul_for_cse\",\"neg\",\"relop\",\"sub\",\"while\"] \n # fizzbuzz excluded bc it has a second proc\n # bool_complex excluded bc it takes long\n for file in tests:\n print(\"Testing: \",file)\n cmd0 = \"python bx2tac_opt.py ../tests/\"+file+\".bx\"\n cmd1 = \"python tac.py ../tests/\"+file+\".tac > a.txt\"\n cmd2 = \"diff a.txt ../tests/\"+file+\".expected\"\n cmd3 = \"rm a.txt\"\n os.system(cmd0)\n os.system(cmd1)\n os.system(cmd2)\n os.system(cmd3)\n\nif __name__ == '__main__':\n main()","sub_path":"dataflow_optimizations/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"411337540","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nfrom klassen import City, distanz\n\n#TRAVELING SALESPERSON PROBLEM - HOW TO FIND THE SHORTEST WAY\n\ndf = pd.read_csv('msg_standorte_deutschland.csv')\n\n#Überblick über den Datensatz verschaffen\n#display (df)\n\n\n#sns.set()\n#ax = sns.scatterplot(x=\"Breitengrad\", y=\"Längengrad\", data=df)\n\n\n# Die Daten aus der Tabelle (Pandas Datenframe) werden genutzt um für jede Stadt eine Klasse City zu erzeugen, die die Kooridinaten und die Nummer der Stadt enthält.\n\ncities = []\n\n# Permutation von 21 Städten ist schon nicht mehr möglich, da es einfach ewig dauert\n# daher wird das Skript an dieser Stelle nur mit weniger Datensätzen getestet\n#df2 = df.iloc[:6]\n\nfor row in df.itertuples():\n new = City(row.Längengrad, row.Breitengrad, row.Nummer, row.msg_Standort)\n cities.append(new)\n\n# # All Tours Algorithm\n# Es werden mittels Permutation alle möglichen Wege und deren Strecke berechnet. Anschließend wird der Weg mit der kleinsten Strecke ausgesucht. \n# Dabei handelt es sich um einen Lösungsweg, der zwar definitiv die kürzeste Strecke ermitteln wird, aber sehr ineffizient und langsam ist, insbesondere für große Datensätze. \n\n\n#Bei der Permutation wird die erste Stadt ausgelassen, da dort immer gestartet wird\n#OPTIMIERUNG: Die Permutationen werden nicht alle in einer Liste gespeichert, sondern so wie von itertools zurück gegeben\n#anschließend kann über alle Permutationen iteriert werden, ohne alle gleichzeitig in einer Liste zu speichern, somit wird ein MEMORY ERROR vermieden, die Laufzeit aber stark erhöht\npermutation = itertools.permutations(cities[1:])\n\n#es werden nun alle einzelnen Permutationen durchlaufen und die Distanz berechnet um das Minimum zu finden\noptimum = []\n#minimale Entfernung maximal groß setzen\nmin_entfernung = float(\"inf\")\nt = 0\n\nfor tour in permutation:\n t += 1\n print (str(t)+\". Tour\")\n tour = (cities[0], ) + tour\n entfernung = 0\n while (entfernung < min_entfernung):\n for i in range(0, len(tour)):\n # wenn die letzte Stadt in der Liste erreicht ist, wird die Distanz zur Startstadt berechnet\n if i == len(tour)-1:\n entfernung += distanz(tour[i], tour[0])\n else:\n entfernung += distanz(tour[i], tour[i+1])\n #wenn eine neue minimale Entfernung gefunden wurde, wird dieser gespeichert\n if entfernung < min_entfernung:\n print(\"Neues Optimum gefunden.\")\n min_entfernung = entfernung\n optimum = list(tour)\n\nprint (\"#########################################\")\nprint (\"Die kürzste Wegstrecke: \" + str(min_entfernung))\n#für die bessere Ausgabe an die Liste hinten noch mal die Startstadt anfügen\n\noptimum.append(cities[0])\n\nfor city in optimum:\n print ((city.nummer, city.name))\n\n\nplt.plot([p.x for p in optimum], [p.y for p in optimum], \"bo-\")\nplt.savefig('optimum.png')\n\n\n\n","sub_path":"Brute_Force/auswertung_bruteforce_optimiert.py","file_name":"auswertung_bruteforce_optimiert.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"448095849","text":"class profile:\r\n\r\n def __init__(self):\r\n class prof1:\r\n age = 24\r\n\r\n def num(self):\r\n print(self.age)\r\n p1 = prof1()\r\n return(p1.num())\r\n\r\n\r\np = profile()\r\np\r\n\r\n# Eg:2 Simple\r\n\r\n\r\n# class tweet:\r\n# pass\r\n\r\n\r\n# a = tweet()\r\n# a.message = '140 Characters'\r\n# print(a.message)\r\n","sub_path":"class withinclass.py","file_name":"class withinclass.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"105146790","text":"##\n# This software was developed and / or modified by Raytheon Company,\n# pursuant to Contract DG133W-05-CQ-1067 with the US Government.\n# \n# U.S. EXPORT CONTROLLED TECHNICAL DATA\n# This software product contains export-restricted data whose\n# export/transfer/disclosure is restricted by U.S. law. Dissemination\n# to non-U.S. persons whether in the United States or abroad requires\n# an export license or other authorization.\n# \n# Contractor Name: Raytheon Company\n# Contractor Address: 6825 Pine Street, Suite 340\n# Mail Stop B8\n# Omaha, NE 68106\n# 402.291.0100\n# \n# See the AWIPS II Master Rights File (\"Master Rights File.pdf\") for\n# further licensing information.\n##\n# ----------------------------------------------------------------------------\n# This software is in the public domain, furnished \"as is\", without technical\n# support, and with no warranty, express or implied, as to its usefulness for\n# any purpose.\n#\n# ExSS2\n#\n# Author:\n# ----------------------------------------------------------------------------\n\nToolType = \"numeric\"\nWeatherElementEdited = \"QPF\"\nfrom numpy import *\nimport SmartScript\n\nVariableList = [(\"Model:\" , \"\", \"D2D_model\")]\nclass Tool (SmartScript.SmartScript):\n def __init__(self, dbss):\n SmartScript.SmartScript.__init__(self, dbss)\n\n def execute(self, GridTimeRange, varDict):\n \"This tool accesses QPF and tp grids directly\"\n\n model = varDict[\"Model:\"]\n\n # Get QPF and tp values\n qpf = self.getGrids(\"Fcst\", \"QPF\", \"SFC\", GridTimeRange)\n tp = self.getGrids(model, \"tp\",\"SFC\", GridTimeRange)\n\n qpf = where(equal(qpf,0.0), tp, qpf)\n return qpf\n","sub_path":"edexOsgi/com.raytheon.edex.plugin.gfe/utility/cave_static/user/GFETEST/gfe/userPython/smartTools/ExSS2.py","file_name":"ExSS2.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"223313195","text":"'''\r\nMajority Element\r\n<T> Array\r\n\r\nint [n] arr\r\n- find the majority element\r\n- appears more than n/2 times\r\n - array is non-empty and the majority element always exist in the array\r\n\r\n\r\nwe can use hmap to count, then iterate that\r\n - Time: O(n+num_unique_elems), Space: O(num_unique_elems)\r\n\r\n'''\r\nclass Solution:\r\n def majorityElement(self, nums: List[int]) -> int:\r\n \r\n hmap = {}\r\n \r\n for item in nums:\r\n if item in hmap:\r\n hmap[item] += 1\r\n else:\r\n hmap[item] = 1\r\n \r\n threshold = len(nums)/2\r\n \r\n ret = None\r\n for k in hmap.keys():\r\n count = hmap[k]\r\n if count > threshold:\r\n ret = k \r\n break\r\n \r\n return ret\r\n \r\n ","sub_path":"leetcode/problems/Array/169.py","file_name":"169.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"253522700","text":"#-*- coding: utf8 -*-\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport scipy.odr.odrpack as odrpack\nimport matplotlib.pyplot as plt\nfrom os import listdir\nimport math\nfrom uncertainties import ufloat\nimport uncertainties.unumpy as unp\nfrom uncertainties.umath import *\nimport uncertainties as uc\n\nimport sys\nsys.path.insert(0,\"../../scripts\")\nimport data_manager as dm\nimport fit_functions as ft\nfrom myPlot import Settings, plot, plot_multi_2, ShorthandFormatter\n\n\ndef get_settings():\n general_sets = Settings()\n \n general_sets.dataset_folder = \"../datasets/\"\n general_sets.dataset_file_name = \"energieerhaltung.csv\"\n general_sets.axes_label_fontsize = 20\n\n constant_sets = general_sets.clone()\n constant_sets.x_label = r\"$\\Delta\\, x \\:(cm)$\"\n constant_sets.y_label = r\"$a \\:(cm\\,s^{-2})$\"\n\n constant_sets.graph_format = [\"bs\",\"r-\",\"y--\",\"y--\"]\n #general_sets.fitted_graph_label = \"Gefittete Kurve: \" + r\"$y = A\\:\\cos(\\omega t + \\phi)\\: e^{-\\beta t}$\"\n constant_sets.graph_label = [\"\",\"\",\"\",\"\"]\n\n line_sets = general_sets.clone()\n line_sets.x_label = r\"$\\Delta\\, x \\:(cm)$\"\n line_sets.y_label = r\"$v_1^2-v_2^2$\"\n\n line_sets.graph_format = [\"bs\",\"r-\",\"y--\",\"y--\"]\n #general_sets.fitted_graph_label = \"Gefittete Kurve: \" + r\"$y = A\\:\\cos(\\omega t + \\phi)\\: e^{-\\beta t}$\"\n line_sets.graph_label = [\"\",\"\",\"\",\"\"]\n\n return constant_sets, line_sets\n\n\ndef get_data(sets):\n #reads data from datasets specified in Settings\n dataset = dm.csv_to_list(sets.dataset_folder + sets.dataset_file_name)\n \n x1_vals, x2_vals = dm.return_column(dataset, title = \"x1\"), dm.return_column(dataset, title = \"x2\")\n x_err = dm.return_column(dataset, title = \"x_err\")\n x1_u, x2_u = unp.uarray(x1_vals, x_err), unp.uarray(x2_vals, x_err)\n\n x0_vals = dm.return_column(dataset, title = \"x0\")\n x0_u = unp.uarray(x0_vals, 0.1)\n\n v1_vals, v2_vals = dm.return_column(dataset, title = \"v1_corr\"), dm.return_column(dataset, title = \"v2_corr\")\n v1_err, v2_err = dm.return_column(dataset, title = \"v1_err\"), dm.return_column(dataset, title = \"v2_err\")\n v1_u, v2_u = unp.uarray(v1_vals, v1_err), unp.uarray(v2_vals, v2_err)\n\n #return x0_u/100, x1_u/100, x2_u/100, v1_u/100, v2_u/100\n return x0_u, x1_u, x2_u, v1_u, v2_u\n\n\ndef plot_constant(sets):\n f = ft.constant\n fit_samples = 2\n x0,x1,x2,v1,v2 = get_data(sets)\n dv = v2-v1\n dx = x1-x0\n a = (v1**2-v2**2)/(2*(x1-x2))\n dx_n, x0_n, dv_n, a_n = unp.nominal_values(dx), unp.nominal_values(x0), unp.nominal_values(dv), unp.nominal_values(a)\n dx_s, x0_s, dv_s, a_s = unp.std_devs(dx), unp.std_devs(x0), unp.std_devs(dv), unp.std_devs(a)\n\n popt, cov = curve_fit(f, dv_n, a_n, sigma = a_s, absolute_sigma=True)\n a_err = np.sqrt(cov[0][0])\n x_fit_v = np.linspace(0, max(dv_n), fit_samples)\n #x_fit_x = np.linspace(min(x0_n), max(x0_n), fit_samples)\n x_fit_dx = np.linspace(0, max(dx_n)*1.1, fit_samples)\n y_fit = np.array([popt[0], popt[0]])\n\n y_fit_up, y_fit_down = y_fit+a_err, y_fit-a_err\n\n a_fit = ufloat(popt, a_err)\n fmtr = ShorthandFormatter()\n a_str = fmtr.format(\"{0:.1u}\",a_fit)\n \n sets.graph_label[1] += \"a = {} \".format(a_str) + r\"$cm\\,s^{-2}$\"\n\n #fig, ax = plot_multi_2(sets, x_values = [dv_n,x_fit_v,x_fit_v,x_fit_v], y_values = [a_n,y_fit,y_fit_up,y_fit_down], x_err = [dv_s,[],[],[]], y_err = [a_s,[],[],[]])\n fig, ax = plot_multi_2(sets, x_values = [dx_n,x_fit_dx], y_values = [a_n,y_fit], x_err = [dx_s,[]], y_err = [a_s,[]])\n #fig, ax = plot_multi_2(sets, x_values = [dx_n,x_fit_dx,x_fit_dx, x_fit_dx], y_values = [a_n,y_fit,y_fit_up,y_fit_down], x_err = [x0_s,[],[],[]], y_err = [a_s,[],[],[]])\n\n ax.fill_between(x_fit_dx, y_fit_down, y_fit_up, facecolor = \"r\", alpha = 0.1)\n ax.set_xbound(0,70)\n b = ax.get_ybound()\n ax.set_ybound(b[0],b[1]+(b[1]-b[0])*0.1)\n plt.subplots_adjust(left=0.165, right = 0.98, bottom = 0.15, top = 0.99)\n \nif __name__ == \"__main__\":\n sets1, sets2 = get_settings()\n plot_constant(sets1)\n\n plt.show()","sub_path":"Versuch6/scripts/energieerhaltung.py","file_name":"energieerhaltung.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"243322308","text":"import argparse, os, sys, logging\nimport random\nimport shutil\nimport pysam\n\nparser = argparse.ArgumentParser(description='')\n\nparser.add_argument('all_novel', help='A file containing information for all the novel sites')\nparser.add_argument('-a', '--annotation', default='/projects/dmacmillanprj2/polya/ccle/novel_cleavage_events/pysam_version/with_utr3/ucsc.utr3.gtf', help='UCSC-downloaded annotation file')\nparser.add_argument(\"-l\", \"--log\", dest=\"logLevel\", default='WARNING', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level. Default = \"WARNING\"')\nparser.add_argument('-n', '--name', default='result', help='Name for the file output. Default is \"result\"')\nparser.add_argument('-o', '--outdir', default=os.getcwd(), help='Path to output to. Default is {}'.format(os.getcwd()))\n\nargs = parser.parse_args()\n\nfiltered_kleats_path = '/projects/dmacmillanprj2/polya/ccle/filteredKleats/kleats_plus_added'\nwebdir = '/gsc/www/bcgsc.ca/downloads/dmacmillan/'\ndata_output = open(os.path.join(args.outdir, 'data.compareNovel'), 'w')\n\ndef getGtexCram(name):\n return '/projects/btl/polya/gtex/star/crams/{}.star.cram'.format(name)\n\ndef getCcleCram(name):\n return '/projects/btl/polya/sorted_star_ccle/cram_sorted_{}.cram'.format(name)\n\nif not os.path.isdir(args.outdir):\n try:\n os.makedirs(args.outdir)\n except OSError:\n pass\n\n# Logging\nlogging.basicConfig(filename=os.path.join(args.outdir, 'log.compareNovel'), level=getattr(logging, args.logLevel))\n\nnovel = strong = gtex = utrs = None\n\nwith open(args.annotation, 'r') as f:\n utrs = [x.strip().split('\\t') for x in f.readlines()]\n\nwith open(args.all_novel) as f:\n all_novel = [x.strip().split('\\t') for x in f.readlines()]\n all_novel = all_novel[1:]\n\nall_ccle_samples = set([x[0] for x in all_novel])\n\ngnovel = {}\n\nfor i in all_novel:\n if i[4] not in gnovel:\n gnovel[i[4]] = {}\n if i[5] not in gnovel[i[4]]:\n gnovel[i[4]][i[5]] = []\n gnovel[i[4]][i[5]].append(i)\n\ndef sprint(text):\n sys.stdout.write(text)\n sys.stdout.flush()\n\ndef getClosestUtr3(site, utrs):\n utrs = [x for x in utrs if x[0] == site[4]]\n min_dist = float('inf')\n closest_utr3 = None\n for i, u in enumerate(utrs):\n start = int(u[3])\n end = int(u[4])\n cs = int(site[6])\n dist = min(abs(start-cs),abs(end-cs))\n if dist < min_dist:\n min_dist = dist\n closest_utr3 = u\n return closest_utr3\n\n\nwindow = 20\nclusters = []\nfor chrom in gnovel:\n for gene in gnovel[chrom]:\n cluster = {'centroid': None, 'sites': []}\n for nov in gnovel[chrom][gene]:\n cs = int(nov[6])\n if not cluster['centroid']:\n cluster['centroid'] = cs\n cluster['sites'].append(nov)\n continue\n dist = abs(cluster['centroid'] - cs)\n if dist <= 20:\n cluster['sites'].append(nov)\n cluster['centroid'] = sum([int(x[6]) for x in cluster['sites']]) / len(cluster['sites'])\n continue\n else:\n clusters.append(cluster)\n break\n\nclusters = sorted(clusters, key=lambda x: len(x['sites']), reverse=True)\n\ndef getMedian(array):\n length = len(array)\n if (length == 0):\n return 'N/A'\n elif (length % 2 == 0):\n return ((array[length/2]) + (array[(length/2)-1]))/float(2)\n else:\n return array[length/2]\n\ndef getMedianCoverage(pysam_alignment_file_object, chrom, start, end):\n ns = []\n for p in pysam_alignment_file_object.pileup(chrom, start, end, truncate=True):\n ns.append(p.n)\n median = getMedian(ns)\n return median\n\ncentroids = {}\ndata_output.write(('\\t').join(['CHROM', 'GENE', 'STRAND', 'TISSUE', 'DIST_FROM_ANNOT',\n 'PAS', 'ID', 'CELL_LINE', 'CLEAVAGE_SITE_CENTROID',\n 'SCORE', 'MEDIAN_LEFT', 'MEDIAN_RIGHT',\n 'MED_DIFF', 'CLOSEST_UTR3_ATTR']) + '\\n')\nfor clust in clusters:\n clust['best_site'] = None\n clust['best_score'] = 0\n logging.debug('Total sites in cluster: {}'.format(len(clust['sites'])))\n for i,site in enumerate(clust['sites']):\n logging.debug('site index: {}'.format(i))\n logging.debug('site: {}'.format(site))\n try:\n score = (int(site[16]) + int(site[17]) + int(site[18]) + int(site[19])) / int(site[15][1])\n except (ValueError, IndexError) as e:\n score = (int(site[16]) + int(site[17]) + int(site[18]) + int(site[19]))\n clust['sites'][i].append(score)\n if score > clust['best_score']:\n clust['best_site'] = site\n clust['best_score'] = score\n clust['best_score'] = score\n clust['best_site'] = site\n if not clust['best_site']:\n logging.debug('Skipped because no best site')\n continue\n logging.debug('Best site: {}'.format(clust['best_site']))\n closest_utr3 = getClosestUtr3(clust['best_site'], utrs)\n if not closest_utr3:\n logging.debug('Skipped because no close utr3')\n continue\n logging.debug('Closest utr3: {}'.format(closest_utr3))\n name = clust['best_site'][0]\n cline = clust['best_site'][1]\n annot_dist = clust['best_site'][11]\n pas = clust['best_site'][15]\n tissue = clust['best_site'][2]\n chrom = clust['best_site'][4]\n gene = clust['best_site'][5]\n cs = int(clust['best_site'][6])\n strand = clust['best_site'][10]\n utr3_start = int(closest_utr3[3])\n utr3_end = int(closest_utr3[4])\n if (utr3_start >= cs) or (utr3_end <= cs):\n logging.debug('Skipped because cs not within utr3')\n continue\n #print '-'*(cs-utr3_start) + '|' + '-'*(utr3_end-cs)\n ccle_aln = pysam.AlignmentFile(getCcleCram(name), 'rc')\n left = getMedianCoverage(ccle_aln, chrom, utr3_start, cs)\n right = getMedianCoverage(ccle_aln, chrom, cs, utr3_end)\n if strand == '-':\n temp = right\n right = left\n left = temp\n try:\n diff = left - right\n except TypeError:\n logging.error('TypeError abs(left - right)\\nleft: \"{}\"\\nright: \"{}\"'.format(left, right))\n diff = 0\n logging.debug('diff: {}'.format(diff))\n data = [chrom, gene, strand, tissue, annot_dist, pas, name, cline, clust['centroid'], clust['best_score'], left, right, diff, closest_utr3[8]]\n data_output.write('\\t'.join([str(x) for x in data]) + '\\n')\n","sub_path":"compareNovel.py","file_name":"compareNovel.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"377624335","text":"import pandas as pd\nimport xlwings as xw\nfrom shutil import copy2\nimport os\nfrom datetime import datetime\n\n\ndef fill_readme(sheet):\n \"\"\" Read individual lines from text file into list. \"\"\"\n txtlist = []\n with open('poc_info.txt') as f:\n for row in f:\n txtlist.append(row)\n sheet.range('H10').options(transpose=True).value = txtlist\n sheet.range('H1:I2').columns.autofit()\n print('POC info written to README')\n return\n\n\ndef write_workbook(org):\n # Record in log which org is being written\n with open(logfile, append_write) as writer:\n writer.write(org + '\\n')\n\n # Copy the template, rename it, set as active xlwings workbook\n outfile = os.path.join('output', '18q3 Roster - {}.xlsx'.format(org))\n copy2('my_template.xlsx', outfile)\n wb = xw.Book(outfile)\n print('Opening:', wb.fullname)\n\n # Filter full dataframe for member, obtain unique sheet names\n df1 = wfa.loc[wfa.org == org]\n sht_list = df1.sheet.unique()\n print('# of sheets: {}'.format(len(sht_list)))\n existing_sheets = list(wb.sheets)[1:-1]\n\n # By sheet, filter org df and write out to Excel worksheet\n for sheet, sht in zip(sht_list, existing_sheets):\n sht.name = sheet\n df2 = df1.loc[df1.sheet == sheet]\n sht.range('A5').options(index=False, header=False).value = df2\n print('\\tWrote: {} {} rows'.format(sht.name, len(df2)))\n with open(logfile, append_write) as writer: # log it\n writer.write('\\t' + sheet + str(len(df2)) + '\\n')\n\n # Write sheet list to summary tab table, write POC to README\n summary = wb.sheets('Player Summary')\n summary.range('Q2').options(transpose=True).value = sht_list\n fill_readme(wb.sheets['README'])\n\n # Delete unused sheets\n wfa_sheets = [x for x in wb.sheets if 'WFA' in str(x)]\n for sht in wfa_sheets:\n sht.delete()\n\n # Reset active sheet to first roster\n wb.sheets[1].activate()\n\n wb.save()\n print('Saved:', wb.fullname)\n wb.close()\n\n# BEGIN RUNNING\n# Create timestamp log\nlogfile = 'log.txt'\nif os.path.exists(logfile):\n append_write = 'a'\nelse:\n append_write = 'w'\nstart = datetime.now()\nstartline = 'START: ' + str(start)\nprint(startline)\nwith open(logfile, append_write) as writer:\n writer.write(startline + '\\n')\n\n# Read in source file\nwfa = pd.read_csv('18q3_full.csv')\nwfa_org_list = wfa.org.unique()\n\n# Check for output folder\nif not os.path.exists('output'):\n os.mkdir('output')\n\n# Open Excel instance\ntry:\n app1 = xw.apps[0]\nexcept IndexError:\n app1 = xw.App(visible=False)\napp1.screen_updating = True # false is faster, but if error then you can't see\n\n# choice = int(input('Which index for org? : '))\n\n# MAIN EVENT\nfor org in wfa_org_list:\n write_workbook(org)\n\napp1.quit()\n\nend = datetime.now()\nendline = 'FINISH:' + str(end)\ndurline = '\\tin {:.10}'.format(str(end-start))\nwith open(logfile, append_write) as writer:\n writer.write(endline + '\\n')\n writer.write(durline + '\\n' + '-'*50 + '\\n')\nprint(endline)\nprint(durline)\n","sub_path":"fill.py","file_name":"fill.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"631817927","text":"from panda3d.core import Point2,Point3,Vec3,Vec4\nfrom direct.task.Task import Task\nfrom panda3d.core import Camera\nfrom panda3d.core import AmbientLight, PointLight\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.actor.Actor import Actor, VBase4, DirectionalLight, PerspectiveLens\n\nfrom ship import *\n\nclass test(ShowBase):\n\tdef __init__(self):\n\t\tShowBase.__init__(self)\n\n\t\tself.gameTask = taskMgr.add(self.flyCircles, \"circles\")\n\n\n\t\tbase.disableMouse()\n\t\t\n\t\tbase.camera.setPos(50, 100, 800)\n\t\tbase.camera.lookAt(0, 0, 0)\n\n\t\tdl = DirectionalLight('dLight')\n\t\tdl.setColor(Vec4(0.1,0.1,0.1,1))\n\t\tdlNP = render.attachNewNode(dl)\n\t\tdlNP.setPos(1000,1000,0)\n\n\t\tal = AmbientLight('alight')\n\t\tal.setColor(Vec4(0.3, 0.3, 0.3, 1))\n\t\talNP = render.attachNewNode(al)\n\n\t\tpl = PointLight('plight')\n\t\tpl.setColor(VBase4(0.2,0.2,0.2,1))\n\t\tplNP = render.attachNewNode(pl)\n\t\tplNP.setPos(100,100,100)\n\t\trender.setLight(plNP)\n\n\n\n\t\tself.shipList = [\n\t\t\tBwing(\"xwing1\"), \n\t\t\tTieInterceptor(\"tie1\")\n\t\t\t]\n\n\t\t\n\t\tfor i, ship in enumerate(self.shipList):\n\t\t\tship.reparentTo(render)\n\t\t\tship.setScale(2)\n\t\t\tship.setPos(Point3(i*10,i*0,i*0))\n\t\t\t# ship.setLight(dlNP)\n\t\t\tship.setLight(alNP)\n\n\t\tself.count = 0\n\n\t\tself.iter = 0\n\t\n\n\tdef flyCircles(self, task):\n\n\t\tdt = globalClock.getDt()\n\t\t# self.shipList[1].navSystem.flyInCircle()\n\t\tself.shipList[0].navSystem.pursue(self.shipList[1])\n\t\tself.shipList[1].navSystem.pursue(self.shipList[0])\n\n\t\tstf = 0\n\t\tif False:\n\t\t\tcamera.setPos(self.shipList[stf].getPos() - self.shipList[stf].getVelocity()*100)\n\t\t\tcamera.setHpr(self.shipList[stf].navSystem.getHpr())\n\t\t\tcamera.lookAt(self.shipList[stf].getPos())\n\n\t\treturn Task.cont\n\nt = test()\nt.run()\n","sub_path":"test_goToLocation.py","file_name":"test_goToLocation.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"283391524","text":"class Scene(object):\n def __init__(self, title, urlname, description):\n self.title = title\n self.urlname = urlname\n self.description = description\n self.paths = {}\n\n def go(self, direction):\n default_direction = None\n if '*' in self.paths.keys():\n default_direction = self.paths.get('*')\n return self.paths.get(direction, default_direction)\n\n def add_paths(self, paths):\n self.paths.update(paths)\n\n# Create the scenes of the game\ncentral_corridor = Scene(\"Central Corridor\", \"centreal_corridor\",\n\"\"\"\nThe Gothons of Planet Percal #25 have invaded your ship and destroyed\nyour entire crew. You are the last surviving member (oh noes!) and your\nlast mission is to get the neutron destruct bomb from the Weapons Armory,\nput it in the bridge, and blow up the ship after getting into an escape pod.\n\nYou're now running down the central corridor to the Weapons Armory when a\nGothon hops out in an evil clown costume filled with hate. He's blocking the door\nto the Armory and about to pull a weapon to blast you.\n\"\"\")\n\nlaser_weapon_armory = Scene(\"Laser Weapon Armory\", \"laser_weapon_armory\",\n\"\"\"\nLucky for you they made you learn Gothon insults in the academy.\nYou tell the one Gothon joke you know:\nLbhe zbgure vg fb sng, jura fur vfvg nebhaq gut ubhfr, fur fvgf nebhaq gut ubhfr.\nThe Gothon bursts into laughter and rolls around on the ground. While insults laughing\nyou run up and use your copy of Nietzsche's notebooks (translated into Gothon)\nto lecture the Gothon on the shaky foundations of its ideologies. While it tries\nto cope with its existential crisis, you leap through the Weapon Armory door.\n\nYou dive roll into the Weapon Armory, crouch and scan the room more Gothons\nthat might be hiding. It's dead quiet, too quiet. You stand up and run to the far\nside of the room and find the neutron bomb in its container. There's a keypad lock\non the box and you need the code to get the bomb out. The code is 3 digits.\n\"\"\")\n\nthe_bridge = Scene(\"The Bridge\", \"the_bridge\",\n\"\"\"\nThe container clickes open and the seal breaks, letting gas out. You grab the\nneutron bomb and run like heck to the bridge where you place it in the right spot.\n\nYou burst into the Bridge with the bomb under your arm and surprises 5 Gothons\nwho are trying to take control of the ship. Each of them has an uglier clown costume\nthat the last. They don't pull their weapons out of the fear that they will set off\nthe bomb under your arm.\n\"\"\")\n\nescape_pod = Scene(\"Escape Pod\", \"escape_pod\",\n\"\"\"\nYou gesture towards the bomb and threaten to set it off, the Gothons put up\ntheir arms and ask for a truce. You inch backwards to the door, open it, and\ncarefully place the bomb on the floor, waving your finger over the detonate button.\nThen you jump back through the door, hit the close button and zap the lock so they\ncan't get out. Now that the bomb is placed you run to the escape pod.\n\nYou rush through the ship desperately trying to make it to the escape pod. It seems\nlike there's no Gothons around, so you run as fast as possible. Eventually you reach\nthe room with escape pods, and you now need to pick one to take. Some of them could\nbe damaged, but you don't have time to look. There's 5 pods, which one do you take?\n\"\"\")\n\nthe_end_winner = Scene(\"You Made It!\", \"the_end_winner\",\n\"\"\"\nYou jump into pod 2 and hit the eject button. The pod flies out into space heading\nto the planet below. As you're heading down, you look back and see your ship implode\nand then explode like a supernova, taking down the Gothon ship at the same time.\nYou made it!\n\"\"\")\n\nthe_end_loser = Scene(\"...\", \"the_end_loser\",\n\"\"\"\nMeanwhile, the bomb exploded in the pod. All the innocent people were\nthere... You killed them all. Even though you survive but you will live\nwith guilty forever, you loser!\n\"\"\")\n\nisland = Scene(\"Welcome to Magic Island\", \"island\",\n\"\"\"\nYou have been thrown out from the ship and now landed on this Magic Island.\nThis island is so quiet. You walk around and explore a bit. A few hours later,\nyou feel so hungry and exhausted. You really need some food.\n\nYou walk and walk...Oh, there are some food! You see some apples on the tree,\nsome mushrooms on the ground, and wait...an unfinished proper meal.\nWhich one do you choose?\n\"\"\")\n\nhealthy = Scene(\"Healthy agian\", \"healthy\",\n\"\"\"\nThanks to the apples, they cure you. Now you are strong and\nhealthy again. Do you want to leave the island or stay?\n\"\"\")\n\nescape_pod_dodge = Scene(\"Escape Pod\", \"escape_pod\",\n\"\"\"\nYou had been swimming for more than 2 days. And here you are finally, the Escape Pod. Eventually\nyou reach the room with escape pods, and you now need to pick one to take. Some of them could be\ndamaged, but you don't have time to look. There's 5 pods, which one do you take?\n\"\"\")\n\nmagic_power = Scene(\"You got some magic power\", \"magic_power\",\n\"\"\"\nNow you know why this island is called \"Magic Island\".\nAll the mushrooms contain special supernatural power.\nOnce you eat them, you will have a strong magic power.\nYou could time travel back to whenever you want.\nWhich period do you want to travel back?\n\"\"\")\n\ncentral_corridor_dodge = Scene(\"Central Corridor\", \"centreal_corridor\",\n\"\"\"\nYou are here again. How is the time travelling experience?\nGood? Exciting? The invaders are still here. What do you\nwant to do this time? Still dodge them or do other actions?\n\"\"\")\n\none_bullet_left = Scene(\"One bullet to go\", \"one_bullet_left\",\n\"\"\"\nYou shoot them all down but one. And most importantly, you have only\none bullet left. This shot is critcal. Do you want to shoot him left or right?\n\"\"\")\n\nhave_control = Scene(\"You have control\", \"have_control\",\n\"\"\"\nWow, you have made it. You are born to be a killer. Now\nyou have the control of the ship, which way do you want to go?\n\"\"\")\n\nhave_control_shoot = Scene(\"You have control\", \"have_control\",\n\"\"\"\nYou found a gun in the first drawer and you shooted the man.\nYou are born to be a killer. Now you have the control of the ship,\nwhich way do you want to go?\n\"\"\")\n\ntied = Scene(\"You got tied\", \"tied\",\n\"\"\"\nOh no...you missed the shot and he tied you. Now it's doomed. Wait...\nthere is a cupboard behind you. There must something to help you get out of here.\nDo you want to open the first drawer, second drawer or the third drawer?\n\"\"\")\n\nphone = Scene(\"Phone\", \"phone\",\n\"\"\"\nYou found a phone in the second drawer. You open the contact list.\nEmergency: 112\nHead Quarter: 648394794801\nWhich number do you want to dial?\n\"\"\")\n\nlaser_weapon_armory_shoot = Scene(\"Laser Weapon Armory\", \"laser_weapon_armory\",\n\"\"\"\nYou arrived the Weapon Armory. You leap through the Weapon Armory door.\n\nYou dive roll into the Weapon Armory, crouch and scan the room more Gothons\nthat might be hiding. It's dead quiet, too quiet. You stand up and run to the far\nside of the room and find the neutron bomb in its container. There's a keypad lock\non the box and you need the code to get the bomb out. The code is 3 digits.\n\"\"\")\n\nthe_end_winner_shoot = Scene(\"Head Quarter has control\", \"the_end_winner\",\n\"\"\"\nYou tell everything to the head quarter. And now, they will send\nanother team to the Weapon Armory to do the rest. You have already\ndone a great job. You will receive the highest honour from Gothon.\n\"\"\")\n\ngeneric_death_nth = Scene(\"Death\", \"death\",\n\"\"\"\nThis drawer has nothing in it...The man saw you opening\nthe drawer. He is now really mad and gonna take out his\ngun...Booooooommbbbbbb! You are dead.\n\"\"\")\n\ngeneric_death_police = Scene(\"Death\", \"death\",\n\"\"\"\nYou called the police and guess what. They are too stupid\nand said they didn't know where exactly you were and could\nnot help. You are dead.\n\"\"\")\n\ngeneric_death_poison = Scene(\"Death\", \"death\",\n\"\"\"\nThis meal is poisonous. That's why it is unfinished because\nthe last one who ate this could not finish it and died after\ntwo bites. The corpse is still missing. Now it's your turn.\nYou are dead.\n\"\"\")\n\ngeneric_death = Scene(\"Death\", \"death\",\n\"\"\"\nLooks like you bit the dust.\n\"\"\")\n\n# Define the action commands available in each Scene\nescape_pod.add_paths({\n '1': the_end_loser,\n '2': the_end_winner,\n '3': the_end_loser,\n '4': the_end_loser,\n '5': the_end_loser\n})\n\nthe_bridge.add_paths({\n 'throw the bomb': generic_death,\n 'slowly place the bomb': escape_pod\n})\n\nlaser_weapon_armory.add_paths({\n '132': the_bridge,\n '*': generic_death\n})\n\ncentral_corridor.add_paths({\n 'shoot':one_bullet_left,\n 'dodge':island,\n 'tell a joke': laser_weapon_armory\n})\n\nisland.add_paths({\n 'apples':healthy,\n 'mushrooms':magic_power,\n 'unfinished proper meal': generic_death_poison\n})\n\nhealthy.add_paths({\n 'leave':escape_pod_dodge,\n 'stay': the_end_loser\n})\n\nmagic_power.add_paths({\n 'central corridor': central_corridor_dodge,\n 'island': island\n})\n\none_bullet_left.add_paths({\n 'left': have_control,\n 'right': tied\n})\n\nhave_control.add_paths({\n 'laser weapon armory': laser_weapon_armory_shoot,\n 'home': the_end_loser\n})\n\ntied.add_paths({\n 'first drawer': have_control_shoot,\n 'second drawer': phone,\n 'third drawer': generic_death_nth\n})\n\nphone.add_paths({\n '112': generic_death_police,\n '648394794801': the_end_winner_shoot\n})\n\n# Make some useful variables to be used in the web application\nSCENES = {\n central_corridor.urlname : central_corridor,\n central_corridor_dodge.urlname : central_corridor,\n laser_weapon_armory.urlname : laser_weapon_armory,\n laser_weapon_armory_shoot.urlname : laser_weapon_armory,\n the_bridge.urlname : the_bridge,\n escape_pod.urlname : escape_pod,\n escape_pod_dodge.urlname : escape_pod,\n the_end_winner.urlname : the_end_winner,\n the_end_winner_shoot.urlname : the_end_winner,\n the_end_loser.urlname : the_end_loser,\n generic_death.urlname : generic_death,\n generic_death_nth.urlname : generic_death,\n generic_death_police.urlname : generic_death,\n generic_death_poison.urlname : generic_death,\n island.urlname : island,\n healthy.urlname : healthy,\n magic_power.urlname : magic_power,\n one_bullet_left.urlname : one_bullet_left,\n have_control.urlname : have_control,\n have_control_shoot.urlname : have_control,\n tied.urlname : tied,\n phone.urlname : phone\n}\nSTART = central_corridor\n","sub_path":"EX52/gothonweb/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":10239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"473688816","text":"import threading\nfrom .telegram_connection import process_updates\nimport atexit\n\ndef run():\n global CONTINUE\n\n next_update_id = 0\n while CONTINUE:\n next_update_id = process_updates(next_update_id)\n\ndef stop():\n print('stopping update thread')\n\n global CONTINUE\n CONTINUE = False\n\n\ndef start():\n print('starting update thread')\n\n global CONTINUE\n CONTINUE = True\n\n update_thread = threading.Thread(target=run)\n update_thread.start()\n\n atexit.register(stop)\n","sub_path":"alertinator/update_thread.py","file_name":"update_thread.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"576052246","text":"#%%\nfrom collections import defaultdict\nfrom re import template,sub\nfrom pyecharts.charts.basic_charts.wordcloud import WordCloud\nfrom pyspark import SparkConf,SparkContext\nfrom pyspark.ml.feature import CountVectorizer, IDF,HashingTF,Tokenizer\nfrom pymongo import MongoClient\nfrom pyspark.sql.functions import json_tuple\nfrom pyspark.sql.session import SparkSession\nimport numpy as np\nimport jieba\nimport json\nfrom pyecharts import options as opts\nfrom tqdm import tqdm\nnp.set_printoptions(threshold=np.inf)\n#%%\n\"\"\" mongodb连接 \"\"\"\nhost = 'localhost' # 你的ip地址\nclient = MongoClient(host, 27017) # 建立客户端对象\ndb = client[\"Gootworms\"] # 连接mydb数据库,没有则自动创建\n#%%\nsentence_list=[]\nresult=db[\"Result\"]\ncounter=0\nfor i in result.find():\n if \"content\" in i:\n if i[\"content\"] is None:continue\n content=str(list(jieba.cut(i[\"content\"].replace(\" \",\"\")))).\\\n replace(\",\",\" \").replace(\"'\",\"\")\n # print(content)\n # 去除特殊字符\n temp_tupple=(counter,sub(r\"[a-zA-Z]+\",\"\",content[1:-2]))\n sentence_list.append(temp_tupple)\n counter+=1\n#%% \n\"\"\" 初始化spark并创建dataframe \"\"\"\nconf=SparkConf().setMaster(\"local\").setAppName(\"NewsAnalys\")\nsc=SparkContext(conf=conf)\nspark=SparkSession(sc)\nsentenceData=spark.createDataFrame(sentence_list).toDF(\"label\",\"sentence\").distinct()\n# %%\ntokenizer=Tokenizer(inputCol=\"sentence\",outputCol=\"words\")\nwordsData=tokenizer.transform(sentenceData)\n#%%\nwordsData.show(1)\n#%%\n\"\"\" TF哈希结果(无法将词频对应上单词)\"\"\"\nhashingTF=HashingTF(inputCol=\"words\",outputCol=\"rawFeatures\")\nfeaturizeData=hashingTF.transform(wordsData)\nfeaturizeData.select(\"words\",\"rawFeatures\").show(truncate=False)\n#%%\n\"\"\" CountVectorizer词频统计(可以将词频对应上单词)\"\"\"\ncountVector=CountVectorizer(inputCol=\"words\",outputCol=\"rawFeatures\",minDF=2)\ncvModel=countVector.fit(wordsData)\ncv_df=cvModel.transform(wordsData)\ncv_df.show(4,False)\n#%%\n# voc=cvModel.vocabulary\n# getKeywordFunc=udf()\n# %%\n\"\"\" IDF模型训练 \"\"\"\nidf=IDF(inputCol=\"rawFeatures\",outputCol=\"features\")\nidfModel=idf.fit(cv_df)\nrescaledData=idfModel.transform(cv_df)\n# %%\nlist=rescaledData.collect()\n# with open(\"./collect_file.txt\",\"w+\") as f:\n# f.write(str(list))\n# %%\nFeatures=rescaledData.select(\"features\").toPandas()\nWords=rescaledData.select(\"words\").toPandas()\n#%%\nfeatures_dict=Features.to_dict()\n# with open(\"./features_dict.txt\",\"w\") as f:\n# f.write(str(features_dict[\"features\"]))\n# %%\nfeatures_numpy=np.array(Features)\n#%%\nword_idf=defaultdict(float)\nvacabulary=cvModel.vocabulary\nfeatures_dict=Features.to_dict()\nfeatures=features_dict[\"features\"]\ndocs=features.keys()\n#%%\nfor doc_num in tqdm(docs):\n temp_features=features[int(doc_num)]\n values=temp_features.values\n indices=temp_features.indices\n for i in indices:\n word_idf[vacabulary[int(i)]]=temp_features[int(i)]\njsObj = json.dumps(word_idf)\nwith open(\"./word_idf.json\",\"w+\") as f:\n f.write(jsObj)\n# with open(\"./word_idf.json\",\"r\") as f:\n# word_idf=json.loads(f.read())\n\n#%%\nword_cloud_list=[]\nfor k,v in word_idf.items():\n word_cloud_list.append((k,v))\nwith open(\"./word_cloud_list.txt\",\"w\") as f:\n f.write(str(word_cloud_list))\n\n#%%\n#%%\nwith open(\"./features_numpy.txt\",\"w+\") as f:\n f.write(str(features_numpy[0][0]))\n#%%\n\"\"\" 计算两两文本间的idf-tf的余弦相似度 \"\"\"\nres_list=[]\nfor i in range(496):\n for j in range(i+1,496):\n vec1=features_numpy[i][0].toArray()\n vec2=features_numpy[j][0].toArray()\n num=vec1.dot(vec2.T)\n denom=np.linalg.norm(vec1)*np.linalg.norm(vec2)\n res_list.append(((i,j),num/denom))\n# %%\n# with open(\"cosineSim.txt\",\"w+\") as f:\n# f.write(str(res_list))\n# %%\n# 渲染图\ndef wordcloud_base() -> WordCloud:\n c = (\n WordCloud()\n .add(\"\", word_cloud_list, word_size_range=[20, 100], shape='diamond') # SymbolType.ROUND_RECT\n .set_global_opts(title_opts=opts.TitleOpts(title='WordCloud词云'))\n )\n return c\n\n# 生成图\nwordcloud_base().render('./词云图.html')\n\n# %%\n","sub_path":"test/spark_handle.py","file_name":"spark_handle.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"550569648","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 30 09:26:47 2018\n\n@author: pme-mst\n\"\"\"\n\nfrom datetime import datetime\nfrom IebwumsDataHandling import MySqlFunctions as MySqlF\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.io\n\n# Definition\n\nRZ24_0001 = MySqlF.MysqlConPara(\"24_0001adm\",\"HILSQL@ebc\",\"d24.itc.rwth-aachen.de\",3324,\"24_0001\")\n\nmeine_variablen = [\"KK.Soll_Temp_KK\", \"HYD.Bank[4].Temp_extRL.REAL_VAR\",\"HYD.Bank[4].Soll_Vdot\",\"HYD.Bank[4].Vdot.REAL_VAR\" ]\nMessreihe = \"hil2_20180130_115522_measurement\"\nstart = datetime(2018, 1, 31, 12, 3, 24)\nend = datetime(2018, 2, 1, 12, 3, 24)\nSpeicherort = (r'D:\\pme-mst\\dymola repos\\MA\\SimulationInputData\\Tables\\CalibrationData\\CalibrateHP.hdf3').replace('\\\\','/')\nmein_titel = \"TestFigure\"\n\n# Daten von SQL-Server downloaden\nmy_data = MySqlF.ReadData(MysqlConPara = RZ24_0001, Messreihe = Messreihe, Variable = meine_variablen, Startzeit = start, Endzeit = end, Interpolationsweite = \"1s\", ZeilenSchrittweite = 1)\n\n# Zeitspalte in Sekunden umwandeln\nmy_data.to_hdf(Speicherort,key=mein_titel)\n\n# pd frame erstellen\ndf = pd.read_hdf(Speicherort)\n\n# Ungewünschte Anfangsreihen rausschmeißen\ndf = df.drop(df.index[np.arange(0,11,1)])\n\n# Auswahl der Werte ab Überschreiten eines Schwellenwertes\ndf = df[df[\"HYD.Bank[4].Vdot.REAL_VAR\"] > 1]\n\n# Daten nach Taußen sortieren\ndf = df.sort_values(by=[\"KK.Soll_Temp_KK\"])\n\n# Plots erzeugen \n#T_a = plt.plot(df[\"KK.Soll_Temp_KK\" ]) \n#V_ist = plt.plot(df[\"HYD.Bank[4].Vdot.REAL_VAR\" ]) \n#V_soll = plt.plot(df[\"HYD.Bank[4].Soll_Vdot\"])\nplt.plot(df[\"KK.Soll_Temp_KK\"], df[\"HYD.Bank[4].Temp_extRL.REAL_VAR\"])","sub_path":"Datenauswertung/Statistische Auswertungen/HeatingCurveMeasured.py","file_name":"HeatingCurveMeasured.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"190645258","text":"import platform\n\nimport pkg_resources\nimport requests\nfrom requests import Response\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util import Retry\n\nfrom .config import ProxyConfiguration, HttpConfiguration\nfrom .errors import ServerError\nfrom .request import BaseRequest\n\n\ndef generate_params(api_key, request):\n \"\"\"\n Used to generate params from request\n Parameters\n ----------\n api_key : str\n request : BaseRequest\n\n Returns\n -------\n\n \"\"\"\n params = request.decode()\n params['apiKey'] = api_key\n return params\n\n\ndef generate_proxy(proxy_config):\n \"\"\"\n Generate requests specific proxy configuration\n Parameters\n ----------\n proxy_config : ProxyConfiguration\n\n Returns\n -------\n proxy config for requests\n \"\"\"\n proxy = None\n if proxy_config:\n if proxy_config.username:\n proxy = {proxy_config.protocol: '{0}://{1}:{2}@{3}:{4}'.format(proxy_config.protocol,\n proxy_config.username,\n proxy_config.password,\n proxy_config.host,\n proxy_config.port)}\n else:\n proxy = {proxy_config.protocol: '{0}://{1}:{2}'.format(proxy_config.protocol,\n proxy_config.host,\n proxy_config.port)}\n\n return proxy\n\n\ndef generate_timeout_and_retry(http_config):\n \"\"\"\n Generate timeout and retry mechanism for requests to use\n Parameters\n ----------\n http_config : HttpConfiguration\n\n Returns\n -------\n tuple (tuple, Retry)\n \"\"\"\n timeout = (http_config.connect_timeout, http_config.read_timeout)\n\n retry = Retry(total=http_config.max_retry, status_forcelist=[500, 501, 502, 503])\n\n return timeout, retry\n\n\ndef generate_user_agent():\n version = pkg_resources.require(\"opsgenie-sdk\")[0].version\n return \"opsgenie-python-sdk/{0}; {1}/{2}; {3}\".format(version,\n platform.system(),\n platform.release(),\n platform.python_version())\n\n\ndef execute_http_call(method, url, params, retry, timeout, proxy, attachment=None):\n \"\"\"\n Executes http call using requests library\n Parameters\n ----------\n method : str\n url : str\n params : dict\n retry : Retry\n timeout : tuple\n proxy : object\n attachment : str\n\n Returns\n -------\n Response\n \"\"\"\n session = requests.session()\n session.mount('http://', HTTPAdapter(max_retries=retry)) # Documented in HTTPAdapter\n session.mount('https://', HTTPAdapter(max_retries=retry)) # Documented in HTTPAdapter\n session.headers = {'User-Agent': generate_user_agent()}\n if method is \"GET\":\n response = session.get(url, params=params, proxies=proxy, timeout=timeout)\n elif method is \"DELETE\":\n response = session.delete(url, params=params, proxies=proxy, timeout=timeout)\n elif method is \"POST\":\n if attachment is None:\n response = session.post(url, json=params, proxies=proxy, timeout=timeout)\n else:\n response = session.post(url, data=params, proxies=proxy, timeout=timeout,\n files={'attachment': open(attachment, 'rb')})\n else:\n raise NotImplementedError()\n\n return response\n\n\ndef execute(method, url_suffix, response_cls, attachment=False):\n \"\"\"\n Executes http call with given parameters\n Parameters\n ----------\n method : {'GET', 'POST', 'DELETE'}\n url_suffix : str\n response_cls : class\n Class of response type\n attachment : bool\n \"\"\"\n\n def request_wrapper(__):\n def request_call(self, request):\n \"\"\"\n\n Parameters\n ----------\n self : BaseService\n request : instance of BaseRequest subclass\n\n Returns\n -------\n Instance of response_cls\n \"\"\"\n request.validate()\n\n url = self.configuration.endpoint + url_suffix\n params = generate_params(self.configuration.api_key, request)\n proxy = generate_proxy(self.configuration.proxy_config)\n timeout, retry = generate_timeout_and_retry(self.configuration.http_config)\n\n response = execute_http_call(method, url, params, retry, timeout, proxy,\n None if attachment is False else request.attachment)\n\n handle_error(response)\n return response_cls(response.text)\n\n return request_call\n\n return request_wrapper\n\n\ndef handle_error(response):\n if response.status_code is not 200:\n raise ServerError(response.text)\n\n\nclass BaseService:\n def __init__(self, configuration):\n \"\"\"\n\n Parameters\n ----------\n configuration : Configuration\n \"\"\"\n self.configuration = configuration\n","sub_path":"opsgenie/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":5273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"326651266","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/bee/Dev/piu/django/testSite/bee_django_user/templatetags/bee_django_user_filter.py\n# Compiled at: 2020-01-06 03:52:53\n__author__ = 'zhangyue'\nfrom datetime import datetime\nfrom django import template\nfrom django.contrib.auth.models import User, Group, Permission\nfrom bee_django_user.exports import get_user_leave_status\nregister = template.Library()\n\n@register.filter\ndef get_difference_abs(a, b):\n return abs(a - b)\n\n\n@register.filter\ndef has_permission(group, permission_name):\n try:\n if group.permissions.get(codename=permission_name):\n return True\n else:\n return False\n\n except:\n return False\n\n\n@register.filter\ndef has_manage(user):\n try:\n if user.userprofile.has_group('管理员') or user.userprofile.has_group('客服') or user.userprofile.has_group('助教'):\n return True\n except:\n return False\n\n return False\n\n\n@register.simple_tag\ndef get_leave_status(user):\n status = get_user_leave_status(user)\n if status:\n return '请假中'\n\n\n@register.simple_tag\ndef get_user_live_detail(user, time):\n try:\n from bee_django_course.models import UserLive\n if time == '本日':\n scope = 'day'\n offset = 0\n elif time == '昨日':\n scope = 'day'\n offset = -1\n elif time == '本周':\n scope = 'week'\n offset = 0\n elif time == '上周':\n scope = 'week'\n offset = -1\n elif time == '本月':\n scope = 'month'\n offset = 0\n elif time == '上月':\n scope = 'month'\n offset = -1\n else:\n return (0, 0, 0)\n return UserLive.get_user_live_detail([user], scope=scope, offset=offset)\n except Exception as e:\n return (0, 0, 0)\n\n\n@register.filter\ndef get_class_coin(class_id):\n try:\n from bee_django_coin.models import OtherCoinCount\n record = OtherCoinCount.objects.get(coin_type__identity='user_class', coin_content_id=class_id)\n return record.count\n except:\n return\n\n return\n\n\n@register.simple_tag\ndef get_group_has_permission(group_id, codename):\n group = Group.objects.get(id=group_id)\n has_permission = False\n if group.permissions.filter(codename=codename).exists():\n has_permission = True\n return has_permission","sub_path":"pycfiles/bee-django-user-0.0.98.tar/bee_django_user_filter.py","file_name":"bee_django_user_filter.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"192570239","text":"from sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\nimport numpy as np\r\nimport pickle\r\n\r\n# IMPLEMENTS THE RANDOM FOREST CLASSIFIER\r\n# IT TAKES AS INPUT THE TRAIN SET AND LABELS \r\n# FOR CALIBRATION AND THE TEST SET AND LABELS\r\n# FOR EVALUATION AND CONFUSION MATRIX\r\n# THE reuse VARIABLE INDICATES IF THE MODEL HAS TO BE TRAINED\r\n# AGAIN OR IF IT WILL JUST BE LOADED AND USED AS IS\r\n# WARNING : MAKE SURE THAT A SAVED MODEL INSTANCE (.pkl) EXISTS\r\ndef f_RFC(X_train, Y_train, X_test, Y_test, reuse):\r\n if reuse:\r\n with open('Algos/RFC_folder/RFC.pkl', 'rb') as filehandler:\r\n classifier = pickle.load(filehandler)\r\n else:\r\n\t\t# n_estim IS THE NUMBER OF TREES TO TRAIN SEPARATELY\r\n\t\t# BEFORE BEING COMPILED TOGETHER AS A RANDOM FOREST\t\r\n\t\t# THE max_depth IS THE MAXIMUM NUMBER OF DECISIONS/NODES\r\n\t\t# IN THE DECISION TREE\r\n\t\t# n_jobs IS THE NUMBER OF PARALLEL COMPUTATIONS TO ALLOW\r\n\t\t# -1 BEING THE MAXIMUM POSSIBLE\t\r\n n_estim = 50\r\n classifier = RandomForestClassifier(n_estimators=n_estim, max_depth=15,\r\n n_jobs=20, class_weight='balanced')\r\n # TRAINING THE RFC WITH THE TRAIN SET \r\n print('Training the RandomForest')\r\n classifier.fit(X_train, Y_train)\r\n print('Now scoring the classification of the different labels')\r\n\r\n # SCORING THE MODEL ON THE TEST SET GIVEN IN ARGUMENT\r\n # AND GENERATING THE CONFUSION MATRIX\r\n conf_matrix = confusion_matrix(classifier.predict(X_test), Y_test)\r\n normalisation = np.sum(conf_matrix, axis=1, keepdims=True)\r\n conf_matrix = conf_matrix/normalisation\r\n print(conf_matrix)\r\n\r\n # SAVES THE MODEL\r\n with open('Algos/RFC_folder/RFC.pkl', 'wb') as filehandler:\r\n pickle.dump(classifier, filehandler)\r\n print('Model saved')\r\n \r\n return conf_matrix\r\n","sub_path":"3_categories/Algos/RFC_folder/RFC.py","file_name":"RFC.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"90579323","text":"from flask import Flask, request\nimport telepot\nimport urllib3\n\nproxy_url = \"http://proxy.server:3128\"\ntelepot.api._pools = {\n 'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=30),\n}\ntelepot.api._onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=proxy_url, num_pools=1, maxsize=1, retries=False, timeout=30))\n\nsecret = \"d0006cdc-de2c-4429-89b1-97094bddb945\"\n#bot = telepot.Bot(\"535413959:AAEjg6O6I648ZZcbPB91Ps8SFRJciKeGuv8\")\nbot.setWebhook(\"https://Izzard.pythonanywhere.com/{}\".format(secret), max_connections=1)\n\napp = Flask(__name__)\n\n@app.route('/{}'.format(secret), methods=[\"POST\"])\ndef telegram_webhook():\n update = request.get_json()\n if \"message\" in update:\n text = update[\"message\"][\"text\"]\n chat_id = update[\"message\"][\"chat\"][\"id\"]\n bot.sendMessage(chat_id, \"From the web: you said '{}'\".format(text))\n return \"OK\"","sub_path":"esempio.py","file_name":"esempio.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"230408856","text":"\"\"\"\nCode to configure the survey's redis coordinator.\n\n\"\"\"\n\nimport tempfile\nimport shutil\nimport os\n\nfrom fabric.api import *\n\n@task\n@runs_once # do this once, locally\ndef compile_redis():\n \"Compile redis locally\"\n tempdir = tempfile.mkdtemp()\n try:\n os.remove('redis-server')\n except OSError:\n pass\n try:\n os.remove('redis-cli')\n except OSError:\n pass\n\n with lcd(tempdir):\n local('wget http://download.redis.io/releases/redis-2.8.3.tar.gz'\n ' -O -| tar xz --strip 1')\n local('make')\n #local('make test') # takes a long time\n shutil.move(os.path.join(tempdir, 'src/redis-server'),\n '.')\n shutil.move(os.path.join(tempdir, 'src/redis-cli'),\n '.')\n shutil.rmtree(tempdir)\n\n@task\ndef configure_redis():\n \"Copy redis configuration and scripts\"\n sudo('mkdir -p /etc/redis')\n sudo('rm -rf /etc/redis/*')\n put('configs/redis.upstart', '/etc/init/redis.conf',\n use_sudo=True)\n put('configs/redis.conf', '/etc/redis/redis.conf',\n use_sudo=True)\n put('configs/redis-local.conf', '/etc/redis/redis-local.conf',\n use_sudo=True)\n\n@task\ndef copy_redis():\n \"Copy local redis binary to remote\"\n put('redis-server', '/usr/local/bin/redis-server',\n use_sudo=True, mirror_local_mode=True)\n put('redis-cli', '/usr/local/bin/redis-cli',\n use_sudo=True, mirror_local_mode=True)\n\n@task\ndef install_redis():\n \"Compile, then install redis remotely\"\n compile_redis()\n configure_redis()\n copy_redis()\n sudo('service redis restart', warn_only=True)\n","sub_path":"configurator/fabfile/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"242174388","text":"import spacy\nfrom spacy.lang.en import English\nfrom spacy.matcher import Matcher\n\ndef is_float(n):\n try:\n support_float_with_norwegian_format = n.replace(',','.')\n float_n = float(support_float_with_norwegian_format)\n except ValueError:\n return False\n else:\n return True\n\ndef is_int(n):\n try:\n float_n = float(n)\n int_n = int(float_n)\n except ValueError:\n return False\n else:\n return float_n == int_n\n\ndef identify_TRADE_AREA_in_text(text):\n nlp = English()\n doc = nlp(text)\n matcher = Matcher(nlp.vocab)\n\n #\n # START - spaCy patterns\n #\n\n matcher.add(\n \"TRADE_AREA\",\n [\n [\n {\"LOWER\": {\"IN\": [\"bankfiske\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"havfiske\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"fjordfiske\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"isfarvann\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"kystfiske\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"fartsområde\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"europeisk\"]}},\n {\"LOWER\": {\"IN\": [\"fart\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"stor\"]}},\n {\"LOWER\": {\"IN\": [\"kystfart\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"internasjonal\"]}},\n {\"LOWER\": {\"IN\": [\"reise\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"intent\"]}},\n {\"LOWER\": {\"IN\": [\"sertifisert\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"nord-\"]}},\n {\"LOWER\": {\"IN\": [\"og\"]}},\n {\"LOWER\": {\"IN\": [\"østersjøfart\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"oversjøiskfart\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"fart\"]}},\n {\"LOWER\": {\"IN\": [\"på\"]}},\n {\"LOWER\": {\"IN\": [\"innsjøer\"]}},\n {\"LOWER\": {\"IN\": [\"og\"]}},\n {\"LOWER\": {\"IN\": [\"elver\"]}}\n ],\n [\n {\"LOWER\": {\"IN\": [\"uinnskrenket\"]}},\n {\"LOWER\": {\"IN\": [\"fart\"]}}\n ]\n ])\n\n #\n # END - spaCy patterns\n #\n\n result = []\n\n for match_id, token_start, token_end in matcher(doc):\n\n match_id_as_string = nlp.vocab.strings[match_id]\n final_token_start = token_start\n final_token_end = token_end\n\n spacy_pattern_detection = doc[token_start:token_end]\n spacy_pattern_detection_as_lower_text = spacy_pattern_detection.text.lower()\n \n #\n # Expand VESSEL_TYPE?\n #\n\n if match_id_as_string == \"TRADE_AREA\" and token_start > 0:\n\n if spacy_pattern_detection_as_lower_text == \"internasjonal reise\":\n\n prev_word_1_token_number = token_start - 1\n prev_word_1_token = doc[prev_word_1_token_number]\n\n if prev_word_1_token.text.lower() == \"kort\":\n # Example: kort internasjonal reise\n # Expanding.\n final_token_start = prev_word_1_token_number\n\n elif spacy_pattern_detection_as_lower_text == \"fartsområde\":\n\n next_word_1_token_number = token_end\n next_word_1_token = doc[next_word_1_token_number]\n\n if is_int(next_word_1_token.text.lower()):\n # Example: fartsområde 5\n # Expanding.\n final_token_end = next_word_1_token_number + 1\n\n elif (spacy_pattern_detection_as_lower_text == \"bankfiske\" or \n spacy_pattern_detection_as_lower_text == \"havfiske\" or\n spacy_pattern_detection_as_lower_text == \"isfarvann\"):\n\n next_word_1_token_number = token_end\n next_word_1_token = doc[next_word_1_token_number]\n\n if (next_word_1_token.text.lower() == \"i\" or \n next_word_1_token.text.lower() == \"ii\"):\n # Example: havfiske II\n # Expanding.\n final_token_end = next_word_1_token_number + 1\n\n #\n # convert token_span to char_span.\n # char_span is needed to display correctly withdisplacy.render().\n #\n span = doc[final_token_start:final_token_end]\n span_char_start = span[0].idx\n span_char_end = span[-1].idx + len(span[-1].text)\n\n # return result\n identified_entity = {'start': span_char_start, 'end': span_char_end, 'label': match_id_as_string}\n result.append(identified_entity)\n\n return result\n\ndef merge_spacy_entity_results_to_spacy_ner_format(spacy_ner_formated_text_line,spacy_ner_entities_to_be_merged_in_as_a_list):\n text = spacy_ner_formated_text_line['text']\n ents = spacy_ner_formated_text_line['ents']\n title = spacy_ner_formated_text_line['title']\n\n if ents:\n for ent in spacy_ner_entities_to_be_merged_in_as_a_list:\n ents.append(ent)\n else:\n ents = spacy_ner_entities_to_be_merged_in_as_a_list\n\n return {'text': text, 'ents': sorted(ents, key=lambda x: x['start']), 'title': title}\n\ndef identify_TRADE_AREA_in_norwegian_spacy_lines(spacy_lines):\n\n result = []\n\n for spacy_line in spacy_lines:\n\n if spacy_line['text'] != \"\\n\" and len(spacy_line['text']) > 0:\n\n nlp_result_list = identify_TRADE_AREA_in_text(spacy_line['text'])\n\n # this result might be empty.\n\n if nlp_result_list:\n\n # we have results to merge in.\n # merge in the result using this function.\n new_spacy_line = merge_spacy_entity_results_to_spacy_ner_format(spacy_line,nlp_result_list)\n\n result.append(new_spacy_line)\n else:\n result.append(spacy_line)\n else:\n result.append(spacy_line)\n\n return result","sub_path":"NLP Python Jupyter Notebooks/Script - Api - identify-TRADE_AREA-in-text-service-norwegian-chapter/spacy_matching_rule_identify_TRADE_AREA_no.py","file_name":"spacy_matching_rule_identify_TRADE_AREA_no.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"321702683","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format\nfrom pyspark.sql.types import TimestampType\nfrom pyspark.sql.functions import to_timestamp,monotonically_increasing_id\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ['AWS_ACCESS_KEY_ID']=config.get('AWS_CREDENTIALS','AWS_ACCESS_KEY_ID')\nos.environ['AWS_SECRET_ACCESS_KEY']=config.get('AWS_CREDENTIALS','AWS_SECRET_ACCESS_KEY')\n\n\ndef create_spark_session():\n \"\"\"This function will create the spark session that will be available all the session.\"\"\"\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\n\ndef process_song_data(spark, input_data, output_data):\n \"\"\"This function will ingest the data from the song_data path. Also will create the parquets files for the songs table and artist table.\"\"\"\n # get filepath to song data file\n song_data = input_data + \"song_data/*/*/*/*.json\"\n \n # read song data file\n df = spark.read.json(song_data)\n\n # extract columns to create songs table\n songs_table = df.select(\"song_id\",\"title\", \"artist_id\",\"year\",\"duration\").dropDuplicates()\n \n # write songs table to parquet files partitioned by year and artist\n songs_table.write.mode(\"overwrite\").partitionBy(\"year\",\"artist_id\").parquet(output_data+\"songs\")\n\n # extract columns to create artists table\n artists_table = df.select(\"artist_id\",col(\"artist_name\").alias(\"name\"),col(\"artist_location\").alias(\"location\"),col(\"artist_latitude\").alias(\"latitude\"),col(\"artist_longitude\").alias(\"longitude\")).dropDuplicates()\n\n # write artists table to parquet files\n artists_table.write.mode(\"overwrite\").parquet(output_data+\"artists\")\n\n\ndef process_log_data(spark, input_data, output_data):\n \"\"\"This function will ingest the data from the log-data path. Also will create the parquets files for the users table and the time table. In the case of the songplays table, it will be joined with the data from the song_path.\"\"\"\n \n # get filepath to log data file\n log_data = input_data + \"log-data\"\n\n # read log data file\n df = spark.read.json(log_data)\n \n # filter by actions for song plays\n df = df.filter(col(\"page\")=='NextSong').filter(df.userId.isNotNull())\n\n # extract columns for users table \n users_table = df.select(col(\"userId\").alias(\"user_id\"), col(\"firstName\").alias(\"first_name\"), col(\"lastName\").alias(\"last_name\"), \"gender\", \"level\").dropDuplicates()\n \n # write users table to parquet files\n users_table.write.mode(\"overwrite\").parquet(output_data+\"users\")\n\n # create timestamp column from original timestamp column\n get_timestamp = udf(lambda x: str(int(int(x) / 1000)))\n df = df.withColumn(\"timestamp\",get_timestamp(col(\"ts\")))\n \n # create datetime column from original timestamp column\n get_datetime = udf(lambda x: str(datetime.fromtimestamp(int(x) / 1000.0)))\n df = df.withColumn(\"datetime\", get_datetime(col(\"ts\")))\n \n # extract columns to create time table\n time_table = df.select(\n 'timestamp',\n hour('datetime').alias('hour'),\n dayofmonth('datetime').alias('day'),\n weekofyear('datetime').alias('week'),\n month('datetime').alias('month'),\n year('datetime').alias('year'),\n date_format('datetime', 'F').alias('weekday')\n )\n \n # write time table to parquet files partitioned by year and month\n time_table.write.mode(\"overwrite\").partitionBy(\"year\",\"month\").parquet(output_data+\"time\")\n\n # read in song data to use for songplays table\n song_data = input_data + \"song_data/*/*/*/*.json\"\n song_df = spark.read.json(song_data)\n\n # extract columns from joined song and log datasets to create songplays table \n tsFormat = \"yyyy/MM/dd HH:MM:ss z\"\n songplays_table = song_df.join(df,song_df.artist_name==df.artist).withColumn(\"songplay_id\", monotonically_increasing_id()).withColumn('start_time', to_timestamp(date_format((col(\"ts\") /1000).cast(dataType=TimestampType()), tsFormat),tsFormat)).select(\"songplay_id\",\"start_time\",col(\"userId\").alias(\"user_id\"),\"level\",\"song_id\",\"artist_id\",col(\"sessionId\").alias(\"session_id\"),col(\"artist_location\").alias(\"location\"),\"userAgent\",month(col(\"start_time\")).alias(\"month\"),year(col(\"start_time\")).alias(\"year\"))\n\n\n # write songplays table to parquet files partitioned by year and month\n songplays_table.write.mode(\"overwrite\").partitionBy(\"year\",\"month\").parquet(output_data+\"songplays\")\n\n\ndef main():\n \"\"\"This is the main function that will create the spark session and create the dataframes that will be written in parquet in S3.\"\"\"\n spark = create_spark_session()\n input_data = \"s3a://udacity-dend/\"\n output_data = \"\"\n \n process_song_data(spark, input_data, output_data) \n process_log_data(spark, input_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"31596987","text":"################### 1 ##################\n\ndef grade0():\n\ta=input('백분위 점수: ')\n\twhile not(a.isdigit() and 0<=int(a)<=100):\n\t\ta=input('백분위 점수: ')\n\n\n\ta=int(a)\n\n\tif 0<=a<60:\n\t\tprint('학점: F')\n\n\telif 60<=a<70:\n\t\tprint('학점: D')\n\n\telif 70<=a<80:\n\t\tprint('학점: C')\n\n\telif 80<=a<90:\n\t\tprint('학점: B')\n\n\telif 90<=a<=100:\n\t\tprint('학점: A')\n\n\tprint('1-가 프로그램 안녕')\n\n\ndef grade1():\n\twhile True:\n\n\t\ta=input('백분위 점수: ')\n\t\twhile not(a.isdigit() and 0<=int(a)<=100):\n\t\t\ta=input('백분위 점수: ')\n\n\n\t\ta=int(a)\n\n\t\tif 0<=a<60:\n\t\t\tprint('학점: F')\n\n\t\telif 60<=a<70:\n\t\t\tprint('학점: D')\n\n\t\telif 70<=a<80:\n\t\t\tprint('학점: C')\n\n\t\telif 80<=a<90:\n\t\t\tprint('학점: B')\n\n\t\telif 90<=a<=100:\n\t\t\tprint('학점: A')\n\n\n\n\t\tagain=input('더할래?(y/n)')\n\t\twhile not (again=='y' or again=='n'):\n\t\t\tagain=input('더할래?(y/n)')\n\n\t\tif again=='n':\n\t\t\tbreak\n\n\tprint('1-나 프로그램 안녕')\n\n\n################## 2 ############################\n\ndef bigger(a,b):\n\tif a>b:\n\t\treturn a\n\telse:\n\t\treturn b\n\n\ndef biggest(a,b,c):\n\treturn bigger(bigger(a,b),c)\n\n\ndef median(a,b,c):\n\tk=[a,b,c]\n\tk.remove(biggest(a,b,c))\n\treturn bigger(k[0],k[1])\n\n################### 3 ################################\n\ndef fac0(n):\n\tif n>1:\n\t\treturn n*fac0(n-1)\n\telse:\n\t\treturn 1\n\n\n\ndef fac1(n):\n\tdef loop(n,k):\n\t\tif n>1:\n\t\t\treturn loop(n-1,k*n)\n\t\telse:\n\t\t\treturn k\n\treturn loop(n,1)\n\n\n\ndef fac(n):\n\tk=1\n\twhile n>1:\n\t\tk=k*n\n\t\tn=n-1\n\treturn k\n\ndef facfor(n):\n\tk=1\n\tfor i in range(n):\n\t\tk=k*(i+1)\n\treturn k\n\n###################### 4 #####################\n\n\ndef take0(n,s):\n\tif n>0 and s!=0:\n\t\treturn [s[0]]+take0(n-1,s[1:])\n\telse:\n\t\treturn []\n\n\ndef take1(n,s):\n\tdef loop(n,s,k):\n\t\tif n>0 and s!=0:\n\t\t\treturn loop(n-1,s[1:],k+[s[0]])\n\t\telse:\n\t\t\treturn k\n\treturn loop(n,s,[])\n\ndef take(n,s):\n\tk=[]\n\twhile n>0 and s!=0:\n\t\tk=k+[s[0]]\n\t\ts=s[1:]\n\t\tn=n-1\n\treturn k\n\n####################### 5 #######################\n\n##### 가\n\ndef length(s):\n\ta=0\n\twhile s!=[]:\n\t\ta=a+1\n\t\ts=s[1:]\n\n\treturn a\n\n\ndef length0(s):\n\tif s!=[]:\n\t\treturn 1+length0(s[1:])\n\telse:\n\t\treturn 0\n\ndef length1(s):\n\tdef loop(s,n):\n\t\tif s!=[]:\n\t\t\treturn loop(s[1:],n+1)\n\t\telse:\n\t\t\treturn n\n\n\treturn loop(s,0)\n\n##### 나\n\ndef member(x,s):\n\ta=False\n\twhile s!=[]:\n\n\t\tif s[0]==x:\n\t\t\ta=True\n\t\t\tbreak;\n\n\t\ts=s[1:]\n\n\treturn a\n\n\n\ndef member0(x,s):\n\tif s!=[]:\n\t\tif x==s[0]:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn member0(x,s[1:])\n\n\treturn False\n\n\n\n\n##### 다\n\ndef count(x,s):\n\ta=0\n\twhile s!=[]:\n\t\tif x==s[0]:\n\t\t\ta=a+1\n\t\ts=s[1:]\n\n\treturn a\n\n\ndef count0(x,s):\n\tif s!=[]:\n\t\tif x==s[0]:\n\t\t\treturn 1+count0(x,s[1:])\n\t\telse:\n\t\t\treturn count0(x,s[1:])\n\n\telse:\n\t\treturn 0\n\ndef count1(x,s):\n\tdef loop(x,s,n):\n\n\t\tif s!=[]:\n\t\t\tif x==s[0]:\n\t\t\t\treturn loop(x,s[1:],n+1)\n\t\t\telse:\n\t\t\t\treturn loop(x,s[1:],n)\n\t\treturn n\n\n\treturn loop(x,s,0)\n\n##### 라\n\ndef remove_one(x,s):\n\ta=[]\n\twhile x!=s[0]:\n\t\ta=a+[s[0]]\n\t\ts=s[1:]\n\n\treturn a+s[1:]\n\n\ndef remove_one0(x,s):\n\n\tif x!=s[0]:\n\t\treturn [s[0]]+remove_one0(x,s[1:])\n\n\telse:\n\t\treturn s[1:]\n\n\ndef remove_one1(x,s):\n\tdef loop(x,s,front):\n\t\tif x!=s[0]:\n\t\t\treturn loop(x,s[1:],front+[s[0]])\n\n\t\telse:\n\t\t\treturn front+s[1:]\n\n\n\n\treturn loop(x,s,[])\n\n\n##### 마\n\n\ndef remove_all(x,s):\n\ta=[]\n\twhile s!=[]:\n\t\tif x!=s[0]:\n\t\t\ta=a+[s[0]]\n\t\ts=s[1:]\n\n\treturn a\n\n\ndef remove_all0(x,s):\n\ta=[]\n\tif s!=[]:\n\t\tif x!=s[0]:\n\t\t\treturn [s[0]]+remove_all0(x,s[1:])\n\n\t\telse:\n\t\t\treturn remove_all0(x,s[1:])\n\n\telse:\n\n\t\treturn []\n\n\n\ndef remove_all1(x,s):\n\tdef loop(x,s,n):\n\t\tif s!=[]:\n\t\t\tif x!=s[0]:\n\t\t\t\treturn loop(x,s[1:],n+[s[0]])\n\t\t\telse:\n\t\t\t\treturn loop(x,s[1:],n)\n\t\telse:\n\t\t\treturn n\n\n\treturn loop(x,s,[])\n\n\n\n\n\n\n################### 6 ######################\n\n\ndef union(xs,ys):\n\tfor i in xs:\n\t\tys=remove_all(i,ys)\n\treturn xs+ys\n\n\ndef intersection(xs,ys):\n\tfor i in xs:\n\t\tif not member0(i,ys):\n\t\t\txs=remove_one(i,xs)\n\n\tfor i in ys:\n\t\tif not member0(i,xs):\n\t\t\tys=remove_one(i,ys)\n\n\treturn ys\n\ndef difference(xs,ys):\n\tfor i in xs:\n\t\tif member0(i,ys):\n\t\t\txs=remove_one(i,xs)\n\treturn xs\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2학기 프로그래밍기초/HomeWorks/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"497443846","text":"from MarcovModel import MarcovModel\nimport spacy\nimport sys\nimport random\n\n'''\nExperimentation with our updated model!\n'''\n\n# Sue, Yemi, Nicole\ndef component3a():\n print(\"-----working on component3a (Check 'results' folder)-----\")\n f = open(\"results/component3a.txt\", \"a\")\n\n # Load the standard English model suite\n nlp = spacy.load(\"en_core_web_sm\")\n # Update the model suite to allow for a long corpus\n nlp.max_length = sys.maxsize\n\n # Prepare a corpus\n corpus = open(\"chatbot/language.txt\").read().split(\"\\n\")\n\n length = len(corpus)\n sentences = [corpus[random.randint(0, length - 1)], corpus[random.randint(0, length - 1)], corpus[random.randint(0, length - 1)]]\n\n # POS-tag the corpus\n for i, sentence in enumerate(sentences):\n f.write(f\"-----Sentence {i} of Chat_Bot/language.txt-----\\n\")\n with nlp.select_pipes(enable=[\"tok2vec\", \"tagger\"]):\n tagged_tokens = nlp(sentence)\n # Print out the tagged tokens\n for token in tagged_tokens:\n f.write(f\"{token}/{token.tag_}\\n\") \n \n # Prepare a corpus\n corpus2 = open(\"corpora/donald_trump_collected_tweets.txt\").read().split(\"\\n\")\n\n length = len(corpus2)\n sentences = [corpus2[random.randint(0, length - 1)], corpus2[random.randint(0, length - 1)], corpus2[random.randint(0, length - 1)]]\n \n # POS-tag the corpus\n for i, sentence in enumerate(sentences):\n f.write(f\"-----Sentence {i} of Donald Trump-----\\n\")\n with nlp.select_pipes(enable=[\"tok2vec\", \"tagger\"]):\n tagged_tokens = nlp(sentence)\n # Print out the tagged tokens\n for token in tagged_tokens:\n f.write(f\"{token}/{token.tag_}\\n\") \n\n# Sue, Yemi\ndef component3b():\n print(\"-----working on component3b (Check 'results' folder)-----\")\n f = open(\"results/component3b.txt\", \"a\")\n f.write(\"\\n-----POS ENGAGED-----\\n\\n\")\n for order in range(1,8):\n model = MarcovModel(\"alexander_dumas_collected_works.txt\", level = \"word\", order = order, pos = True)\n f.write(f\"-----Results for {model.corpus_filename}, Order: {order} -----\\n\")\n f.write(model.generate(30) + \"\\n\")\n\n# Sue, Yemi\ndef component3c():\n print(\"-----working on component3c (Check 'results' folder)-----\")\n f = open(\"results/component3c.txt\", \"a\")\n f.write(\"-----without the POS-----\")\n model = MarcovModel(\"alexander_dumas_collected_works.txt\", level = \"word\", order = 5, pos = False)\n f.write(model.generate(30) + \"\\n\")\n f.write(\"-----with the POS-----\")\n model2 = MarcovModel(\"alexander_dumas_collected_works.txt\", level = \"word\", order = 5, pos = True)\n f.write(model2.generate(30) + \"\\n\")\n\ndef component3():\n #component3a()\n #component3b()\n component3c()\n\nif __name__ == \"__main__\":\n component3()","sub_path":"component3.py","file_name":"component3.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"646055218","text":"import random\n\n#1:4, 2:6, 3:6.7, 4:8, 5:8.8, bypass:4\navg_entry_num = [0,4,6,6.7,8,8.8]\navg_server_num = [0,1,1.5,2,2.5,3]\nentry_mapping = [0, 4, 8, 8, 12, 12]\n\nU_table = [[0 for x in range(5)] for x in range(100000)]\n\ndef mapping(SC):\n\ts = random.randint(1,len(SC))\n\treturn entry_mapping[s]\n\ndef U_table_init(user_num):\n\tlines = open('test.txt').read().splitlines()\n\tfor i in range(user_num):\n\t\td = lines[i].split()\n\t\tU_table[i][0]=d[0] #ip\n\t\tU_table[i][1]=int(d[1]) #Bw\n\t\tU_table[i][2]=d[2] #SLA\n\t\tU_table[i][3]=int(d[3]) \t #Edge\n\t\tU_table[i][4]=d[4] #SC\n\ndef gen_flows(user_num, flow_num):\n\tlines = open('mec_user_3edge.txt').read().splitlines()\n\tlines2 = []\n\tflows = []\n\tfor i in range(user_num):\n\t\tlines2.append(lines[i])\n\tfor i in range(flow_num):\n\t\trand_line = random.choice(lines2)\n\t\td=rand_line.split()\n\t\tflows.append([d[0], int(d[1]), d[2], int(d[3]), d[4]])\n\treturn flows\n\n\n#tmp \ndef gen_flows1(user_num, flow_num):\n\tlines = open('test.txt').read().splitlines()\n\tlines2 = []\n\tflows = []\n\tfor i in range(user_num):\n\t\tlines2.append(lines[i])\n\tfor i in lines2:\n\t\td=i.split()\n\t\tflows.append([d[0], int(d[1]), d[2], int(d[3]), d[4]])\n\treturn flows\n\ndef gen_flows2(user_num, flow_num):\n\tlines = open('mec_user_3edge.txt').read().splitlines()\n\tlines2 = []\n\tflows = []\n\tfor i in range(user_num):\n\t\tlines2.append(lines[i])\n\tfor i in lines2:\n\t\td=i.split()\n\t\tflows.append([d[0], int(d[1]), d[2], int(d[3]), d[4]])\n\treturn flows\n\n\n\ndef split_SC(SC):\n\ti = 0\n\twhile i < len(SC) and SC[i] <= 'B':\n\t\ti += 1\n\tif i == len(SC):\n\t\treturn [SC, '*']\n\telif i == 0:\n\t\treturn ['*', SC]\n\telse:\n\t\treturn [SC[0:i],SC[i:len(SC)]]\n\n","sub_path":"Flow_entry/flow_entry_mapping.py","file_name":"flow_entry_mapping.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"320783262","text":"# -*- coding: utf-8 -*-\n\nfrom functools import wraps\nfrom spcache.utils import CacheWrapper, make_key\nimport logging; logger = logging.getLogger(__name__)\n\n\ndef cached(trigger, suffix=None, base_name=None, \n store_keys=False, timeout=600, uniq_id=None, \n base_name_keylist=None, dg=False):\n \"\"\"\n cached\n @kwparam trigger: trigger\n @kwparam suffix: suffix\n @kwparam base_name: base_name\n @kwparam store_keys: store_keys\n @kwparam timeout: timeout\n @kwparam uniq_id: uniq_id\n @kwparam base_name_keylist: base_name_keylist\n @kwparam dg: dg\n @return: wrapper\n \"\"\"\n def wrapper(func):\n \"\"\"\n wrapper\n @kwparam func: func\n @return: CacheWrapper\n \"\"\"\n if base_name == None:\n real_base_name = func.__module__ + \".\" + func.__name__\n else:\n real_base_name = base_name\n return CacheWrapper(func, trigger, suffix, real_base_name, \n store_keys, timeout, uniq_id, \n base_name_keylist, dg)\n return wrapper\n\n\ndef spmemoize(cache, key_func=None, num_args=1):\n \"\"\"\n Кэширование непосредственно в процессе\n @kwparam cache: cache\n @kwparam key_func: key_func\n @kwparam num_args: num_args\n @return: decorator\n \"\"\"\n def decorator(func):\n \"\"\"\n decorator\n @kwparam func: func\n @return: wrapper\n \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n \"\"\"\n wrapper\n @kwparam *args: args\n @kwparam **kwargs: kwrags\n @return: result\n \"\"\"\n key = key_func(*args, **kwargs) if key_func \\\n and callable(key_func) else args[:num_args]\n key = make_key(key)\n if key in cache:\n return cache[key]\n result = func(*args, **kwargs)\n cache[key] = result\n return result\n return wrapper \n return decorator\n\n","sub_path":"apps/spcache/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"270435212","text":"import socket\r\nimport sys\r\nimport time\r\nimport os\r\nfrom os import path\r\nimport collections\r\nimport pickle\r\n\r\nfrom threading import Thread\r\nfrom socketserver import ThreadingMixIn\r\nfrom divideFile import divideFile\r\n\r\nnum_peer=0\r\npeer_list=[]\r\nmyIp='0.0.0.0'\r\ntrack_ip = '192.168.43.131'\r\nmyPort=4322\r\ntracker_port = 4321\r\ndef notify_tracker():\r\n\ts_tracker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\ts_tracker.connect((track_ip, 4320))\r\n\tmsg = 'Hello'\r\n\tdata = pickle.dumps(msg)\r\n\ts_tracker.send(data)\r\n\ts_tracker.close()\r\n\tprint(\"Im in!\")\r\n\r\n\r\ndef tracker_connect():\r\n\ts_tracker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\ts_tracker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\ts_tracker.bind((myIp, tracker_port))\r\n\tprint(\"Listening to tracker...\")\r\n\twhile(True):\r\n\t\ts_tracker.listen(5)\r\n\t\t(conn, (ip,port)) = s_tracker.accept()\r\n\t\tdata = conn.recv(1024)\r\n\t\t#################################\r\n\t\tnew_list=pickle.loads(data)\r\n\t\tnew_list=set(new_list)-set(peer_list)\r\n\t\tpeer_list.extend(list(new_list))\r\n\t\t#################################\r\n\t\tprint(peer_list)\r\n\t\tnum_peer=len(peer_list)\r\n\r\n\r\ndef listenPeers():\r\n\ttcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\ttcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\ttcpsock.bind((myIp, myPort))\r\n\tprint(\"Listening to peers...\")\r\n\r\n\tif not os.path.exists('Backup_Store'):\r\n\t\tos.mkdir('Backup_Store')\r\n\twhile(True):\r\n\t\ttcpsock.listen(5)\r\n\t\t(conn, (ip,port)) = tcpsock.accept()\r\n\t\tdata1=conn.recv(8)\r\n\t\tdata1=str(data1, 'utf-8')\r\n\t\tif '#' in data1:\r\n\t\t\tdata2=data1.split(\"#\", 1)[0]\r\n\t\t\tnumrep=int(data1.split(\"#\",1)[1])\r\n\t\t\tif (data2=='Backup'):\r\n\t\t\t\twhile(numrep):\r\n\t\t\t\t\tif not os.path.exists('Backup_Store/'+ip):\r\n\t\t\t\t\t\tos.mkdir('Backup_Store/'+ip)\r\n\t\t\t\t\tdata=conn.recv(1024)\r\n\t\t\t\t\tdata=str(data, 'utf-8')\r\n\t\t\t\t\tfileName=data.split(\"#\", 2)[0]\r\n\t\t\t\t\tfileWoutExt=fileName.split(\".\", 1)[0]\r\n\t\t\t\t\tExt=fileName.split(\".\", 1)[1]\r\n\t\t\t\t\tchunkId=data.split(\"#\", 2)[1]\r\n\t\t\t\t\tchunkData=data.split(\"#\", 2)[2]\r\n\t\t\t\t\tFinalFileName=fileWoutExt+\"_\"+chunkId+\".\"+Ext\r\n\t\t\t\t\tdataprint = [chunkData]\r\n\t\t\t\t\tprint(\"\\nReceived backup chunk \", str(dataprint), \" of file \",fileName,\" from IP \", ip)\r\n\t\t\t\t\tprint(\"Chunk stored in Backup_Store/\"+ip+\"/\"+FinalFileName,\"\\n\")\r\n\t\t\t\t\twriteData=chunkData.split(\"/n\")\r\n\r\n\t\t\t\t\twith open('Backup_Store/'+ip+'/'+FinalFileName, \"w\") as f1:\r\n\t\t\t\t\t\tfor item in writeData:\r\n\t\t\t\t\t\t\tf1.write(\"%s\" %item)\r\n\t\t\t\t\tf1.close()\r\n\t\t\t\t\tnumrep-=1\r\n\r\n\t\telif(data1=='Retrieve'):\r\n\t\t\tfileName=conn.recv(1024)\r\n\t\t\tf=open(\"Backup_Store/\"+ip+'/'+str(fileName, 'utf-8'), \"r\")\r\n\t\t\tdata=f.read()\r\n\t\t\tdataprint = [data]\r\n\t\t\tprint(\"Sending backed up chunk data \", str(dataprint), \" to IP \", ip)\r\n\t\t\tconn.send(bytes(data, 'utf-8'))\r\n\t\tconn.close()\r\n\t\tprint('\\nMenu:\\n')\r\n\t\tprint('1. Backup\\n')\r\n\t\tprint('2. Retrieve\\n')\r\n\t\tprint(\"List your choice: \")\r\n\r\n\r\ndef connect_peer(ip,port):\r\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\ttry:\r\n\t\ts.connect((ip, port))\r\n\texcept Exception as e:\r\n\t\tprint(\"Exception is \", e)\r\n\t\treturn False\r\n\treturn s,ip, port\r\n\r\n\r\ndef backup(socks,chunks, fileName,repeat):\r\n \t#chunks=chunk_list socket_list= socket, ip, port\r\n\tcount=0\r\n\tn = 0\r\n\tflag = {}\r\n\tcnt_rep = 0\r\n\tfor sock in socks:\r\n\t\tflag[sock] = 0\r\n\twhile n<repeat:\r\n\t\tfor sock in socks:\r\n\t\t\tcnt_rep+=1\r\n\t\t\tif flag[sock] == 0 :\r\n\t\t\t\tbackup=bytes('Backup#'+str(repeat),'utf-8')\r\n\t\t\t\tsock[0].send(backup)\r\n\t\t\t\tflag[sock] = 1\r\n\t\t\t#time.sleep(1)\r\n\t\t\tchunk_id=count\r\n\t\t\tchunk = chunks[count]\r\n\t\t\tchunkprint = [chunk]\r\n\t\t\tprint(\"Chunk \" +str(chunkprint)+ \" being sent to IP \"+sock[1])\r\n\t\t\tchunk=fileName+\"#\"+str(chunk_id)+\"#\"+chunk\r\n\t\t\tmydata.append(tuple((fileName,chunk_id,sock[1],sock[2])))\r\n\t\t\tnewThread=sendFile(fileName, chunk, sock)\r\n\t\t\tnewThread.start()\r\n\t\t\tthreads.append(newThread)\r\n\t\t\tif(cnt_rep==repeat):\r\n\t\t\t\tcount+=1\r\n\t\t\t\tcnt_rep = 0\r\n\t\tn+=1\r\n\r\n\r\nclass sendFile(Thread):\r\n def __init__(self,fileName, chunk,socks):\r\n Thread.__init__(self)\r\n self.ip = socks[1]\r\n self.port = socks[2]\r\n self.sock = socks[0]\r\n self.fileName=fileName\r\n self.chunk=chunk\r\n\r\n\r\n def run(self):\r\n \t#backup=bytes('Backup','utf-8')\r\n \t#self.sock.send(backup)\r\n \tdata=bytes(self.chunk,'utf-8')\r\n \tself.sock.send(data)\r\n\r\n\r\ndef retrieveFile(fileName):\r\n fileMetadata=[]\r\n for data in mydata:\r\n if (data[0]==fileName):\r\n fileMetadata.append(tuple((data[0],data[2], data[3], data[1]))) # fileName,ip, port, chunk_id\r\n return fileMetadata\r\n\r\n\r\nclass getChunk(Thread):\r\n\tdef __init__(self, ip, port, chunkId,fileName):\r\n\t\tThread.__init__(self)\r\n\t\tself.ip = ip\r\n\t\tself.port = port\r\n\t\tself.chunkId=chunkId\r\n\t\tself.fileName=fileName\r\n\t\tself.ext=fileName.split('.', 1)[1]\r\n\t\tself.chunk_file=fileName.split('.', 1)[0]+\"_\"+str(chunkId)+\".\"+self.ext\r\n\r\n\r\n\tdef run(self):\r\n\t\ts_getChunk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\ts_getChunk.settimeout(2)\r\n\t\ttry:\r\n\t\t\ts_getChunk.connect((self.ip, self.port))\r\n\t\texcept Exception as e:\r\n\t\t\tconnectionFails.append(self.ip)\r\n\t\t\tprint(\"Exception \", e)\r\n\t\t\tprint(e)\r\n\t\t\treturn\r\n\t\ts_getChunk.settimeout(None)\r\n\t\ts_getChunk.send(bytes('Retrieve', 'utf-8'))\r\n\t\t#time.sleep(1)\r\n\t\ts_getChunk.send(bytes(self.chunk_file, 'utf-8'))\r\n\t\tdata_i_got = s_getChunk.recv(1024)\r\n\t\tdata_i_got = str(data_i_got, 'utf-8')\r\n\t\tchunkprint = [data_i_got]\r\n\t\tprint(\"Chunk \" + str(chunkprint)+ \" retrieved from IP - \"+self.ip)\r\n\t\tdata_retrieved.update({self.chunkId : data_i_got})\r\n\r\n\r\ndef getFile(fileMetadata):\r\n\tfor data in fileMetadata:\r\n\t\tip=data[1]\r\n\t\tport=data[2]\r\n\t\tchunkId=data[3]\r\n\t\tfileName=data[0]\r\n\t\tif chunkId not in data_retrieved.keys():\r\n\t\t\tif ip not in connectionFails:\r\n\t\t\t\tnewThread=getChunk(ip, port, chunkId, fileName)\r\n\t\t\t\tnewThread.start()\r\n\t\t\t\tnewThread.join()\r\n\t\t\t\trThreads.append(newThread)\r\n\r\n\r\nthreads=[]\r\nrThreads=[]\r\nlthreads=[]\r\ndata_retrieved={}\r\nconnectionFails=[]\r\n\r\nnotify_tracker()\r\n#tracker ip and port\r\n\r\nmydata=[]\r\nth_track=Thread(target=tracker_connect)\r\nth_track.start()\r\n\r\nth_listen=Thread(target=listenPeers)\r\nth_listen.start()\r\n\r\n\r\nwhile(True):\r\n\tprint('\\nMenu:\\n')\r\n\tprint('1. Backup\\n')\r\n\tprint('2. Retrieve\\n')\r\n\tchoice=input(\"List your choice: \")\r\n\tif(choice=='1'):\r\n\t\tnum_peer_instant=len(peer_list)\r\n\t\tsockets_list=[]\r\n\t\tfile_name=input(\"Enter the filename: \")\r\n\t\tif not(os.path.isfile(file_name)):\r\n\t\t\tprint(\"File does not exist.\")\r\n\t\t\tcontinue\r\n\t\tprint('\\nSub-Menu:\\n')\r\n\t\tprint('1, High Priority File (3 copies will be created)\\n')\r\n\t\tprint('2. Low Priority File (2 copies will be created)\\n')\r\n\r\n\t\tchoice1=input(\"List your choice: \")\r\n\t\tif(choice1=='1'):\r\n\t\t\tn=3\r\n\t\t\tprint(\"Backing up 3 copies\")\r\n\t\telse:\r\n\t\t\tn=2\r\n\t\t\tprint(\"Backing up 2 copies\")\r\n\r\n\t\tprint(peer_list)\r\n\t\tfor i in range(0, len(peer_list)):\r\n\t\t\tip=peer_list[i][0]\t\t#getting ip and port of peer\r\n\t\t\tport=int(peer_list[i][1])\r\n\t\t\tconn=connect_peer(ip, port)\r\n\t\t\tif(conn!=False):\r\n\t\t\t\tsockets_list.append(conn)\r\n\t\tconnections=len(sockets_list)\r\n\r\n\t\tif connections ==0:\r\n\t\t\tprint(\"No peers connected - Try later!!\")\r\n\t\t\tcontinue\r\n\r\n\t\tchunk_list=divideFile(file_name,connections)\r\n\t\tprint(\"Chunks created :\", chunk_list)\r\n\t\tprint(\"# of Conections: \", connections)\r\n\t\tbackup(sockets_list,chunk_list,file_name,n)\r\n\r\n\telif(choice=='2'):\r\n #data_retrieved = {}\r\n\t\tfileName=input(\"Enter the file name: \")\r\n\t\tflag=0\r\n\t\tfor data in mydata:\r\n\t\t\tif(fileName==data[0]):\r\n\t\t\t\tflag=1\r\n\t\tif(flag==0):\r\n\t\t\tprint(\"Error!!! File not backed up\")\r\n\t\t\tcontinue\r\n\t\tfileMetadata=retrieveFile(fileName)\r\n\t\tgetFile(fileMetadata)\r\n\t\tz=[]\r\n\t\tod=collections.OrderedDict(sorted(data_retrieved.items()))\r\n\t\tfor k, v in od.items():\r\n\t\t\tz.append(v)\r\n\t\tf=open(\"new\"+fileName, \"w\")\r\n\t\tfor data1 in z:\r\n\t\t\tf.write(\"%s\" %data1)\r\n\t\tf.close()\r\n\t\tprint(\"Final File retrieved - \", z)\r\n","sub_path":"src/Peer3/peer.py","file_name":"peer.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"411283968","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom layers import *\nfrom data import mobilenet_carplate, change_cfg_for_ssd512_mobilenet\nimport os\nfrom mobilenet import MobileNetV1\n\n\nclass SSD_mobilenet(nn.Module):\n \"\"\"Single Shot Multibox Architecture\n The network is composed of a base VGG network followed by the\n added multibox conv layers. Each multibox layer branches into\n 1) conv2d for class conf scores\n 2) conv2d for localization predictions\n 3) associated priorbox layer to produce default bounding\n boxes specific to the layer's feature map size.\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n\n Args:\n phase: (string) Can be \"test\" or \"train\"\n size: input image size\n base: VGG16 layers for input, size of either 300 or 500\n extras: extra layers that feed to multibox loc and conf layers\n head: \"multibox head\" consists of loc and conf conv layers\n \"\"\"\n\n def __init__(self, phase, size, base_net, extras, head, num_classes, head_type):\n super(SSD_mobilenet, self).__init__()\n self.head_type = head_type\n if self.head_type not in ['BB', 'BB+FV', 'FV']:\n assert Exception(\"head type must be BB, BB+FV, or FV\")\n self.phase = phase\n self.num_classes = num_classes\n self.cfg = mobilenet_carplate\n if size == 512:\n self.cfg = change_cfg_for_ssd512_mobilenet(self.cfg)\n self.priorbox = PriorBox(self.cfg)\n with torch.no_grad():\n self.priors = Variable(self.priorbox.forward())\n self.size = size\n\n # SSD network\n self.base_net = nn.ModuleList(base_net)\n self.extras = nn.ModuleList(extras)\n\n self.conf = nn.ModuleList(head[0])\n if self.head_type == 'BB':\n self.loc = nn.ModuleList(head[1])\n elif self.head_type == 'BB+FV':\n self.loc = nn.ModuleList(head[1])\n self.four_corners = nn.ModuleList(head[2])\n else:\n self.four_corners = nn.ModuleList(head[1])\n\n if phase == 'test':\n self.softmax = nn.Softmax(dim=-1)\n if self.head_type == 'BB':\n self.detect = Detect()\n elif self.head_type == 'BB+FV':\n self.detect = Detect_four_corners()\n else:\n self.detect = Detect_only_four_corners()\n \n\n def forward(self, x):\n \"\"\"Applies network layers and ops on input image(s) x.\n\n Args:\n x: input image or batch of images. Shape: [batch,3,300,300].\n\n Return:\n Depending on phase:\n test:\n Variable(tensor) of output class label predictions,\n confidence score, and corresponding location predictions for\n each object detected. Shape: [batch,topk,7]\n\n train:\n list of concat outputs from:\n 1: confidence layers, Shape: [batch*num_priors,num_classes]\n 2: localization layers, Shape: [batch,num_priors*4]\n 3: priorbox layers, Shape: [2,num_priors*4]\n \"\"\"\n sources = list()\n conf = list()\n if self.head_type == 'BB':\n loc = list()\n elif self.head_type == 'BB+FV':\n loc = list()\n four_corners = list()\n else:\n four_corners = list()\n\n # conv-bw10\n for k in range(11):\n x = self.base_net[k](x)\n sources.append(x)\n\n # conv-bw12\n for k in range(11, len(self.base_net)):\n x = self.base_net[k](x)\n sources.append(x)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n x = v(x)\n sources.append(x)\n\n # apply multibox head to source layers\n if self.head_type == 'BB':\n for (x, l, c) in zip(sources, self.loc, self.conf):\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n elif self.head_type == 'BB+FV':\n for (x, l, c, f) in zip(sources, self.loc, self.conf, self.four_corners):\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n four_corners.append(f(x).permute(0, 2, 3, 1).contiguous())\n else:\n for (x, c, f) in zip(sources, self.conf, self.four_corners):\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n four_corners.append(f(x).permute(0, 2, 3, 1).contiguous())\n\n if self.head_type == 'BB':\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n elif self.head_type == 'BB+FV':\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n four_corners = torch.cat([o.view(o.size(0), -1) for o in four_corners], 1)\n else:\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n four_corners = torch.cat([o.view(o.size(0), -1) for o in four_corners], 1)\n if self.phase == \"test\":\n if self.head_type == 'BB':\n output = self.detect.apply(self.num_classes, 0, 200, 0.01, 0.45,\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(conf.size(0), -1,\n self.num_classes)), # conf preds\n self.priors.type(type(x.data)) # default boxes\n )\n elif self.head_type == 'BB+FV':\n output = self.detect.apply(self.num_classes, 0, 200, 0.01, 0.45,\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(conf.size(0), -1,\n self.num_classes)), # conf preds\n self.priors.type(type(x.data)), # default boxes\n four_corners.view(four_corners.size(0), -1, 8)\n )\n else:\n output = self.detect.apply(self.num_classes, 0, 200, 0.01, 0.45,\n self.softmax(conf.view(conf.size(0), -1,\n self.num_classes)), # conf preds\n self.priors.type(type(x.data)), # default boxes\n four_corners.view(four_corners.size(0), -1, 8)\n )\n else:\n if self.head_type == 'BB':\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n self.priors\n )\n elif self.head_type == 'BB+FV':\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n self.priors,\n four_corners.view(four_corners.size(0), -1, 8)\n )\n else:\n output = (\n conf.view(conf.size(0), -1, self.num_classes),\n self.priors,\n four_corners.view(four_corners.size(0), -1, 8)\n )\n return output\n\n def load_weights(self, base_file):\n other, ext = os.path.splitext(base_file)\n if ext == '.pkl' or '.pth':\n print('Loading weights into state dict...')\n self.load_state_dict(torch.load(base_file,\n map_location=lambda storage, loc: storage))\n print('Finished!')\n else:\n print('Sorry only .pth and .pkl files supported.')\n\n\ndef multibox(base_net, extra_layers, cfg, num_classes, head_type='BB'):\n conf_layers = []\n if head_type == 'BB':\n loc_layers = []\n elif head_type == 'BB+FV':\n loc_layers = []\n four_corners_layers = []\n else:\n four_corners_layers = []\n base_net_source = [-3, -1]\n extras_source = [0, 1, 2, 3]\n for k, v in enumerate(base_net_source):\n conf_layers += [nn.Conv2d(base_net[v][3].out_channels,\n cfg[k] * num_classes, kernel_size=3, padding=1)]\n if head_type == 'BB':\n loc_layers += [nn.Conv2d(base_net[v][3].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n elif head_type == 'BB+FV':\n loc_layers += [nn.Conv2d(base_net[v][3].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n four_corners_layers += [nn.Conv2d(base_net[v][3].out_channels,\n cfg[k] * 8, kernel_size=3, padding=1)]\n else:\n four_corners_layers += [nn.Conv2d(base_net[v][3].out_channels,\n cfg[k] * 8, kernel_size=3, padding=1)]\n for k, v in enumerate(extras_source, 2):\n conf_layers += [nn.Conv2d(extra_layers[v][2].out_channels,\n cfg[k] * num_classes, kernel_size=3, padding=1)]\n if head_type == 'BB':\n loc_layers += [nn.Conv2d(extra_layers[v][2].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n elif head_type == 'BB+FV':\n loc_layers += [nn.Conv2d(extra_layers[v][2].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n four_corners_layers += [nn.Conv2d(extra_layers[v][2].out_channels,\n cfg[k] * 8, kernel_size=3, padding=1)]\n else:\n four_corners_layers += [nn.Conv2d(extra_layers[v][2].out_channels,\n cfg[k] * 8, kernel_size=3, padding=1)]\n if head_type == 'BB':\n return base_net, extra_layers, (conf_layers, loc_layers)\n elif head_type == 'BB+FV':\n return base_net, extra_layers, (conf_layers, loc_layers, four_corners_layers)\n else:\n return base_net, extra_layers, (conf_layers, four_corners_layers)\n\nmbox = {\n '300': [6, 6, 6, 6, 6, 6],\n '512': [6, 6, 6, 6, 6, 6],\n}\n\n\ndef build_ssd(phase, size=300, num_classes=21, head_type='BB'):\n if phase != \"test\" and phase != \"train\":\n print(\"ERROR: Phase: \" + phase + \" not recognized\")\n return\n if size != 300 and size != 512:\n print(\"ERROR: You specified size \" + repr(size) + \". However, \" +\n \"currently only SSD300 SSD512 (size=300 or size=512) is supported!\")\n return\n \n base_net = MobileNetV1(1001).model\n extras = MobileNetV1(1001).extras\n base_, extras_, head_ = multibox(base_net, extras,\n mbox[str(size)], num_classes, head_type=head_type)\n return SSD_mobilenet(phase, size, base_, extras_, head_, num_classes, head_type)\n","sub_path":"ssd_mobilenet.py","file_name":"ssd_mobilenet.py","file_ext":"py","file_size_in_byte":10944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"411005702","text":"#log.py\n#coding=utf-8\n#Classe usada para escrever acessos, mensagens\nfrom datetime import datetime\n\nclass Log(object):\n\t__strlogfile = None\n\n\t#Guarda o caminho do arquivo para futuro uso\n\tdef __init__(self, logfile):\n\t\tself.__strlogfile = logfile\n\t\ttry:\n\t\t\twith open(self.__strlogfile, \"a+\") as log:\n\t\t\t\tstrbuffer = \"[log] [\" + str(datetime.now())[0:19] + \"] Inicializando o log '\" + self.__strlogfile + \"' . . .\\n\"\n\t\t\t\tlog.write(strbuffer)\n\t\t\t\tlog.close()\n\t\t\tprint(strbuffer, end=\"\")\n\t\texcept IOError as e:\n\t\t\traise Exception(\"Não foi possivel inicializar o Log.\")\n\n\t#Registra um comando no log\n\tdef write(self, command, strmsg):\n\t\twith open(self.__strlogfile, \"a+\") as log:\n\t\t\tstrbuffer = \"[log] [\" + str(datetime.now())[0:19] + \"] [\" + command + \"] \" + strmsg + \"\\n\"\n\t\t\tlog.write(strbuffer)\n\t\t\tlog.close()\n\t\tprint(strbuffer, end=\"\")\n\n\t#Registra uma mensagem no log\n\tdef write_message(self, username, strmsg, channel_name):\n\t\tif strmsg == \"\":\n\t\t\tstrmsg = \"<Vazio/envio de arquivo>\"\n\n\t\t#Lindando com Exceptions pois a mensagem pode conter carácteres inválidos\n\t\ttry:\n\t\t\twith open(self.__strlogfile, \"a+\") as log:\n\t\t\t\tstrbuffer = \"[log] [\" + str(datetime.now())[0:19] + \"] [\" + channel_name + \"] \" + username + \": \" + strmsg + \"\\n\"\n\t\t\t\tlog.write(strbuffer)\n\t\t\t\tlog.close()\n\t\t\tprint(strbuffer, end=\"\")\n\t\texcept Exception as e:\n\t\t\tself.write_exception(self.write_message.__name__, e)\n\n\t#Registra uma Exception no log\n\tdef write_exception(self, command, e):\n\t\twith open(self.__strlogfile, \"a+\") as log:\n\t\t\tstrbuffer = \"[log] [\" + str(datetime.now())[0:19] + \"] [Exception] [\" + command + \"] \" + str(e) + \"\\n\"\n\t\t\tlog.write(strbuffer)\n\t\t\tlog.close()\n\t\tprint(strbuffer, end=\"\")\n","sub_path":"util/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"535836690","text":"import math\n\nfrom rlbot.agents.base_agent import BaseAgent, SimpleControllerState\nfrom rlbot.utils.structures.game_data_struct import GameTickPacket\n\n\nclass PythonExample(BaseAgent):\n\n def initialize_agent(self):\n #This runs once before the bot starts up\n self.controller_state = SimpleControllerState()\n\n def get_output(self, packet: GameTickPacket) -> SimpleControllerState:\n ball_location = Vector2(packet.game_ball.physics.location.x, packet.game_ball.physics.location.y)\n\n my_car = packet.game_cars[self.index]\n car_location = Vector2(my_car.physics.location.x, my_car.physics.location.y)\n car_direction = get_car_facing_vector(my_car)\n car_to_ball = ball_location - car_location\n\n steer_correction_radians = car_direction.correction_to(car_to_ball)\n\n if steer_correction_radians > 0:\n # Positive radians in the unit circle is a turn to the left.\n turn = -1.0 # Negative value for a turn to the left.\n action_display = \"turn left\"\n else:\n turn = 1.0\n action_display = \"turn right\"\n\n self.controller_state.throttle = 1.0\n self.controller_state.steer = turn\n\n draw_debug(self.renderer, my_car, packet.game_ball, action_display)\n\n return self.controller_state\n\nclass Vector2:\n def __init__(self, x=0, y=0):\n self.x = float(x)\n self.y = float(y)\n\n def __add__(self, val):\n return Vector2(self.x + val.x, self.y + val.y)\n\n def __sub__(self, val):\n return Vector2(self.x - val.x, self.y - val.y)\n\n def correction_to(self, ideal):\n # The in-game axes are left handed, so use -x\n current_in_radians = math.atan2(self.y, -self.x)\n ideal_in_radians = math.atan2(ideal.y, -ideal.x)\n\n correction = ideal_in_radians - current_in_radians\n\n # Make sure we go the 'short way'\n if abs(correction) > math.pi:\n if correction < 0:\n correction += 2 * math.pi\n else:\n correction -= 2 * math.pi\n\n return correction\n\n\ndef get_car_facing_vector(car):\n pitch = float(car.physics.rotation.pitch)\n yaw = float(car.physics.rotation.yaw)\n\n facing_x = math.cos(pitch) * math.cos(yaw)\n facing_y = math.cos(pitch) * math.sin(yaw)\n\n return Vector2(facing_x, facing_y)\n\ndef draw_debug(renderer, car, ball, action_display):\n renderer.begin_rendering()\n # draw a line from the car to the ball\n renderer.draw_line_3d(car.physics.location, ball.physics.location, renderer.white())\n # print the action that the bot is taking\n renderer.draw_string_3d(car.physics.location, 2, 2, action_display, renderer.white())\n renderer.end_rendering()\n","sub_path":"python_example/python_example.py","file_name":"python_example.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"48527652","text":"'''На плоскости заданы координаты вершин треугольника и множество точек.\"\n\"\\nНайти такие окружности, которые проходят хотя бы через три различные точки множества\\n\"\n\"и для которых хотя бы одни из прямых, проходящих через сторону треугольника может быть касательной к окружности\\n\"\n\"Среди полученных окружностей найти такую,для которой площадь треугольника,\n образованного центрами треугольника и окружности\\n\"\n\"и точки касания максимальна.'''\n\nfrom math import *\nfrom tkinter import *\nfrom tkinter.filedialog import *\nimport copy\n\n'''\nmx = [0, 2, 4, 6, 8]\nmy = [2, 4, 2, 4, 2]\n\ntx = [-3, 4, 4]\nty = [4, 4, -5]\n'''\n# 575757 - light grey color\n\nmx =[]\nmy =[]\ntx =[]\nty =[]\n\ndef clear():\n mx.clear()\n my.clear()\n tx.clear()\n ty.clear()\n\n listbox1.delete(1, END)\n listbox2.delete(1, END)\n\n print(\"Очищено\\nTX = \", tx, \"\\nTY = \", ty, \"\\n\")\n print(\"Очищено\\nMX = \", mx, \"\\nMY = \", my, \"\\n\\n\")\n\ndef display_graphics_execution(circle_data, tx, ty, x_c, y_c,kas_data,line):\n root_txt = Tk()\n root_txt.minsize(width=500, height=600)\n root_txt.title('Ответ')\n\n canv = Canvas(root_txt, width=500, height=700, bg=\"#B2B0B0\")\n canv.config(scrollregion=canv.bbox(ALL))\n canv.config(bd=2)\n canv.create_text(10, 10, fill=\"darkblue\", font=\"Helvetica 14\", text=line, anchor=NW)\n\n canv.grid()\n\n\n c_x = 850\n c_y = 700\n\n scl = 40\n\n tr_x_dr = copy.deepcopy(tx)\n tr_y_dr = copy.deepcopy(ty)\n kas = copy.deepcopy(kas_data)\n\n kas[0] = kas[0] *scl + c_x*0.5\n kas[1] = kas[1]*(-1) *scl + c_y*0.5\n\n for i in range(len(tr_x_dr)):\n tr_x_dr[i], tr_y_dr[i] = tr_x_dr[i] * scl + c_x * 0.5, tr_y_dr[i]*(-1) * scl + c_y / 2\n\n circle_dr = copy.deepcopy(circle_data)\n\n circle_dr[0] = circle_dr[0] * scl + c_x * 0.5\n circle_dr[1] = circle_dr[1]*(-1) * scl + c_y / 2\n circle_dr[2] = circle_dr[2] * scl\n\n x_c = x_c *scl + c_x * 0.5\n y_c = y_c*(-1) *scl + c_y * 0.5\n\n root_gr = Tk()\n root_gr.title('GRAPHICS INTERPRETATION')\n root_gr.minsize(width=c_x, height=c_y)\n canv = Canvas(root_gr, width=c_x, height=c_y, bg=\"#B2B0B0\")\n #canv.config(bd=2)\n\n #Оси абсцис и ординат\n canv.create_line(0,c_y/2,c_x,c_y/2,width=1)\n canv.create_line(c_x/2,0,c_x/2,c_y,width=1)\n\n #Вывод окружности\n canv.create_oval(circle_dr[0]-circle_dr[2],circle_dr[1]+circle_dr[2],circle_dr[0]+circle_dr[2],circle_dr[1]-circle_dr[2],outline = \"red\")\n\n\n #Вывод треугольника\n canv.create_line(tr_x_dr[0],tr_y_dr[0],tr_x_dr[1],tr_y_dr[1],fill=\"yellow\")\n\n canv.create_line(tr_x_dr[0], tr_y_dr[0], tr_x_dr[2], tr_y_dr[2],fill=\"yellow\")\n\n canv.create_line(tr_x_dr[1], tr_y_dr[1], tr_x_dr[2], tr_y_dr[2],fill=\"yellow\")\n\n '''for i in range(len(tx) - 1):\n for j in range(i + 1, len(tx)):\n print(i+1,j+1)\n lne = make_line(tr_x_dr[i], tr_x_dr[j], tr_y_dr[i], tr_y_dr[j])\n print(lne)\n if (len(lne) == 2):\n if (kas[1] == lne[0] * kas[1] + lne[1]):\n canv.create_line(tr_x_dr[i],tr_y_dr[i],tr_x_dr[j]+1000,tr_y_dr[j]+1000,fill=\"yellow\")\n if (len(lne) == 1):\n if (kas[0] == lne[0]):\n canv.create_line(tr_x_dr[i],tr_x_dr[i],tr_x_dr[i],tr_y_dr[j]+1000,fill=\"yellow\")'''\n\n\n #Точки на которых строится результирующий треугольник\n canv.create_line(x_c,y_c,x_c+2,y_c+2,width=3)\n canv.create_line(circle_dr[0],circle_dr[1],circle_dr[0]+2,circle_dr[1]+2,width=3)\n canv.create_line(kas[0],kas[1],kas[0]+2,kas[1]+2,width=3)\n\n\n canv.create_polygon([x_c,y_c],[circle_dr[0],circle_dr[1]],[kas[0],kas[1]],fill=\"white\",outline = \"black\")\n\n canv.grid()\n\n root_gr.mainloop()\n\n\n\n\n# Эта функция производит считывание введенных точек из поля ввода в массив точек множества\n# или треугольнкиа в зависимости от выбранного маркера\ndef get_points():\n selection = v.get() # Узнаем какой маркер отмечен\n string = enter_point.get()\n enter_point.delete(0, END) # Очистка поля для пользователя после захвата введенных данных\n string = string.split()\n\n if (selection == 1):\n if (len(string) == 0 or len(string) == 1):\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Поле ввода пусто или координаты введены неполностью!\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n\n print(\"\\n\")\n if (len(tx) < 3 and len(ty) < 3):\n listbox1.insert(END, string)\n string[0], string[1] = float(string[0]), float(string[1])\n tx.append(string[0])\n ty.append(string[1])\n elif len(tx) == len(ty) == 3:\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Ввведено максимальное количество точек!Удалите какую-нибудь\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n # print(\"t\",t)\n\n elif (selection == 2): # Если заполняем массив\n if (len(string) == 0 or len(string) == 1):\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Поле ввода пусто или координаты введены неполностью!\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n\n # print(\"\\n\")\n listbox2.insert(END, string)\n string[0], string[1] = float(string[0]), float(string[1]) # массив цифр\n mx.append(string[0])\n my.append(string[1])\n\n # print(\"Добавлено\\nTX = \", tx, \"\\nTY = \", ty, \"\\n\")\n # print(\"Доабвлено\\nMX = \", mx, \"\\nMY = \", my, \"\\n\\n\")\n\n # print(\"Mx = \",mx,\"\\nMy =\",my)\n # print(\"Tx = \",tx,\"\\nTy =\",ty)\n\n return\n\n\n# Функция редактирования точки\ndef change_point():\n selection = v.get()\n replace_with = enter_point.get() # Точка на которую будет меняться\n replace_with = replace_with.split() # Создание массива\n if (selection == 1):\n if (replace_with == \"\" or len(replace_with) == 1):\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Поле ввода пусто или координаты введены неполностью!\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n\n to_change = listbox1.get(ACTIVE) # Выделенная в боксе точка она будет изменяться\n to_change = list(to_change)\n\n for i in range(len(tx)):\n if (tx[i] == float(to_change[0]) and ty[i] == float(to_change[1])):\n tx[i], ty[i] = float(replace_with[0]), float(replace_with[1])\n listbox1.delete(i + 1);\n listbox1.insert(i + 1, replace_with);\n\n print(tx, \"\\n\", ty)\n elif (selection == 2):\n if (replace_with == \"\" or len(replace_with) == 1):\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Поле ввода пусто или координаты введены неполностью!\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n\n to_change = listbox2.get(ACTIVE) # Выделенная в боксе точка она будет изменяться\n to_change = list(to_change)\n\n for i in range(len(mx)):\n if (mx[i] == float(to_change[0]) and my[i] == float(to_change[1])):\n mx[i], my[i] = float(replace_with[0]), float(replace_with[1])\n listbox2.delete(i + 1);\n listbox2.insert(i + 1, replace_with);\n\n # print(\"Изменено\\nTX = \", tx, \"\\nTY = \", ty, \"\\n\")\n # print(\"Изменено\\nMX = \", mx, \"\\nMY = \", my, \"\\n\\n\")\n\n\n# отлажена\n# Функция удаления точки по нажатию конпки при выбранной точке в листбоксе1 или 2\ndef del_point():\n selection = v.get()\n\n if (selection == 1):\n to_del = listbox1.get(ACTIVE)\n to_del = list(to_del)\n\n i = 0\n while i < len(tx):\n # print(tx[i])\n # print(float(to_del[0]))\n if (tx[i] == float(to_del[0]) and ty[i] == float(to_del[1])):\n del tx[i]\n del ty[i]\n listbox1.delete(i + 1)\n else:\n i += 1\n\n elif (selection == 2):\n to_del = listbox2.get(ACTIVE)\n to_del = list(to_del)\n\n l = 0\n while l < len(my):\n if (mx[l] == float(to_del[0]) and my[l] == float(to_del[1])):\n del mx[l]\n del my[l]\n listbox2.delete(l + 1)\n else:\n l += 1\n\n # print(\"Удалено\\nTX = \", tx, \"\\nTY = \", ty, \"\\n\")\n # print(\"Удалено\\nMX = \", mx, \"\\nMY = \", my, \"\\n\\n\")\n\n\ndef find_triangle_centre(s1_x, s2_x, s3_x, s1_y, s2_y, s3_y):\n x_c = (s1_x + s2_x + s3_x) / 3\n\n y_c = (s1_y + s2_y + s3_y) / 3\n\n # print(\"центр треугольника\", x_c, y_c)\n\n return x_c, y_c\n\n\ndef tr_area(x1, x2, x3, y1, y2, y3):\n side_1 = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n a = side_1\n\n side_2 = sqrt((x3 - x1) ** 2 + (y3 - y1) ** 2)\n b = side_2\n\n side_3 = sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)\n c = side_3\n\n # Рассчет площади треугольника по формуле Герона\n\n p = (side_1 + side_2 + side_3) / 2\n\n S = sqrt(p * (p - a) * (p - b) * (p - c))\n\n return S\n\n#проверка введенных данных\ndef check():\n\n if (len(tx) != 3 and len(tx) != 3):\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Недостаточно точек для построения треугольника\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n else:\n side_1 = sqrt( (tx[1]-tx[0])**2 + (ty[1]-ty[0])**2 )\n side_2 = sqrt( (tx[2]-tx[1])**2 + (ty[2]-ty[1])**2 )\n side_3 = sqrt( (tx[2]-tx[0])**2+ (ty[2]-ty[0])**2 )\n\n if not(side_1 + side_2 > side_3 and side_1 + side_3 > side_2 and side_2 + side_3 > side_1):\n\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Треугольник не существует\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n\n if len(mx) <3:\n top = Toplevel()\n top.title(\"Ошибка\")\n msg = Message(top, text=\"Необходимо миниммум три точки множества\\nПовторите ввод!\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n return\n\n# Вывод условия.\ndef ouput_info():\n top = Toplevel()\n top.title(\"Условие\")\n\n msg = Message(top, text=\"На плоскости заданы координаты вершин треугольника и множество точек.\"\n \"\\nНайти такие окружности, которые проходят хотя бы через три различные точки множества\\n\"\n \"и для которых хотя бы одни из прямых, проходящих через сторону треугольника может быть касательной к окружности\\n\"\n \"Среди полученных окружностей найти такую,для которой площадь треугольника, образованного центрами треугольника и окружности\\n\"\n \"и точки касания максимальна.\")\n msg.grid(row=0, column=0)\n\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n\n return\n\n\n# ПОСТРОЕНИЕ ОКРУЖНОСТИ НА ТРЕХ ТОЧКАХ\n# Данная функция возвращает координаты центра и радиус в массиве\n# или пустой массив если окружность на данных точках не существует\n#через пару точек для задания окружности проводятся отрезки\n#центр круга лежит на пересечении двух перпендикулярных прямых, которые проходят через середины отрезков\n\ndef make_circle(circle, x1, x2, x3, y1, y2, y3):\n # Проверка на вертикальные и горизонтальные прямые(отсутствие этой проверки может повлечь за собой деление на ноль)\n if (x1 == x2 == x3 or y1 == y2 == y3):\n return False\n\n\n # Проверка на вертикальные и горизонтальные прямые(отсутствие этой проверки может повлечь за собой деление на ноль\n if (x1 == x2 or y1 == y2):\n tmp_x = x2\n tmp_y = y2\n x2 = x3\n y2 = y3\n x3 = tmp_x\n y3 = tmp_y\n\n if (x2 == x3 or y2 == y3):\n tmp_x = x1\n tmp_y = y1\n x1 = x2\n y1 = y2\n x2 = tmp_x\n y2 = tmp_y\n\n # print(\"Changed \",x1,y1,\" \",x2,y2,\" \",x3,y3)\n\n ma = (y2 - y1) / (x2 - x1)\n mb = (y3 - y2) / (x3 - x2)\n\n # print(\"turns \",ma,\" \",mb)\n\n if (ma - mb == 0):\n return False\n\n x_centre = (ma * mb * (y1 - y3) + mb * (x1 + x2) - ma * (x2 + x3)) / (2 * (mb - ma))\n if x_centre == -0.0:\n x_centre = 0\n\n y_centre = ((-1 / ma) * (x_centre - ((x1 + x2) / 2))) + ((y1 + y2) / 2)\n\n if y_centre == -0.0:\n y_centre = 0\n\n radius = sqrt((x1 - x_centre) ** 2 + (y1 - y_centre) ** 2)\n\n circle.append(x_centre)\n circle.append(y_centre)\n circle.append(radius)\n # print(circle)\n\n return True\n\n\n# ПОСТРОЕНИЕ ПРЯМОЙ НА ДВУХ ТОЧКАХ\ndef make_line(x1, x2, y1, y2):\n if (x2 - x1 != 0):\n k = (y2 - y1) / (x2 - x1)\n if k == -0.0 or 0.0:\n k = round(k)\n m = y1 - k * x1\n return [k, m]\n else:\n x = x1\n return [x1]\n\n\ndef find_single_intersection(x0, y0, radius, k, m):\n a = k ** 2 + 1\n b = -2 * x0 + 2 * k * m - 2 * k * y0\n\n c = x0 ** 2 + m ** 2 + y0 ** 2 - 2 * m * y0 - radius ** 2\n\n D = b ** 2 - 4 * a * c\n\n # print(D)\n\n if (D == 0):\n x = -b / (2 * a)\n y = k * x + m\n\n return [x, y]\n else:\n return []\n\n\ndef find_single_vert_intersection(x0, y0, radius, x1):\n a = 1\n b = -2 * y0\n c = y0 ** 2 + (x1 - x0) ** 2 - radius ** 2\n\n D = b ** 2 - 4 * a * c\n\n # print(D)\n\n if (D == 0):\n y = -b / (2 * a)\n\n return [x1, y] # координаты точки касания\n else:\n return []\n\n\n# Вычисление условия\n# TO-DO:\n# СДЕЛАТЬ ПОИСК ПЛОЩАДЕЙ ПО УСЛОВИЮ, НАЙТИ ТАКИЕ ПРЯМЫЕ (С НЕНУЛЕВЫМ УГЛ КОЭФ) КАСАТЕЛЬНЫЕ К ОКРУЖНОСТИ\n# Оставить завтра только визуализацию\ndef execute():\n line_output = ''\n\n ct = 0\n circles = []\n circle = []\n # tx[i] ty[i] - 1 точка\n # этот цикл тройной вложенности формирует окружности\n for i in range(len(mx) - 1):\n for j in range(i + 1, len(mx) + 1):\n for k in range(j + 1, len(mx)):\n # print(\" \", i + 1, \" \", j + 1, \" \", k + 1)\n if (make_circle(circle, mx[i], mx[j], mx[k], my[i], my[j], my[k]) == True):\n ct += 1\n # circle.append(ct)\n circles.append(circle)\n circle = []\n\n #print(circles)\n\n x_c = 0\n y_c = 0\n x_c, y_c = find_triangle_centre(tx[0], tx[1], tx[2], ty[0], ty[1], ty[2])\n # print(\"Центр треугольника - (\", x_c, \";\", y_c, \")\\n\\n\")\n\n\n p = 0\n line_output = 'Было сформировано ' + str(len(circles)) + ' окружностей\\n' + 'Центр треугольника - (' + str(\n round(x_c, 2)) + ');(' + str(round(y_c, 2)) + ')\\n\\n'\n p += 1\n\n counter = 0\n kas = []\n for i in range(len(circles)):\n kas.append([])\n\n # ЦИКЛ ИТЕРИРОВАНИЯ ПО ПРЯМЫМ ТРЕУГОЛЬНИКА для каждой окружности\n modified_circs = []\n flag = 0\n\n to_print =[]\n\n # Данный цикл тройной вложенности ищет окружности которые имеют касательные(мб 1 единственную) и формирует два массива\n # 1 - массив окружностей, имеющих касательные\n # 2 - массив кастальеных к этим окружностям\n # P.S. Печать на стадии релиза убрать (debug only)\n for cir in range(len(circles)): # проход по окружностям\n for i in range(len(tx) - 1):\n for j in range(i + 1, len(tx)):\n line = make_line(tx[i], tx[j], ty[i], ty[j])\n if len(line) == 2:\n tang_point = find_single_intersection(circles[cir][0], circles[cir][1], circles[cir][2], line[0],\n line[1])\n\n if (len(tang_point) != 0):\n to_print.append([i+1,j+2])\n flag += 1\n counter += 1\n kas[cir].append([tang_point[0], tang_point[1]])\n if not (circles[cir] in modified_circs):\n modified_circs.append(circles[cir])\n if len(line) == 1:\n tang_point = find_single_vert_intersection(circles[cir][0], circles[cir][1], circles[cir][2],\n line[0])\n if len(tang_point) != 0:\n to_print.append([i + 1, j + 2])\n flag += 1\n counter += 1\n kas[cir].append([tang_point[0], tang_point[1]])\n if not (circles[cir] in modified_circs):\n modified_circs.append(circles[cir])\n\n if not (flag == 0):\n\n print(\"\\n\\n\\n\",to_print,\"\\n\\n\\n\")\n\n line_output = line_output + 'Из них ' + str(len(modified_circs)) + ' окружности имеют касательные:\\n '\n p += 1\n\n index = 0\n while index < len(kas):\n if len(kas[index]) == 0:\n del kas[index]\n else:\n index += 1\n\n areas = []\n for i in range(len(kas)):\n areas.append([])\n\n for i in range(len(modified_circs)):\n line_output += '\\n' + str(i + 1) + ') Окружность - ' + 'центр (' + str(modified_circs[i][0]) + '; ' + str(\n modified_circs[i][1]) + ')\\n '\n p += 1\n for j in range(len(kas[i])):\n S = tr_area(x_c, modified_circs[i][0], kas[i][j][0], y_c, modified_circs[i][1], kas[i][j][1])\n # print(\"S = \",S,\"\\n\\n\")\n areas[i].append(S)\n line_output += ' ' + str(j + 1) + ' точка касания (' + str(kas[i][j][0]) + ';' + str(\n kas[i][j][1]) + ')\\n Площадь треугольника,' \\\n '\\n построенного на данной точке касания ' + str(round(S, 2)) + '\\n'\n p += 1\n\n m = areas[0][0]\n number = 0\n\n x_k = y_k = 0\n d = 0\n\n for i in range(len(areas)):\n for j in range(len(areas[i])):\n if areas[i][j] > m:\n m = areas[i][j]\n if j != len(areas[i]) - 1:\n d = j\n else:\n d = len(areas[i]) - 1\n if i != len(areas) - 1:\n number = i + 1\n else:\n number = len(areas) - 1\n\n line_output += '\\n\\nОкружность для которой площадь треугольника,\\nобразованного центрамитреугольника и окружности\\nи точки касания максимальна - ' + 'окружность с центром ' \\\n 'в точке (' + str(\n modified_circs[number][0]) + \\\n ';' + str(modified_circs[number][1]) + ')\\n\\n'\n\n line_output += 'Площадь треугольника - ' + str(round(m, 2))\n\n p += 1\n\n '''print(\"\\nAreas list - \", areas)\n print(\"m = \", m)\n print(\"circle one \", modified_circs[number])\n print(\"Tangent point bITCH !!!!!\", kas[number][d])'''\n # print(\"circles only with tangent lines = \",modified_circs,\"\\n\")\n # print(\"kas = \", kas,\"\\n\\n\")\n # print(\"\\nAreas list - \",areas)\n\n display_graphics_execution(modified_circs[number], tx, ty, x_c, y_c,kas[number][d],line_output)\n\n else:\n top = Toplevel()\n top.title(\"Ответ\")\n msg = Message(top, text=\"Не найдено окружностей,\\nподходящих условию задачи\")\n msg.grid(row=0, column=0)\n Button(top, text=\"Закрыть\", command=top.destroy).grid(row=1, column=0)\n\n\n# MAIN WINDOW\nroot = Tk()\n\nroot.minsize(width=500, height=300)\nroot.title('Ввод исходных значений')\n\nv = IntVar()\n\n# Листбокс для треугольника\nlistbox1 = Listbox(root, height=5, width=10, selectmode=SINGLE)\nlistbox1.insert(END, \"X Y\")\n\n# Листбокс для множества\nlistbox2 = Listbox(root, height=5, width=10, selectmode=SINGLE)\nlistbox2.grid(row=2, column=1)\nlistbox2.insert(END, \"X Y\")\nlistbox1.grid(row=2)\n\nRadiobutton(root, text=\"Координаты вершин треугольника\", padx=20, variable=v, value=1).grid(row=1)\nRadiobutton(root, text=\"Множество точек\", padx=20, variable=v, value=2).grid(row=1, column=1)\n\nLabel(root, text=\"Введите точку\").grid(row=3)\nenter_point = Entry(root)\nenter_point.grid(row=3, column=1)\n\nlab1 = Label(root)\n\nButton(root, text=\"Добавить\", command=get_points).grid(row=4)\nButton(root, text=\"Удалить точку\", command=del_point).grid(row=5)\nButton(root, text=\"Вычислить\", command=execute).grid(row=7)\nButton(root, text=\"Изменить точку\", command=change_point).grid(row=6)\nButton(root, text='Выход', command=root.quit).grid(row=7, column=1)\nButton(root, text='Условие', command=ouput_info).grid(row=5, column=1)\nButton(root, text=\"Проверка\", command=check).grid(row=4, column=1)\nButton(root, text=\"Очистить\", command=clear).grid(row=6, column=1)\n\nroot.mainloop()\n","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":24791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"234184788","text":"import json\nimport glob\n\ndef print_scores(dirname):\n scores = {}\n for filename in glob.glob(f'{dirname}/*.json'):\n scores[filename] = {}\n with open(filename) as infile:\n for result in json.load(infile):\n for subject, score in result.items():\n scores[filename].setdefault(subject,[])\n scores[filename][subject].append(score)\n\n for one_class in scores:\n print(one_class)\n for subject, subject_scores in scores[one_class].items():\n min_score = min(subject_scores)\n max_score = max(subject_scores)\n average_score = (sum(subject_scores) /\n len(subject_scores))\n\n print(subject)\n print(f'\\tmin {min_score}')\n print(f'\\tmax {max_score}')\n print(f'\\taverage {average_score}')","sub_path":"json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"347592963","text":"from flask_testing import TestCase\n\nfrom src.models import db\nfrom src.app import create_app\nfrom src.models.task import Task\n\nclass ModelTaskTestCase(TestCase):\n def create_app(self):\n return create_app()\n\n def setUp(self):\n db.create_all()\n\n def tearDown(self):\n db.drop_all()\n\n def test_task_CRUD(self):\n origin_task = Task()\n origin_task.name = 'origin task'\n origin_task.status = False\n\n # create\n db.session.add(origin_task)\n db.session.commit()\n\n # read\n tasks = Task.query.filter_by(name=origin_task.name)\n task = tasks.first()\n self.assertEqual(1, tasks.count())\n self.assertEqual(origin_task.status, task.status)\n\n # update\n task.status = True\n db.session.commit()\n tasks = Task.query.filter_by(name=origin_task.name)\n task = tasks.first()\n self.assertEqual(True, task.status)\n\n # delete\n db.session.delete(task)\n db.session.commit()\n\n tasks = Task.query.filter_by(name=task.name)\n self.assertEqual(0, tasks.count())\n","sub_path":"backend/tests/model_task_tests.py","file_name":"model_task_tests.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"10025256","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport scrapy\nimport time\nfrom ..sendemail import *\nfrom urllib.parse import urlencode\nfrom scrapy import Request\nfrom ..items import VczhItem\n\nclass VcSpider(scrapy.Spider):\n start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n name = 'vc'\n allowed_domains = ['www.zhihu.com']\n base_url = 'https://www.zhihu.com/api/v4/members/excited-vczh/followees?'\n\n def start_requests(self):\n data = {\n 'include': 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics',\n 'limit': 20\n }\n for page in range(1, self.settings.get('MAX_PAGE') + 1):\n data['offset'] = page * 20\n params = urlencode(data)\n url = self.base_url + params\n yield Request(url, callback=self.parse, errback=self.error_back)\n\n def parse(self, response):\n result = json.loads(response.text)\n for data_ in result.get('data'):\n item = VczhItem()\n item['id'] = data_.get('id')\n item['avatar_url'] = data_.get('avatar_url').replace('_is', '')\n item['name'] = data_.get('name')\n item['gender'] = data_.get('gender')\n item['headline'] = data_.get('headline')\n item['person_url'] = data_.get('url'),\n item['follower_count'] = data_.get('follower_count')\n item['answer_count'] = data_.get('answer_count')\n item['articles_count'] = data_.get('articles_count')\n yield item\n\n\n def closed(self, reason):\n \"\"\"\n 爬虫关闭发送通知邮件\n \"\"\"\n EmailSenderClient = EmailSender()\n receive_list = ['northxw@gmail.com', 'northxw@qq.com']\n fnished = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n subject = \"爬虫状态报告!\"\n body = \"爬虫名称: {}\\n\\n, 开始时间: {}\\n 请求成功总量:{}\\n 数据库存储总量:{}\\n 下载头像总量:{}\\n 结束时间 : {}\\n\".format(\n '知乎轮子哥粉丝爬虫',\n str(self.start),\n str(COUNT_SUCCESS_REQUEST['Request_Success']),\n str(COUNT_SUCCESS_DB['Storage_Success']),\n str(RESPONSE_STATUS['Download_Success']),\n str(str(fnished)),\n )\n EmailSenderClient.sendEmail(receive_list, subject, body)\n\n\n def error_back(self, e):\n _ = self\n self.logger.debug('Request Error: {}'.format(e))","sub_path":"16-vczh/vczh/spiders/vc.py","file_name":"vc.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"344255009","text":"# -*- coding: utf-8 -*-\nimport logging\nimport requests\nimport markdown\nimport glob\nimport simplejson\nimport re\nimport datetime\nfrom slugify import slugify\n\nfrom magnet.config import settings\nfrom magnet.converter.item import Item\n\nfrom matmos.utils import make_md5\n\n\nclass MdownItem(Item):\n\n def get_id(self):\n assert self.name != None\n assert self.fname != None\n file_name = self.fname.split('/')[-1]\n return make_md5('%s-%s' % (self.name, file_name))[:8]\n\n def get_images(self):\n images = []\n for image in self.item.get('images'):\n images.append({\n 'type': 'feature',\n 'title': None,\n 'url': image,\n 's3_url': None,\n 'credit': None,\n 'description': None,\n 'width': None,\n 'height': None,\n })\n return images\n\n def get_source(self):\n return {\n 'name': self.name,\n 'id': None,\n 'url': None,\n }\n\n def get_slug(self):\n return self.item.get('slug')\n\n def get_tags(self):\n tags = self.item.get('tags', '')\n if tags:\n return [n.strip().lower() for n in tags.split(',')]\n return []\n\n def get(self):\n md = markdown.Markdown(extensions = ['markdown.extensions.meta'])\n text = self.item.decode('utf-8')\n html = md.convert(text)\n meta = md.Meta\n meta = {k: v[0] for k, v in meta.items()}\n images, html_clean = self.extract_img_tags(html)\n self.item = {\n 'body': html_clean,\n 'images': images,\n 'title': meta.get('title'),\n 'author': meta.get('author'),\n 'type': 'inline',\n 'status': meta.get('status', 'live'),\n 'slug': slugify(meta.get('title')),\n 'created': self.to_timestamp(meta.get('created')),\n 'published': self.to_timestamp(meta.get('publish')),\n 'tags': meta.get('tags')\n }\n return super(MdownItem, self).get()\n\n","sub_path":"magnet/converter/mdown_item.py","file_name":"mdown_item.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"502366515","text":"import requests\nimport time\nimport logging\n\n\nclass TaskConsumer:\n server_url: str\n queue_name: str\n\n def __init__(self, server_url):\n self.server_url = server_url\n\n def peek(self, queue_name, cursor=None, size=1, timeout=5):\n res = requests.post(\n f'{self.server_url}/task/peek',\n json={\n 'queue': queue_name,\n 'cursor': cursor,\n 'size': size,\n 'timeout': timeout,\n },\n timeout=timeout + 5,\n )\n data = res.json()['data']\n cursor = res.json()['cursor']\n return data, cursor\n\n def acquire(self, queue_name, peek_data, prt=30):\n res = requests.post(\n f'{self.server_url}/task/acquire',\n json={\n 'queue': queue_name,\n 'ids': [i['id'] for i in peek_data],\n 'promise_reply_time': prt,\n })\n return res.json()['data']\n\n def reply(self, queue_name, id, info, content):\n res = requests.post(\n f'{self.server_url}/task/reply',\n json={\n 'queue': queue_name,\n 'id': id,\n 'info': info or {},\n 'content': content or '',\n }\n )\n return res.json()['data']\n\n def mainloop(self):\n queue_name = self.queue_name\n cursor = None\n while True:\n try:\n # peek\n data, cursor = self.peek(queue_name, cursor)\n if not data:\n continue\n data = [i for i in data if self.accept(i)]\n data = self.acquire(queue_name, data)\n for i in data:\n try:\n info, content = self.process(i)\n self.reply(queue_name, i['id'], info, content)\n except Exception as e:\n logging.exception(e)\n except Exception as e:\n logging.exception(e)\n time.sleep(5)\n return\n\n def accept(self, data):\n return True\n\n def process(self, data):\n return {\"msg\": \"ok\"}, ''\n\n\nif __name__ == \"__main__\":\n tc_endpoint = \"http://127.0.0.1:8000\"\n c = TaskConsumer(tc_endpoint)\n c.queue_name = 'test'\n c.mainloop()\n","sub_path":"client/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"391491444","text":"# Copyright 2017 Rice University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport argparse\nimport sys\nimport json\nimport random\nfrom itertools import chain\nimport socket\nimport ast_extractor\nimport re\nimport simplejson\n\nHELP = \"\"\"Use this script to extract evidences from a raw data file with sequences generated by driver.\nYou can also filter programs based on number and length of sequences, and control the samples from each program.\"\"\"\n\nTCP_IP = '127.0.0.1'\nTCP_PORT = 5005\nBUFFER_SIZE = 1024\nMESSAGE = \"Start Encoding\"\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((TCP_IP, TCP_PORT))\n\n\ndef shorten(call):\n call = re.sub('^\\$.*\\$', '', call) # get rid of predicates\n name = call.split('(')[0].split('.')[-1]\n name = name.split('<')[0] # remove generics from call name\n return name\n\n\ndef extract_evidence(clargs):\n #print('Loading data file...')\n with open(clargs.input_file[0]) as f:\n js = json.load(f)\n #print('Done')\n done = 0\n programs = []\n\n ''' Program_dict dictionary holds Key values in format\n (Key = File_Name Value = dict(Key = String Method_Name, Value = [String ReturnType, List[String] FormalParam , List[String] Sequences] ))\n '''\n programs_dict = dict()\n\n\n valid = []\n #This part appends sorrounding evidences\n done = 0\n ignored = 0\n for program in js['programs']:\n try:\n if '__PDB_FILL__' not in program['body']:\n ast_node_graph, ast_paths = ast_extractor.get_ast_paths(program['ast']['_nodes'])\n ast_extractor.validate_sketch_paths(program, ast_paths, clargs.max_ast_depth)\n\n file_name = program['file']\n method_name = program['method']\n\n returnType = program['returnType'] if 'returnType' in program else \"__Constructor__\"\n\n formalParam = program['formalParam'] if 'formalParam' in program else []\n\n # if '__PDB_FILL__' not in program['body']:\n # if len(sequences) > clargs.max_seqs or (len(sequences) == 1 and len(sequences[0]['calls']) == 1) or \\\n # any([len(sequence['calls']) > clargs.max_seq_length for sequence in sequences]):\n # raise ast_extractor.TooLongPathError\n\n sequences = program['sequences']\n sequences = [[shorten(call) for call in json_seq['calls']] for json_seq in sequences]\n sequences.sort(key=len, reverse=True)\n\n if file_name not in programs_dict:\n programs_dict[file_name] = dict()\n\n programs_dict[file_name][method_name] = [returnType, formalParam, sequences[0]]\n\n\n except (ast_extractor.TooLongPathError, ast_extractor.InvalidSketchError) as e:\n ignored += 1\n #valid.append(False)\n\n done += 1\n #print('Extracted evidences of sorrounding features for {} programs'.format(done), end='\\r')\n\n #print('')\n\n #print('{:8d} programs/asts in training data'.format(done))\n #print('{:8d} programs/asts ignored by given config'.format(ignored))\n #print('{:8d} programs/asts to search over'.format(done - ignored))\n\n\n done = 0\n for pid, program in enumerate(js['programs']):\n\n if '__PDB_FILL__' not in program['body']:\n continue\n\n apicalls = []\n types = []\n keywords = []\n sequences = []\n\n sample = dict(program)\n\n calls = gather_calls(program['ast'])\n apicalls = list(set(chain.from_iterable([APICallsFromCall(call)\n for call in calls])))\n types = list(set(chain.from_iterable([TypesFromCall(call)\n for call in calls])))\n keywords = list(set(chain.from_iterable([KeywordsFromCall(call)\n for call in calls])))\n\n sequence = []\n javaDoc = \"\"\n for string in re.findall(r\"\\S+\", program['body']): # separates out all lines of a program\n if 'call:' in string:\n apicalls.append(string.split(\":\")[1])\n if 'type:' in string:\n types.append(string.split(\":\")[1])\n if 'keyword:' in string:\n keywords.append(string.split(\":\")[1])\n if 'sequence:' in string:\n for call in string.split(\":\")[1:]:\n sequence.append(call)\n if 'javadoc:' in string:\n javaDoc = \" \".join(re.split(\" |:\" , string)[1:])\n\n\n\n\n sample['javaDoc'] = javaDoc\n\n sample['sequences'] = sequence\n\n file_name = program['file']\n method_name = program['method']\n\n returnType = program['returnType'] if 'returnType' in program else \"__Constructor__\"\n formalParam = program['formalParam'] if 'formalParam' in program else []\n\n # Take in classTypes and sample a few\n classTypes = program['classTypes'] if 'classTypes' in program else []\n random.shuffle(classTypes)\n\n sample['sorrreturntype'] = []\n sample['sorrformalparam'] = []\n sample['sorrsequences'] = []\n sample['classTypes'] = classTypes\n sample['apicalls'] = apicalls\n sample['types'] = types\n sample['keywords'] = keywords\n\n\n # (Key = File_Name Value = dict(Key = String Method_Name, Value = [String ReturnType, List[String] FormalParam , List[String] Sequences] ))\n otherMethods = list(programs_dict[file_name].keys())\n random.shuffle(otherMethods)\n\n countSorrMethods = 0\n for method in otherMethods: # Each iterator is a method Name with @linenumber\n\n # Ignore the current method from list of sorrounding methods\n if method == method_name:\n continue\n # Keep a count on number of sorrounding methods, if it exceeds the random choice, break\n countSorrMethods += 1\n\n\n for choice, evidence in zip(programs_dict[file_name][method],['sorrreturntype', 'sorrformalparam', 'sorrsequences']):\n sample[evidence].append(choice)\n\n programs.append(sample)\n\n done += 1\n print('Extracted evidence for {} programs'.format(done), end='\\n')\n\n with open('/home/ubuntu/QueryProg.json', 'w') as f:\n json.dump({'programs': programs}, fp=f, indent=2)\n\n\n s.sendall(MESSAGE.encode('utf-8'))\n data = s.recv(BUFFER_SIZE)\n s.close()\n\n print (\"received ACK:\")\n return\n\n\n\n\ndef APICallsFromCall(callnode):\n\tcall = callnode['_call']\n\tcall = re.sub('^\\$.*\\$', '', call) # get rid of predicates\n\tname = call.split('(')[0].split('.')[-1]\n\tname = name.split('<')[0] # remove generics from call name\n\treturn [name] if name[0].islower() else [] # Java convention\n\ndef get_types_re(s):\n\tpatt = re.compile('java[x]?\\.(\\w*)\\.(\\w*)(\\.([A-Z]\\w*))*')\n\ttypes = [match.group(4) if match.group(4) is not None else match.group(2)\n\t\t\t for match in re.finditer(patt, s)]\n\tprimitives = {\n\t\t'byte': 'Byte',\n\t\t'short': 'Short',\n\t\t'int': 'Integer',\n\t\t'long': 'Long',\n\t\t'float': 'Float',\n\t\t'double': 'Double',\n\t\t'boolean': 'Boolean',\n\t\t'char': 'Character'\n\t}\n\n\tfor p in primitives:\n\t\tif s == p or re.search('\\W{}'.format(p), s):\n\t\t\ttypes.append(primitives[p])\n\treturn list(set(types))\n\ndef TypesFromCall(callnode):\n\tcall = callnode['_call']\n\ttypes = get_types_re(call)\n\n\tif '_throws' in callnode:\n\t\tfor throw in callnode['_throws']:\n\t\t\ttypes += get_types_re(throw)\n\n\tif '_returns' in callnode:\n\t\ttypes += get_types_re(callnode['_returns'])\n\n\treturn list(set(types))\n\nKeywords_STOP_WORDS = { # CoreNLP English stop words\n \"'ll\", \"'s\", \"'m\", \"a\", \"about\", \"above\", \"after\", \"again\", \"against\", \"all\", \"am\", \"an\", \"and\",\n \"any\", \"are\", \"aren't\", \"as\", \"at\", \"be\", \"because\", \"been\", \"before\", \"being\", \"below\", \"between\",\n \"both\", \"but\", \"by\", \"can\", \"can't\", \"cannot\", \"could\", \"couldn't\", \"did\", \"didn't\", \"do\", \"does\",\n \"doesn't\", \"doing\", \"don't\", \"down\", \"during\", \"each\", \"few\", \"for\", \"from\", \"further\", \"had\",\n \"hadn't\", \"has\", \"hasn't\", \"have\", \"haven't\", \"having\", \"he\", \"he'd\", \"he'll\", \"he's\", \"her\",\n \"here\", \"here's\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"how's\", \"i\", \"i'd\", \"i'll\",\n \"i'm\", \"i've\", \"if\", \"in\", \"into\", \"is\", \"isn't\", \"it\", \"it's\", \"its\", \"itself\", \"let's\", \"me\",\n \"more\", \"most\", \"mustn't\", \"my\", \"myself\", \"no\", \"nor\", \"not\", \"of\", \"off\", \"on\", \"once\", \"only\",\n \"or\", \"other\", \"ought\", \"our\", \"ours\", \"ourselves\", \"out\", \"over\", \"own\", \"same\", \"shan't\", \"she\",\n \"she'd\", \"she'll\", \"she's\", \"should\", \"shouldn't\", \"so\", \"some\", \"such\", \"than\", \"that\", \"that's\",\n \"the\", \"their\", \"theirs\", \"them\", \"themselves\", \"then\", \"there\", \"there's\", \"these\", \"they\",\n \"they'd\", \"they'll\", \"they're\", \"they've\", \"this\", \"those\", \"through\", \"to\", \"too\", \"under\",\n \"until\", \"up\", \"very\", \"was\", \"wasn't\", \"we\", \"we'd\", \"we'll\", \"we're\", \"we've\", \"were\", \"weren't\",\n \"what\", \"what's\", \"when\", \"when's\", \"where\", \"where's\", \"which\", \"while\", \"who\", \"who's\", \"whom\",\n \"why\", \"why's\", \"with\", \"won't\", \"would\", \"wouldn't\", \"you\", \"you'd\", \"you'll\", \"you're\", \"you've\",\n \"your\", \"yours\", \"yourself\", \"yourselves\", \"return\", \"arent\", \"cant\", \"couldnt\", \"didnt\", \"doesnt\",\n \"dont\", \"hadnt\", \"hasnt\", \"havent\", \"hes\", \"heres\", \"hows\", \"im\", \"isnt\", \"its\", \"lets\", \"mustnt\",\n \"shant\", \"shes\", \"shouldnt\", \"thats\", \"theres\", \"theyll\", \"theyre\", \"theyve\", \"wasnt\", \"were\",\n \"werent\", \"whats\", \"whens\", \"wheres\", \"whos\", \"whys\", \"wont\", \"wouldnt\", \"youd\", \"youll\", \"youre\",\n \"youve\"\n }\n\ndef Keywords_split_camel(s):\n\ts = re.sub('(.)([A-Z][a-z]+)', r'\\1#\\2', s) # UC followed by LC\n\ts = re.sub('([a-z0-9])([A-Z])', r'\\1#\\2', s) # LC followed by UC\n\treturn s.split('#')\n\ndef KeywordsFromCall(callnode):\n\tcall = callnode['_call']\n\tcall = re.sub('^\\$.*\\$', '', call) # get rid of predicates\n\tqualified = call.split('(')[0]\n\tqualified = re.sub('<.*>', '', qualified).split('.') # remove generics for keywords\n\n\t# add qualified names (java, util, xml, etc.), API calls and types\n\tkeywords = list(chain.from_iterable([Keywords_split_camel(s) for s in qualified])) + \\\n\t\tlist(chain.from_iterable([Keywords_split_camel(c) for c in APICallsFromCall(callnode)])) + \\\n\t\tlist(chain.from_iterable([Keywords_split_camel(t) for t in TypesFromCall(callnode)]))\n\n\t# convert to lower case, omit stop words and take the set\n\treturn list(set([k.lower() for k in keywords if k.lower() not in Keywords_STOP_WORDS]))\n\ndef gather_calls(node):\n \"\"\"\n Gathers all call nodes (recursively) in a given AST node\n\n :param node: the node to gather calls from\n :return: list of call nodes\n \"\"\"\n\n if type(node) is list:\n return list(chain.from_iterable([gather_calls(n) for n in node]))\n node_type = node['node']\n if node_type == 'DSubTree':\n return gather_calls(node['_nodes'])\n elif node_type == 'DBranch':\n return gather_calls(node['_cond']) + gather_calls(node['_then']) + gather_calls(node['_else'])\n elif node_type == 'DExcept':\n return gather_calls(node['_try']) + gather_calls(node['_catch'])\n elif node_type == 'DLoop':\n return gather_calls(node['_cond']) + gather_calls(node['_body'])\n else: # this node itself is a call\n return [node]\n\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description=HELP)\n parser.add_argument('input_file', type=str, nargs=1,\n help='input data file')\n parser.add_argument('--python_recursion_limit', type=int, default=10000,\n help='set recursion limit for the Python interpreter')\n parser.add_argument('--max_seqs', type=int, default=9999,\n help='maximum number of sequences in a program')\n parser.add_argument('--max_seq_length', type=int, default=9999,\n help='maximum length of each sequence in a program')\n parser.add_argument('--max_ast_depth', type=int, default=32,\n help='maximum depth of decoder')\n\n clargs = parser.parse_args()\n sys.setrecursionlimit(clargs.python_recursion_limit)\n\n extract_evidence(clargs)\n","sub_path":"src/main/python/scripts/testEvidencePDBFILLManager.py","file_name":"testEvidencePDBFILLManager.py","file_ext":"py","file_size_in_byte":12789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"66898311","text":"from .test_helpers import SmallboardTestCase\nfrom django.conf import settings\nfrom django.test import override_settings\nfrom rest_framework import status\nfrom puzzles.models import Puzzle, PuzzleTag\n\nTEST_URL = \"https://smallboard.test/\"\n\n\n# Disable all chat features for the purposes of this unit test.\n@override_settings(\n CHAT_DEFAULT_SERVICE=None,\n CHAT_SERVICES={},\n)\nclass ApiTests(SmallboardTestCase):\n def test_get_hunt(self):\n response = self.get_hunt()\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(\n response.data,\n {\n \"id\": self._hunt.pk,\n \"name\": self._hunt.name,\n \"url\": self._hunt.url,\n \"active\": self._hunt.active,\n \"has_drive\": bool(settings.GOOGLE_HUMAN_DRIVE_HUNT_FOLDER_URL),\n },\n )\n\n def test_create_invalid_puzzle(self):\n # Missing name\n response = self.create_puzzle(\n {\"url\": \"https://smallboard.test\", \"is_meta\": False}\n )\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n # Missing url\n response = self.create_puzzle({\"name\": \"test name\", \"is_meta\": False})\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n # Empty string name\n response = self.create_puzzle({\"name\": \"\", \"url\": TEST_URL, \"is_meta\": False})\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n # Malformatted URL (TODO)\n # response = self.create_puzzle(\n # {\"name\": \"test name\", \"url\": \"bad_url\", \"is_meta\": False}\n # )\n # self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n self.assertEqual(Puzzle.objects.count(), 0)\n\n def test_create_puzzle(self):\n response = self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n puzzle = Puzzle.objects.get()\n self.assertEqual(\n response.data,\n {\n \"id\": puzzle.pk,\n \"name\": puzzle.name,\n \"hunt_id\": self._hunt.pk,\n \"url\": TEST_URL,\n \"notes\": \"\",\n \"has_sheet\": False,\n \"chat_room\": None,\n \"status\": \"SOLVING\",\n \"tags\": [],\n \"guesses\": [],\n \"metas\": [],\n \"feeders\": [],\n \"is_meta\": False,\n },\n )\n\n def test_delete_puzzle(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n response = self.delete_puzzle(puzzle.pk)\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data, {})\n self.assertEqual(Puzzle.objects.count(), 0)\n\n def test_edit_puzzle(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n\n response = self.edit_puzzle(puzzle.pk, {\"name\": \"new name\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"name\"], \"new name\")\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.name, \"new name\")\n\n response = self.edit_puzzle(puzzle.pk, {\"url\": \"https://newurl.test/\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"url\"], \"https://newurl.test/\")\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.url, \"https://newurl.test/\")\n\n response = self.edit_puzzle(puzzle.pk, {\"is_meta\": True})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"is_meta\"], True)\n self.assertEqual(len(response.data[\"tags\"]), 1)\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.is_meta, True)\n\n def test_list_puzzles(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n self.create_puzzle({\"name\": \"second test\", \"url\": \"https://secondtest.test/\"})\n self.assertEqual(Puzzle.objects.count(), 2)\n response = self.list_puzzles()\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(response.data), 2)\n self.assertEqual(\n {p[\"name\"] for p in response.data}, {\"test name\", \"second test\"}\n )\n\n def test_add_answer(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n\n response = self.create_answer(puzzle.pk, {\"text\": \"ans\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n # This assumes no answer queue\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.correct_answers(), [\"ANS\"])\n self.assertEqual(puzzle.status, Puzzle.SOLVED)\n\n response = self.create_answer(puzzle.pk, {\"text\": \"ans\"})\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n response = self.create_answer(puzzle.pk, {\"text\": \"\"})\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n response = self.create_answer(puzzle.pk, {\"text\": \"answer two\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.correct_answers(), [\"ANS\", \"ANSWERTWO\"])\n\n def test_delete_answer(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n\n self.create_answer(puzzle.pk, {\"text\": \"ANSWER\"})\n self.create_answer(puzzle.pk, {\"text\": \"ANSWER TWO\"})\n\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.status, Puzzle.SOLVED)\n self.assertEqual(len(puzzle.correct_answers()), 2)\n guesses = list(puzzle.guesses.all())\n\n response = self.delete_answer(puzzle.pk, guesses[0].pk)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.status, Puzzle.SOLVED)\n self.assertEqual(len(puzzle.correct_answers()), 1)\n\n response = self.delete_answer(puzzle.pk, guesses[1].pk)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n puzzle.refresh_from_db()\n self.assertEqual(puzzle.status, Puzzle.SOLVING)\n self.assertEqual(len(puzzle.correct_answers()), 0)\n\n def test_edit_answer(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n\n self.create_answer(puzzle.pk, {\"text\": \"ANSWER\"})\n answer = puzzle.guesses.get()\n\n response = self.edit_answer(puzzle.pk, answer.pk, {\"text\": \"oops real answer\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n answer.refresh_from_db()\n self.assertEqual(answer.text, \"OOPSREALANSWER\")\n\n def test_create_tag(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n\n response = self.create_tag(\n puzzle.pk, {\"name\": \"taggy\", \"color\": PuzzleTag.BLUE}\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(puzzle.tags.count(), 1)\n # Should return a puzzle\n self.assertEqual(response.data[0][\"name\"], puzzle.name)\n\n def test_delete_tag(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n self.create_tag(puzzle.pk, {\"name\": \"taggy\", \"color\": PuzzleTag.BLUE})\n self.assertEqual(puzzle.tags.count(), 1)\n tag = puzzle.tags.get()\n\n response = self.delete_tag(puzzle.pk, tag.pk)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(puzzle.tags.count(), 0)\n\n def test_opposing_tags(self):\n self.create_puzzle({\"name\": \"test name\", \"url\": TEST_URL})\n puzzle = Puzzle.objects.get()\n self.create_tag(puzzle.pk, {\"name\": \"HIGH PRIORITY\", \"color\": PuzzleTag.RED})\n self.assertEqual(puzzle.tags.count(), 1)\n tag = puzzle.tags.get()\n\n response = self.create_tag(\n puzzle.pk, {\"name\": \"LOW PRIORITY\", \"color\": PuzzleTag.YELLOW}\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n # Should still have only 1 tag.\n self.assertEqual(puzzle.tags.count(), 1)\n self.assertEqual(puzzle.tags.all()[0].name, \"LOW PRIORITY\")\n # Should return a puzzle\n self.assertEqual(response.data[0][\"name\"], puzzle.name)\n","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"616141300","text":"# -*- coding:utf-8 -*- \n__author__ = 'John 2017/12/13 9:52'\n\"\"\"\n网格路径\n从一个2×2方阵的左上角出发,只允许向右或向下移动,则恰好有6条通往右下角的路径。\n\n\n对于20×20方阵来说,这样的路径有多少条?\n\"\"\"\n\n\ndef func(n):\n L = [1] * n\n for i in range(n):\n for j in range(i):\n L[j] = L[j] + L[j-1]\n L[i] = 2 * L[i-1]\n return L[n-1]\n\n\nprint(func(20))","sub_path":"欧若拉计划/Problem15.py","file_name":"Problem15.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"374903739","text":"import threading\nimport time\nimport os\nimport sys\nfrom datetime import datetime\n\ndef timer(sleep_time):\n # sleep\n time.sleep(int(sleep_time)/1000)\n os._exit(1)\n\ndef fib(n):\n if n<0:\n print(\"Incorrect input\")\n # First Fibonacci number is 0\n elif n==1:\n return 0\n # Second Fibonacci number is 1\n elif n==2:\n return 1\n else:\n return fib(n-1)+fib(n-2)\n\ndef f(n):\n \"\"\"\n f = open(\"/proc/{pid}/stat\".format(pid=os.getpid()), 'r')\n cpu = f.read().split()[-14]\n f.close()\n \"\"\"\n #cpu = open(\"/proc/{pid}/stat\".format(pid=os.getpid()), 'r').read().split()[-14]\n start = round(time.time(),6)\n #sleep_time = args.get(\"time\",\"50\")\n n = int(n)\n #thread = threading.Thread(target=timer,args=(sleep_time,))\n #thread.start()\n result = fib(int(n))\n #thread.join()\n end = round(time.time(),6)\n\nif __name__ == \"__main__\":\n event = sys.argv[1]\n f(event)\n","sub_path":"SFS-port-OpenLambda/openlambda/default-ol/registry/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"84557356","text":"# osetattr = object.__setattr__\r\n# ogetattr = object.__getattr__\r\nimport sys\r\n\r\nfrom collections import defaultdict, Iterable\r\n\r\nclass Storage(dict):\r\n '''\r\n This is a god-awful way to do pseudo-superclassing\r\n of attributes. That is, with\r\n class A:\r\n x = Attribute()\r\n class B(A):\r\n x = Attribute()\r\n B.x._storage pretends to be a subclass of sorts of A.x._storage.\r\n '''\r\n\r\n # These make it so that you can do JavaScript-style\r\n # dot notation access of elements inside an ordinary\r\n # dictionary.\r\n __getattr__ = dict.__getitem__\r\n __setattr__ = dict.__setitem__\r\n __delattr__ = dict.__delitem__\r\n\r\n def __init__(self, attribute):\r\n super().__init__()\r\n self.attr = attribute\r\n\r\n def __missing__(self, key):\r\n '''\r\n If the key is missing from this storage,\r\n go to the enclosing attribute's class,\r\n go up to the next Node class,\r\n go into the corresponding attribute,\r\n ask its storage.\r\n Which may have to ask the next one up\r\n in turn, etc.\r\n Yayyy.\r\n '''\r\n for superclass in self.attr._storage.cls.__mro__[1:]:\r\n if issubclass(superclass, Node):\r\n superattr = getattr(superclass,\r\n self.attr._storage.name)\r\n return superattr._storage[key]\r\n return None\r\n\r\nclass NodeMetaDict(dict):\r\n '''\r\n Keeps track of the order and names\r\n of variables referenced, so you can do\r\n class A(Node):\r\n a\r\n b\r\n '''\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(self, *args, **kwargs)\r\n self.list = []\r\n def __getitem__(self, key):\r\n if not key.startswith('__'):\r\n self.list.append(key)\r\n return None\r\n else:\r\n return super().__getitem__(key)\r\n\r\nclass NodeMeta(type):\r\n '''\r\n Conceptually, the type of the Node object,\r\n as opposed to Node instances (which are of type Node.)\r\n '''\r\n def __new__(mcls, name, bases, nmdict, **kwargs):\r\n '''\r\n Setup the children based on the class definition.\r\n '''\r\n children = nmdict.list\r\n namespace = dict(nmdict)\r\n namespace['_childNames'] = children\r\n childProxies = []\r\n for c in children:\r\n proxy = ChildProxy(c)\r\n namespace[c] = proxy\r\n childProxies.append(proxy)\r\n klass = super().__new__(mcls, name, bases, namespace)\r\n for c in childProxies:\r\n c._storage.cls = klass\r\n klass._remote_modifiers = defaultdict(set)\r\n return klass\r\n\r\n def __getattribute__(cls, attr):\r\n '''Create proxies as necessary when accessed.'''\r\n if attr.startswith('__') or attr in cls.__dict__:\r\n return super().__getattribute__(attr)\r\n if attr == 'rewrite':\r\n newattr = RewriteProxy(cls)\r\n else:\r\n newattr = AttributeProxy(attr, cls)\r\n setattr(cls, attr, newattr)\r\n return newattr\r\n\r\n @classmethod\r\n def __prepare__(metacls, names, bases, **kwargs):\r\n '''Use the NodeMetaDict instead of the normal local namespace\r\n when creating a Node class.'''\r\n return NodeMetaDict()\r\n\r\ndef rewrite(node):\r\n '''\r\n Rewrite a node until it is satisfied\r\n with its lot in life.\r\n '''\r\n while isinstance(node, Node):\r\n rewritten = node.rewrite\r\n if rewritten is node:\r\n break\r\n node = rewritten\r\n return node\r\n\r\ndef iterNodes(nodes):\r\n '''\r\n Since collections of nodes are\r\n supported as children, it's a common\r\n task to iterate through potentially\r\n one level of iterators.\r\n '''\r\n for n in nodes:\r\n if isinstance(n, Node):\r\n n = rewrite(n)\r\n if isinstance(n, Node):\r\n yield n\r\n if isinstance(n, Iterable) and not isinstance(n, Node):\r\n for n in n:\r\n if isinstance(n, Node):\r\n n = rewrite(n)\r\n if isinstance(n, Node):\r\n yield n\r\n\r\nclass NodeSuper:\r\n '''\r\n This super class is mixed into Node,\r\n so I don't have to worry about the NodeMeta\r\n class doing weird things while I define\r\n these couple normal functions.\r\n '''\r\n def __init__(self, *args, **kwargs):\r\n self.parent = None\r\n # GLOBAL ROOT\r\n # if global_root is not None:\r\n # global_root._children.append(self)\r\n\r\n '''\r\n Terrible implementation of a custom function\r\n signature based on the children declared.\r\n '''\r\n assert len(args) <= len(self._childNames)\r\n assert all(c in self._childNames for c in kwargs)\r\n for c, a in zip(self._childNames, args):\r\n assert c not in kwargs\r\n kwargs[c] = a\r\n assert all(c in kwargs for c in self._childNames)\r\n for c, a in kwargs.items():\r\n if isinstance(a, Node):\r\n a.parent = self\r\n elif isinstance(a, Iterable):\r\n for n in a:\r\n if isinstance(n, Node):\r\n n.parent = self\r\n setattr(self, c, a)\r\n\r\n @property\r\n def children(self):\r\n yield from iterNodes(getattr(self, c) for c in self._childNames)\r\n\r\n def _remote_modify(self, node, attr, value = None, ignore = None):\r\n '''\r\n Apply remote changes corresponding to node.attr.\r\n '''\r\n if ignore is None:\r\n ignore = set()\r\n if self in ignore:\r\n return value\r\n ignore.add(self)\r\n for modifier in self._remote_modifiers[attr]:\r\n val = modifier._remote_modify(node, self, value)\r\n value = val if val is not None else value\r\n for child in self.children:\r\n if isinstance(child, Node):\r\n value = child._remote_modify(node, attr, value, ignore)\r\n return value\r\n\r\n def __getattr__(self, attr):\r\n getattr(type(self), attr)\r\n return getattr(self, attr)\r\n\r\nclass Node(NodeSuper, metaclass = NodeMeta): pass\r\n\r\nclass Proxy:\r\n '''\r\n _storage is used to avoid polluting the namespace,\r\n and also to help chain the attributes of\r\n subclasses together.\r\n '''\r\n def __init__(self, name, cls = None):\r\n self._storage = Storage(self)\r\n self._storage.name = name\r\n self._storage.cls = cls\r\n\r\n def __getattr__(self, attr):\r\n '''\r\n Returns a proxy that represents\r\n an inherited or collection attribute on\r\n the node that THIS attribute supposedly\r\n sets\r\n '''\r\n return SubAttributeProxy(attr, self, self._storage.cls)\r\n\r\nclass ChildProxy(Proxy):\r\n '''\r\n When a child is accessed, first check if\r\n it wants to rewrite itself. That's\r\n why this proxy exists.\r\n '''\r\n def __init__(self, name, cls = None):\r\n super().__init__(name, cls)\r\n self._storage.child = {}\r\n\r\n def __get__(self, obj, owner=None):\r\n if obj is None:\r\n return self\r\n child = self._storage.child[obj]\r\n child = self._storage.child[obj] = rewrite(child)\r\n return child\r\n\r\n def __set__(self, obj, value):\r\n self._storage.child[obj] = value\r\n\r\nclass AttributeProxy(Proxy):\r\n '''\r\n The implementation of attributes.\r\n '''\r\n def __init__(self, name, cls):\r\n super().__init__(name, cls)\r\n self._storage.value = {}\r\n self._storage.computing = defaultdict(bool)\r\n self._storage.computed = defaultdict(bool)\r\n self._storage.circular = defaultdict(bool)\r\n\r\n # Now these are kept undefined.\r\n # Setting them to None explicitly\r\n # prevents them from checking up\r\n # the next level to see if the superclass\r\n # defines a property of this attribute.\r\n #self._storage.compute = None\r\n #self._storage.initial = None\r\n\r\n def __get__(self, obj, owner=None):\r\n if obj is None:\r\n return self\r\n '''\r\n If currently computing,\r\n expects to have a value\r\n returns it\r\n First, creates an initial value if there is one.\r\n Sets \"computing\" flag.\r\n Runs equation, gets result.\r\n Sets it.\r\n '''\r\n import sys\r\n #print(\"1\", self._storage.name, file=sys.stderr)\r\n # If cached, just used that value.\r\n if self._storage.computed[obj]:\r\n return self._storage.value[obj]\r\n\r\n #print(\"2\", file=sys.stderr)\r\n # If currently computing the value, we've\r\n # got a circular dependency.\r\n if self._storage.computing[obj]:\r\n self._storage.circular[obj] = True\r\n # We expect to have an initial value so that\r\n # we can do fixedpoint iteration to resolve the\r\n # circular dependency.\r\n assert obj in self._storage.value, \"Circular evaluation of {} without an initial value, or circular initial value!\".format(self._storage.name)\r\n return self._storage.value[obj]\r\n\r\n #print(\"3\", file=sys.stderr)\r\n # Starting to compute.\r\n self._storage.computing[obj] = True\r\n\r\n #print(\"4\", file=sys.stderr)\r\n # Get an initial value, if applicable.\r\n # Mostly used for circular dependencies and\r\n # remotes.\r\n if self._storage.initial is not None:\r\n self._storage.value[obj] = self._storage.initial(obj)\r\n\r\n # Actually compute the value,\r\n # doing fixedpoint iteration if it's circularly\r\n # dependent.\r\n if self._storage.compute is not None:\r\n value = self._storage.compute(obj)\r\n if self._storage.circular[obj]:\r\n while value != self._storage.value[obj]:\r\n self._storage.value[obj] = value\r\n value = self._storage.compute(obj)\r\n self._storage.value[obj] = value\r\n\r\n # If there is no compute function for this\r\n # attribute, then we consider it to be remote:\r\n # that is, it gets its value from other nodes\r\n # on the AST.\r\n else:\r\n value = self._storage.value.get(obj, None)\r\n self._storage.value[obj] = obj.root._remote_modify(\r\n obj, self._storage.name, value)\r\n self._storage.computed[obj]\r\n\r\n self._storage.computing[obj] = False\r\n self._storage.computed[obj] = True\r\n return self._storage.value[obj]\r\n\r\n def __set__(self, obj, value):\r\n # If we're directly setting...\r\n # Well, just accept it.\r\n self._storage.value[obj] = value\r\n self._storage.computed[obj] = True\r\n\r\n def __call__(self, func=None, initial=None):\r\n '''\r\n Sets something about this attribute.\r\n '''\r\n for key, func in [\r\n ('compute', func),\r\n ('initial', initial)\r\n ]:\r\n if func is not None:\r\n self._storage[key] = func\r\n # Allow chaining\r\n return self\r\n\r\nclass RewriteProxy(Proxy):\r\n '''\r\n A special proxy for the rewrite attribute.\r\n It's different because you can have multiple\r\n separate rewrite functions.\r\n '''\r\n def __init__(self, cls):\r\n super().__init__('rewrite', cls)\r\n self._storage.rewriters = []\r\n self._storage.rewritten = {}\r\n\r\n def __call__(self, rewriter):\r\n self._storage.rewriters.append(rewriter)\r\n\r\n def __get__(self, obj, owner = None):\r\n if obj is None:\r\n return self\r\n if obj in self._storage.rewritten:\r\n return self._storage.rewritten[obj]\r\n for rewriter in self._storage.rewriters:\r\n result = rewriter(obj)\r\n if result is not None:\r\n rewritten = result\r\n break\r\n else:\r\n rewritten = obj\r\n self._storage.rewritten[obj] = rewritten\r\n return rewritten\r\n\r\nclass SubAttributeProxy(Proxy):\r\n '''\r\n SubAttributes dispatch remote evaluation declarations\r\n such as\r\n @A.child.friend.mother.hat\r\n def itsPink(a):\r\n ...\r\n A: Node\r\n child: Attribute\r\n friend: SubAttribute\r\n mother: SubAttribute\r\n hat: SubAttribute\r\n '''\r\n def __init__(self, name, parent, cls):\r\n super().__init__(name, cls)\r\n self._storage.parent = parent\r\n\r\n def __call__(self, func):\r\n self._storage.func = func\r\n self._storage.cls._remote_modifiers[\r\n self._storage.name].add(self)\r\n\r\n def _remote_modify(self, node, modifier_node, val=None):\r\n parent = self._get_parent(modifier_node)\r\n # print(\"Modify match:\", parent, node, id(parent), id(node))\r\n if parent is node or isinstance(parent, Iterable) and node in parent:\r\n v = self._storage.func(modifier_node, val)\r\n return v if v is not None else val #return None\r\n else:\r\n return None\r\n\r\n def _get_parent(self, obj):\r\n return self._storage.parent.__get__(obj, self._storage.cls)\r\n\r\n def __get__(self, obj, owner=None):\r\n if obj is None:\r\n return self\r\n parent = self._get_parent(obj)\r\n return getattr(parent, self._storage.name)\r\n\r\n\r\nclass Root(Node):\r\n _children\r\n\r\n# GLOBAL ROOT\r\n# global_root is an odd idea,\r\n# which is that sometimes every\r\n# node that a person ever creates\r\n# is significant.\r\n# That's often true in examples;\r\n# but less true in practice.\r\n# So this is disabled for now!\r\n# There is also some disabled code\r\n#global_root = None\r\n#global_root = Root([])\r\n\r\n# Look, I got to use my DSL in my DSL!\r\n@Node.root\r\ndef root(node):\r\n if node.parent is None:\r\n return Root(node) #global_root\r\n else:\r\n return node.parent.root\r\n","sub_path":"final/underlang.py","file_name":"underlang.py","file_ext":"py","file_size_in_byte":13841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"427361093","text":"from digi.xbee.devices import XBeeDevice\nimport digi\nimport sys\n\ndevice = XBeeDevice(\"COM6\", 9600)\ndevice.open()\n\nexit = False\n\nwhile not exit:\n next = input('Enter Message: ')\n if next == 'exit':\n exit = True\n try:\n device.send_data_broadcast(next)\n except digi.xbee.exception.TimeoutException:\n print (\"Failed to send\")\n\ndevice.close()","sub_path":"digittest.py","file_name":"digittest.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"653397975","text":"import os\r\nimport hashlib\r\nimport subprocess\r\nimport re\r\nimport shutil\r\nimport pandas as pd\r\nimport zipfile\r\nimport datetime\r\nimport time\r\nimport json\r\n\r\nexcel_sheet = pd.read_excel(os.path.join(os.getcwd()+\"/JO_2020.xlsx\"), sheet_name=None, engine=\"openpyxl\")\r\nmatches = dict()\r\nmatches[\"matches\"] = []\r\nmatch = dict()\r\nfor sheet in excel_sheet:\r\n equipe_ventriglisse = []\r\n if \"ventriglisse\" in sheet:\r\n print(type(excel_sheet[sheet]))\r\n for row in excel_sheet[sheet]:\r\n print(str(row))\r\n if \"equipe\" in str(row):\r\n equipe_ventriglisse.append(str(row))\r\n arbitre = str(excel_sheet[sheet].loc[:,\"arbitre\"], encoding=\"utf-16\").replace(\"NaN\",\"\").replace(\"\\n\",\"/\").replace(\" \",\"\").replace(\"/ /\",\"\")[:-2]\r\n for index,equipe in enumerate(equipe_ventriglisse):\r\n print(equipe)\r\n # team = \"\"\r\n team = str(excel_sheet[sheet].loc[:,equipe], encoding=\"utf-16\").replace(\"NaN\",\"\").replace(\"\\n\",\"/\").replace(\" \",\"\")\r\n equipe_ventriglisse[index]=team\r\n\r\n for i in range(0, len(equipe_ventriglisse), 2):\r\n match[\"match\"] = index\r\n match[\"team1\"] = equipe_ventriglisse[i]\r\n match[\"team2\"] = equipe_ventriglisse[i+1]\r\n match[\"score\"] = \"0:0\"\r\n match[\"over\"] = 0\r\n match[\"level\"] = 0\r\n matches[\"matches\"].append(match)\r\n matches[\"levels\"] = 1\r\n test = open(\"ventriglisse_match.json\",\"w\")\r\n json.dump(matches, test)\r\n # print(excel_sheet[sheet].loc[:,equipe].to_string(index=False))\r\n","sub_path":"JO_parser.py","file_name":"JO_parser.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"278899884","text":"\"\"\"\n------------------------------------------------------------------------------.\n\nconfigProxy.py is a library to get all the changing parameter of the wall-e.\n\n-------------------------------------------------------------------------------\n\"\"\"\nimport yaml\npath_to_file = \"/home/pi/SmartHome/manager/setting/config.yml\"\nwith open(path_to_file, 'r') as stream:\n try:\n config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n\n\ndef getIp():\n \"\"\"Get the local IP adress of the wall-e.\"\"\"\n return config[\"ip_adress\"]\n\n\ndef getPort():\n \"\"\"Get the local port adress for the behavior manager of the wall-e.\"\"\"\n return config[\"port\"]\n","sub_path":"manager/setting/configProxy.py","file_name":"configProxy.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"402947424","text":"import string\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--filename\", type=str,\n help=\"finename\")\nparser.add_argument(\"-c\", \"--connector\", type=str,\n help=\"connector\")\nparser.add_argument(\"-s\", \"--string\", type=str,\n help=\"string to tokenize\")\n\nargs = parser.parse_args()\n\nconnector = args.connector\nfilename = args.filename\ns = args.string\n\ntokens = s.split()\n\nwith open(filename, \"a+\") as f:\n\tf.write(connector.join(tokens)+\"\\n\")\n\n","sub_path":"dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"508544305","text":"import sys\nfrom Dicos import Dicos\nfrom Mcd import Mcd\n\nif len(sys.argv) < 4:\n print('usage:', sys.argv[0], 'mcf_file mcd_file dico_file')\n exit(1)\n\nmcfFileName = sys.argv[1]\nmcdFileName = sys.argv[2]\ndicoFileName = sys.argv[3]\n\nmcd = Mcd(mcdFileName)\n\nprint('populating dicos from file ', mcfFileName)\ndicos = Dicos(mcd)\ndicos.populateFromMcfFile(mcfFileName, mcd, verbose=False)\nprint('saving dicos in file ', dicoFileName)\ndicos.printToFile(dicoFileName)\n","sub_path":"src/create_dicos.py","file_name":"create_dicos.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"465500671","text":"from fastapi import status\nfrom util import rsa_util,snowflakeutil,qrcode_utils, sys_rsa_util\nfrom common import docking_util,sendRsaData\nfrom fastapi.responses import JSONResponse\nfrom logger import logger\nfrom set_path_config import *\nfrom order.dao import order_dao\nfrom urllib import parse\nimport requests\nfrom application.dao import application_dao\nimport json\n\ndef add_order(app):\n logger.info(\"--------------------------添加订单信息-----------------------------\")\n # 验证是否能对接,解密订单信息\n order_dict = docking_util.DockingVerification(app)\n #生成本系统的订单id可以作为二维码名称/path\n sys_order_id = str(snowflakeutil.IdWorker(1,2).get_id())\n qrcode_path = \"static/\"+sys_order_id + \".png\"\n # 将订单填入数据库\n # 如果传入的子订单的金额加起来与主订单总金额不相等\n param_brank_details = order_dict[\"brank_detail\"]\n sum_good_price = 0\n for brank_detail in param_brank_details:\n for order_detail in brank_detail[\"order_detail\"]:\n sum_good_price += float(order_detail[\"price\"])\n if sum_good_price != float(order_dict[\"total_money\"]):\n logger.error(\"(erro):子订单价格总和与主订单金额不符合\")\n return \"子订单价格总和与主订单金额不符合\"\n mes = order_dao.add_order(order_dict,sys_order_id,qrcode_path)\n if mes != \"添加失败\":\n if mes == \"不能添加同一订单\":\n mes_info = {\"info\": \"不能添加同一订单\"}\n rsa_data = sendRsaData.rsa_data(order_dict[\"application_id\"],mes_info)\n return rsa_data\n logger.info(\"--------------------------调用支付接口-----------------------------\")\n pay_url= order_pay(order_dict,mes[\"order_detail_ids\"],mes[\"creat_time\"],order_dict[\"application_id\"])\n # 使用系统的公钥加密数据发回到回调地址\n mes_info = {\"sys_order_id\":mes[\"sys_order_id\"],\"data\":pay_url}\n rsa_data = sendRsaData.rsa_data(order_dict[\"application_id\"],mes_info)\n if pay_url.startswith(\"http://pay.52yaxin.com\"):\n # 生成订单二维码\n qrcode_utils.creat_qrcode_util(\"https://192.168.0.114:/#/orders/\" + sys_order_id, qrcode_path)\n logger.info(\"(14).生成二维码订单:\" + qrcode_path)\n return rsa_data\n mes_info = {\"info\": \"支付失败\"}\n rsa_data = sendRsaData.rsa_data(order_dict[\"application_id\"], mes_info)\n return rsa_data\n\n\ndef get_orders(page,pre_page,is_order_by,filter_mes):\n pagination = order_dao.get_orders(page,pre_page,is_order_by,filter_mes)\n return pagination\n\n\ndef get_order_id(app):\n order_dict = docking_util.Frond_DockingVerification(app)\n order_id = order_dict[\"order_id\"]\n param_application_id = app.application_id\n order_info = order_dao.get_order_id(param_application_id,order_id)\n if order_info != None:\n init_order_dict = {\"sys_order_id\": order_info.sys_order_id,\n \"order_id\": order_info.order_id,\n \"pay_mode\": order_info.pay_mode,\n \"transtype\": order_info.transtype,\n \"total_money\": order_info.total_money,\n \"qrcode_path\": order_info.qrcode_path,\n \"order_ip\": order_info.order_ip,\n \"application_id\": order_info.application_id,\n \"notifyurl\": order_info.notifyurl,\n \"status\": order_info.status,\n \"creat_time\": order_info.creat_time,\n \"pay_time\": order_info.pay_time}\n rsa_success_data = sendRsaData.Frond_rsa_data(init_order_dict)\n return rsa_success_data\n mes_info = {\"data\":\"\", \"info\": \"未查询到订单信息\"}\n rsa_error_data = sendRsaData.Frond_rsa_data(mes_info)\n return rsa_error_data\n# 一马陷足淤泥内,老畜生怎样出蹄 一人跩绳马蹄上,王公子这样答题,\n# 小马不服人上坐,小鞭一出应声啼,此啼皆因不服气,\ndef order_pay(order_dict,order_detail_ids,creat_time,application_id):\n url = 'http://47.95.254.69:8080/payinterface/index.do'\n #验证是否能对接,解密订单信息 3\n # order_dict = docking_util.Frond_DockingVerification(app)\n branklist = []\n orderlist = []\n for brank_info in order_dict[\"brank_detail\"]:\n for index,order_info in enumerate(brank_info[\"order_detail\"]):\n order_data = {\n \"title\": order_info[\"good_title\"],\n \"shopid\": order_info[\"good_id\"],\n \"categoryname\": order_info[\"category\"],\n \"price\": int(float(order_info[\"price\"])*100),\n \"suborderid\": order_detail_ids[index],\n \"remark1\": \"备注1\",\n \"remark2\": \"备注2\"\n }\n orderlist.append(order_data)\n for brank_info in order_dict[\"brank_detail\"]:\n brank_data = {\n \"banknumber\": brank_info[\"brank_number\"],\n \"numbername\": brank_info[\"brank_number_name\"],\n \"remark1\": \"备注1\",\n \"remark2\": \"备注2\",\n \"detaillist\": orderlist\n }\n branklist.append(brank_data)\n data = json.dumps({\n \"ordernumber\":order_dict[\"order_id\"],\n \"ordertime\":str(creat_time),\n \"merid\":os.environ.get(\"MERID\"),\n \"paytype\":\"alipay\",\n \"transtype\":\"0000\",\n \"signmethon\":\"RSA\",\n \"charset\":\"utf8\",\n \"notifyurl\":os.environ.get(\"NOTIFYURL\"),\n \"backurl\": os.environ.get(\"BACKURL\"),\n \"customerip\": \"192.168.0.114\",\n \"amount\":int(float(order_dict[\"total_money\"])*100),\n \"remark1\": \"备⽤1\",\n \"remark2\": \"备⽤2\",\n \"remark3\": \"备⽤3\",\n \"remark4\": \"备⽤4\",\n \"remark5\": \"备⽤5\",\n \"remark6\": \"备⽤6 \",\n \"remark7\": \"备⽤7\",\n \"remark8\": \"备⽤8\",\n \"remark9\": \"备⽤9\",\n \"remark10\": \"备⽤10\",\n \"remark11\": \"备⽤11\",\n \"remark12\": \"备⽤12\",\n \"datalist\":branklist\n })\n logger.info(\"(9).拼接支付接口的json字符串:\"+data)\n logger.info(\"(10).实例化支付系统的公钥,私钥\")\n rsa_ = rsa_util.RsaUtil('rsa_key/orderPay_private_key.pem', 'rsa_key/orderPay_public_key.pem')\n logger.info(\"(11).对json参数进行加密\")\n encrypt = rsa_.public_long_encrypt(data) # 对json参数进行加密\n result = str(encrypt, encoding=\"utf8\")\n key = os.environ.get(\"MER_KEY\")\n sign = rsa_.sign(result,key)\n logger.info(\"(12).生成签名:\"+sign)\n HEADERS = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}\n FormData = {\"result\": result, \"sign\": sign.upper(), \"merid\": \"1CC92CF3C585AF4DE2609EFFE69A21CD\"}\n data = parse.urlencode(FormData)\n content = requests.post(url=url, headers=HEADERS, data=data).text\n if content.startswith(\"http://pay.52yaxin.com\"):\n logger.info(\"(13).调用支付接口成功返回支付地址:\"+content)\n return content\n #没有调用成功支付接口需要删除订单信息\n logger.info(\"(error).没有调用成功支付接口需要删除订单信息:\")\n order_dao.delete_error_order(order_dict[\"order_id\"],application_id)\n return content\n\ndef call_back(result,sign):\n # 对加密数据进行处理\n # 读取公钥,私钥\n # 实例化公钥,私钥\n logger.info(\"(1).实例化支付接口的公钥,私钥\")\n rsa_ = rsa_util.RsaUtil('rsa_key/rsa_private_key.pem', 'rsa_key/rsa_public_key.pem')\n logger.info(\"(2).对签名进行验证签名信息:\" + str(sign))\n # 对签名进行验证, md5(rsa(json)+key),与支付接口定义好的key\n key = os.environ.get(\"MER_KEY\")\n sys_sign = rsa_.sign(result, key)\n if sys_sign != sign:\n logger.error(\"(2.1).签名有误:系统签名:\" + str(sys_sign) + \",支付接口签名:\" + str(sign))\n return JSONResponse(str(\"签名不一致\"), status_code=status.HTTP_417_EXPECTATION_FAILED)\n # 解密数据信息\n json_data = rsa_.private_long_decrypt(result)\n logger.info(\"(3).解密数据信息:\" + str(json_data))\n # 对json数据做处理\n order_dict = json.loads(json_data)\n logger.info(\"(4).修改订单的状态\")\n if order_dict[\"status\"] == \"0\":\n #支付成功\n #用本系统公钥加密发送给回调地址的接口, 返回的信息status = 1\n #支付成功\n # 修改订单的状态改为支付成功\n logger.info(\"(4.1).修改订单的状态改为支付成功\")\n order_info = order_dao.call_back_success(order_dict[\"ordernumber\"],order_dict[\"timestamp\"])\n else:\n # 支付失败\n # 修改订单的状态改为支付失败status = 2\n logger.info(\"(4.2).解密数据信息:\" + str(json_data))\n order_info = order_dao.call_back_error(order_dict[\"ordernumber\"])\n init_order_dict = {\"sys_order_id\": order_info.sys_order_id,\n \"order_id\": order_info.order_id,\n \"pay_mode\": order_info.pay_mode,\n \"transtype\": order_info.transtype,\n \"total_money\": order_info.total_money,\n \"qrcode_path\": order_info.qrcode_path,\n \"order_ip\": order_info.order_ip,\n \"application_id\": order_info.application_id,\n \"notifyurl\": order_info.notifyurl,\n \"status\": order_info.status,\n \"creat_time\": order_info.creat_time,\n \"pay_time\": order_info.pay_time}\n #使用系统的公钥加密数据发回到回调地址\n sendRsaData.send_rsa_data(order_dict[\"ordernumber\"],init_order_dict)\n\n\n","sub_path":"order_transaction/order/service/order_service.py","file_name":"order_service.py","file_ext":"py","file_size_in_byte":9782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"378135368","text":"__author__ = 'V631932'\n\nimport pandas as pd\nimport glob\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#########NEXT SECTION IS ABOUT OWM MODULE\nfrom .DatafileFormated import DatafileFormated\nfrom .ChartPortraitsWriter import chart_portraits\nfrom .narrative_support import get_file_narratives\n\nclass chart_narrative:\n\n def __init__(self, prdatafile_list, prtagfile_list, percentile_dict_path):\n\n #self.prdatafile_path = prdatafile_path\n #self.prtagfile_path = prtagfile_path\n #self.alldatafiles = glob.glob(os.path.join(prdatafile_path, \"**\", \"*.csv\"), recursive=True)\n #self.alltagfiles = glob.glob(os.path.join(prtagfile_path, \"**\", \"*.csv\"), recursive=True)\n #self.allfilenames = [x.split('\\\\')[-1] for x in self.alltagfiles]\n self.prdatafile_list = prdatafile_list\n self.prtagfile_list = prtagfile_list\n self.cp = chart_portraits(percentile_dict_path)\n self.chart_summary_df = None\n\n def get_chart_summary(self):\n\n #for i, filename in enumerate(self.allfilenames):\n for df, tf, filenames in zip(self.prdatafile_list.values(), self.prtagfile_list.values(), self.prdatafile_list.keys()):\n \n narrative_point = list(tf['Narrative_element'])[0]\n datafile = df\n chart_name = filenames \n\n datafileFormated = DatafileFormated(datafile, chart_name)\n\n if 'MAX' in narrative_point:\n self.cp.max_portrait(datafileFormated)\n if 'MIN' in narrative_point:\n self.cp.min_portrait(datafileFormated)\n if 'CORR' in narrative_point:\n self.cp.corr_portrait(datafileFormated)\n if 'SMO' in narrative_point:\n self.cp.SMO_portrait(datafileFormated)\n if 'MONO INTERVAL' in narrative_point:\n self.cp.Interval_portrait(datafileFormated)\n if 'STD' in narrative_point:\n self.cp.std_portrait(datafileFormated)\n if 'SLOPE' in narrative_point:\n self.cp.slope_portrait(datafileFormated)\n if 'TOP' in narrative_point:\n self.cp.Top_portrait(datafileFormated)\n\n self.chart_summary_df = pd.DataFrame(self.cp.chart_summary)\n\n def get_all_narrative_and_highlights(self):\n self.get_chart_summary()\n #gfn = get_file_narratives(self.chart_summary_df, self.prtagfile_path)\n narrative_highlight_dict = {}\n for filename in self.prdatafile_list.keys():\n #print(filename)\n gfn = get_file_narratives(self.chart_summary_df, self.prdatafile_list, self.prtagfile_list, filename)\n k = filename\n v = {'narrative':gfn.get_narrative(), 'df_highlights':gfn.get_highlight()[0],\n 'narrative_highlights': gfn.get_highlight()[1]}\n narrative_highlight_dict[k] = v\n\n return narrative_highlight_dict","sub_path":"app/libs/ai_lib/chart_narrative.py","file_name":"chart_narrative.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"199562368","text":"from django.core.management.base import BaseCommand\n\nfrom legislators.models import Party\n\n\nclass Command(BaseCommand):\n help = u'Bootstrap the Party model data.'\n\n def handle(self, *args, **kwargs):\n self.stdout.write(u'Bootstrapping parties...')\n\n self.load_party(u'Republican')\n self.load_party(u'Democratic')\n\n def load_party(self, name):\n party, created = Party.objects.get_or_create(\n name=name)\n\n if created:\n self.stdout.write('Successfully created `{}`.'.format(name))\n else:\n self.stderr.write('We tried to create `{}`, but we found it '\n 'in the database! You sure you '\n 'wanted to do this?'.format(name))\n","sub_path":"txlege84/legislators/management/commands/bootstrapparty.py","file_name":"bootstrapparty.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"423480135","text":"import scipy as sp\nimport scipy.stats as si\nfrom numpy import zeros\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Input parameters for Black-Scholes Formula\n # S0: spot price\n # K: strike price\n # H: Barrier\n # T: time to maturity\n # r: interest rate\n # q: rate of continuous dividend paying asset\n # sigma: volatility of underlying asset \n # Nom: Nominal Value\n # CDS: Credit-Default Swap\n # c: Coupon\n \n # n_simulation: number of simulations\n # sp.random.seed: fix random numbers\n\nstock_price_today = 9.15 # stock price at time zero\nT =1. # maturity date (in years)\nn_steps=100 # number of steps\nmu =0.15 # expected annual return \nsigma = 0.2 # volatility (annualized)\n# sp.random.seed(12345) # seed() \nn_simulation = 5 # number of simulations\n\ndt=T/n_steps\nS=np.zeros([n_steps])\nx = range(0, int(n_steps), 1) # range(start, stop, step)\nfor j in range(0, n_simulation):\n S[0]= stock_price_today\nfor i in x[:-1]:\n e=np.random.normal()\n S[i+1]=S[i]+S[i]*(mu-0.5*sigma*sigma)*dt+sigma*S[i]*np.sqrt(dt)*e;\n plt.plot(x, S)\nplt.text(0.2,0.8,'S0='+str(stock_price_today)+',mu='+str(mu)+',sigma='+str(sigma))\nplt.text(0.2,0.76,'T='+str(T)+', steps='+str(int(n_steps)))\nplt.title('Stock price (number of simulations = %d ' % n_simulation +')')\nplt.xlabel('Total number of steps ='+str(int(n_steps)))\nplt.ylabel('stock price')\nplt.show()","sub_path":"Options with Monte Carlo/Simulation_of_stock_price_movements.py","file_name":"Simulation_of_stock_price_movements.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"444638342","text":"class computers:\n\n def __init__(self, cpu, memory):\n self.cpu = cpu\n self.memory = memory\n\n def config(self):\n print(\"Config is: \", self.cpu, self.memory)\n\n\n\ncom1 = computers(\"i5\", \"16gb\")\ncom2 = computers(\"i7\", \"32gb\")\n\ncom1.config()\ncom2.config()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"137791827","text":"# -*- coding: utf-8 -*-\n\n\n#### 7.4 문자열 다루기\nval = 'a,b, guido'\nval.split(',')\n\n# strip(공백문자 제거)\npieces = [x.strip() for x in val.split(',')]\n'+'.join(pieces)\n\n# 부�� 문자열 위치\n'guido' in val\nval.index('a')\nval.find(':') #문자열 없는 경우 -1값 봔환\n\n# 문자열 치환\nval.replace(',','')\n\n## 정규표현식(문자열 패턴 찾기)\nimport re # 패턴 매칭, 치환, 분리 \ntext = \"foo bar\\t baz \\tqux\"\nre.split('\\s+',text) # '\\s+' 하나이상의 공백문자 의미\n\n# 직접 정규표현식 compile\nregex = re.compile('\\s+')\nregex.split(text)\nregex.findall(text) # 모든 패턴의 목록\n\n## e-mail 주소를 검사하는 정규표현식\ntext = \"\"\"Dave dave@google.com\nSteve steve@gmail.com\nRob rob@gmail.com\nRyan ryan@yahoo.com\nCyj cyj9201@naver.com\n\"\"\"\n# Matches any character from a-z or 0-9, Matches exactly one character from a-z but length must be 2~4\n# pattern = 사용자+메일주소\npattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}'\nregex = re.compile(pattern, flags=re.IGNORECASE)\nregex.findall(text)\nm=regex.search(text)\nprint(regex.sub('패턴발견',text)) # 찾은 패턴을 주어진 문자열로 치환\n\n\n","sub_path":"Python Script/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"646842339","text":"import checkpy.tests as t\nimport checkpy.lib as lib\nimport checkpy.assertlib as assertlib\nimport sys\n\n@t.test(0)\ndef correctMijn_random(test):\n\tdef testMethod():\n\t\tmijn_random = lib.getFunction(\"mijn_random\", _fileName)\n\t\tif not assertlib.containsOnly([mijn_random(1,1) for i in range(100)], [1]):\n\t\t\treturn False, \"Huh? a random number between 1 and 1 gives something unexpected\"\n\t\tif not assertlib.containsOnly([mijn_random(0,1) for i in range(100)], [0,1]):\n\t\t\treturn False, \"Huh? a random number between 0 and 1 can become something other than 0 or 1?!\"\n\t\treturn True, \"\"\n\ttest.test = testMethod\n\t\n\ttest.description = lambda : \"mijn_random functions correctly\"\n\ttest.fail = lambda info : str(info)\n\n\n@t.passed(correctMijn_random)\n@t.test(1)\ndef correctVierkant(test):\n\ttest.test = lambda : assertlib.between(lib.getFunction(\"Vierkant\", _fileName)(), 0.45, 0.55)\n\ttest.description = lambda : \"correct distance calculated by Vierkant\"","sub_path":"tests/ns2016/module2/random_getallenTest.py","file_name":"random_getallenTest.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"373578964","text":"# -*- coding: utf-8 -*-\nfrom pdfminer.pdfparser import PDFParser\nfrom pdfminer.pdfdocument import PDFDocument\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.pdfpage import PDFTextExtractionNotAllowed\nfrom pdfminer.pdfinterp import PDFResourceManager\nfrom pdfminer.pdfinterp import PDFPageInterpreter\nfrom pdfminer.pdfdevice import PDFDevice\nfrom pdfminer.layout import *\nfrom pdfminer.converter import PDFPageAggregator\nfrom YoudaoTranslator import *\nimport pyperclip\n\n\ndef get_number_count(s):\n numList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n count = 0\n for i in s:\n if i in numList:\n count += 1\n return count\n\n\ndef translateToText(file_path):\n MIN_BUFFER_SIZE = 3000\n MAX_HEADER_FOOT_LENGTH = 100\n MIN_HEADER_FOOT_NUMBER_COUNT = 5\n\n Path = open(file_path, 'rb')\n Save_name = file_path.split('.pdf')[0] + '.txt'\n # 来创建一个pdf文档分析器\n parser = PDFParser(Path)\n # 创建一个PDF文档对象存储文档结构\n document = PDFDocument(parser)\n # 检查文件是否允许文本提取\n if not document.is_extractable:\n raise PDFTextExtractionNotAllowed\n else:\n # 创建一个PDF资源管理器对象来存储共赏资源\n rsrcmgr = PDFResourceManager()\n # 设定参数进行分析\n laparams = LAParams()\n # 创建一个PDF设备对象\n # device=PDFDevice(rsrcmgr)\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n # 创建一个PDF解释器对象\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n translator = YoudaoTranslator()\n buffer = \"\"\n\n # 处理每一页\n for page in PDFPage.create_pages(document):\n interpreter.process_page(page)\n # 接受该页面的LTPage对象\n layout = device.get_result()\n for x in layout:\n if(isinstance(x, LTTextBoxHorizontal)):\n content = str(x.get_text())\n content = content.replace('-\\n', '').replace('-\\r', '')\n content = content.replace('\\n', ' ').replace('-r', ' ')\n content = content + \"\\n\"\n # Check whether the content is valid\n if content.isspace():\n continue\n if len(content) <= MAX_HEADER_FOOT_LENGTH:\n numberCount = get_number_count(content)\n if numberCount > MIN_HEADER_FOOT_NUMBER_COUNT or numberCount >= len(content) / 2:\n continue\n\n # Add content to buffer\n buffer = buffer + content\n\n # When length is over MIN_BUFFER_SIZE, start to translate\n if len(buffer) > MIN_BUFFER_SIZE:\n #trans_content = youdao_translate(content)\n trans_content = translator.translate(buffer)\n with open(Save_name, 'a', encoding='utf-8') as f:\n #print(\"write:\" + buffer)\n #print(\"trans:\" + trans_content)\n # f.write(buffer)\n f.write(trans_content)\n f.write('\\n')\n buffer = \"\"\n trans_content = translator.translate(buffer)\n with open(Save_name, 'a', encoding='utf-8') as f:\n #print(\"write:\" + buffer)\n #print(\"trans:\" + trans_content)\n # f.write(buffer)\n f.write(trans_content)\n f.write('\\n')\n print(\"Finish translate, store to \", Save_name)\n return Save_name\n","sub_path":"translateToText.py","file_name":"translateToText.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"636640342","text":"# import the required libraries\r\nfrom machine import Pin\r\nfrom math import sqrt\r\nimport utime\r\n\r\n\r\n# steady state error for calibration\r\nerror = 0 # cm (subtracted)\r\n\r\n# speed of sound in air at given temperature\r\ntemperature = float(input(\"Temperature (celcius) : \"))\r\ntemperature += 273.16 # convert to kelvin\r\nSONIC_VELOCITY = sqrt(1.4 * 287 * temperature) # m/s\r\nprint(\"Sonic velocity : \",SONIC_VELOCITY, \" m/s\")\r\nutime.sleep(1)\r\nspeed_in_cm_per_microsecond = SONIC_VELOCITY / 10000\r\n# default : 343 m/s or 0.0343 cm/us at 20 deg celcius.\r\n\r\n\r\n# declare trigger and echo pins\r\ntriggerPin = Pin(16, Pin.OUT)\r\n\r\nechoPin = Pin(17, Pin.IN)\r\n\r\n# function for handling Ultrasonic sensor operation\r\ndef pingSensor():\r\n triggerPin.value(0) # triggerPin.low()\r\n utime.sleep_us(20) # sleep in microseconds for sensor stability\r\n \r\n triggerPin.value(1) # set triggerPin to logic 1 for 10 us\r\n utime.sleep_us(10) # wait for 10 micro-second\r\n \r\n triggerPin.value(0) # set triggerPin to default logic 0\r\n \r\n # mark time when the sensor pin is at low state for \r\n # the last time.\r\n \r\n while echoPin.value() == 0:\r\n start_time = utime.ticks_us()\r\n \r\n # mark time when the sensor pin is at high state for\r\n # the last time\r\n while echoPin.value() == 1:\r\n end_time = utime.ticks_us()\r\n \r\n # get duration in microseconds for ( twice the distance )\r\n # the total distance covered i.e from sensor to object and\r\n # back from object to the sensor\r\n \r\n duration_in_microseconds = end_time - start_time # time in us\r\n \r\n # calculate distance of one side . From sensor to object\r\n # distance = speed * total time / 2\r\n distance_in_cm = (speed_in_cm_per_microsecond * (duration_in_microseconds / 2)) + error\r\n \r\n distance_in_mm = distance_in_cm * 10\r\n \r\n # pack the data in a tuple and return to the main logic\r\n return (distance_in_mm, distance_in_cm)\r\n\r\nwhile True:\r\n # unpack the tuple\r\n (distance_in_mm, distance_in_cm) = pingSensor()\r\n\r\n print(\"distance : \", distance_in_cm, \" cm\", \"----->\",distance_in_mm, \" mm\")\r\n utime.sleep(1)\r\n ","sub_path":"code/RaspberryPiPICO/ultrasonic.py","file_name":"ultrasonic.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"240028322","text":"# Importing the usual shit\n\nimport numpy as np\nimport pandas as pd\n\n\n\n# Creating the class, later we create an object of this class and just call functions\n\nclass CORModel:\n \n def __init__(self, books, ratings):\n '''\n This is the constructor. It will drop unnecessary cols, sort by book ID\n and merge both dataframes into one mega dataframe\n\n Parameters\n ----------\n books : pandas dataframe containing the imported dataset\n ratings : pandas dataframe containing 6 mil ratings\n to reduce training time we might have to reduce that number\n\n Returns\n -------\n None.\n\n '''\n booksDF = pd.DataFrame(books, columns=['book_id', 'authors', 'title', 'average_rating'])\n booksDF = booksDF.sort_values('book_id')\n\n self.total_books_data = pd.merge(booksDF, ratings, on='book_id')\n\n def create_correlation_matrix(self):\n '''\n This function is the major time consumer. It pivots total_books_data\n on the user_id and the aggregation function is mean(). Then it\n calculates the correlation matrix using np.corrcoef().\n T() is transposing index and columns\n \n '''\n self.each_user_ratings = pd.pivot_table(self.total_books_data, index='user_id', values='rating', columns='title', fill_value=0)\n self.book_correlations = np.corrcoef(self.each_user_ratings.T)\n self.book_titles = list(self.each_user_ratings)\n\n \n def get_recommendations(self, my_fav_IDs):\n '''\n This function accepts a list of fav book IDs and prints recs.\n Modify it as you want so that it returns recs instead of printing them\n\n Parameters\n ----------\n my_fav_IDs : list of integers\n this is the list of book_ids the user LIKED\n only LIKED, not <= 2 stars\n\n Returns\n -------\n None.\n\n '''\n my_fav_books =[self.total_books_data['title'][i] for i in range(1000) if i in my_fav_IDs]\n \n book_similarities = np.zeros(self.book_correlations.shape[0])\n\n for book in my_fav_books: \n book_index = self.book_titles.index(book)\n book_similarities += self.book_correlations[book_index] \n\n book_preferences = []\n for i in range(len(self.book_titles)):\n book_preferences.append((self.book_titles[i], book_similarities[i]))\n \n user_recs = sorted(book_preferences, key= lambda x: x[1], reverse=True)\n \n recs = [(self.total_books_data[self.total_books_data['title']==user_recs[i][0]].book_id.unique()[0], user_recs[i][0],user_recs[i][1]) for i in range(20)]\n\n return recs\n","sub_path":"models/cor_model.py","file_name":"cor_model.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"623174178","text":"import numpy as np\nimport numpy.random\nfrom .core import schema\nimport random\n\nrng_state = numpy.random.RandomState(seed=42)\n\n\ndef reseed(seed=None):\n rng_state.seed(seed)\n random.seed(seed)\n\n\ndef generate_margins(max_margin=1.0):\n return rng_state.rand(2) * max_margin\n\n\ndef generate_random_column_name():\n name_len = rng_state.randint(1, 10)\n return ''.join(random.choice(schema._valid_column_name_chars) for _ in range(name_len))\n\n\ndef generate_random_times(n_trial=None, max_length=1000, be_sorted=True):\n if n_trial is None:\n n_trial = rng_state.randint(1, 500 + 1)\n result = rng_state.rand(n_trial) * max_length\n if be_sorted:\n result = np.sort(result)\n\n return result\n\n\ndef generate_random_shape(ndim=None):\n if ndim is None:\n ndim = rng_state.randint(0, 5)\n shape = tuple(rng_state.randint(1, 10, size=ndim)) # also works when ndim == 0\n return shape\n\n\ndef generate_codes_and_times(num_code=None,\n event_codes_per_trial=None, max_trial_length=1.0):\n if num_code is None:\n num_code = rng_state.randint(10, 20 + 1)\n\n if event_codes_per_trial is None:\n event_codes_per_trial = rng_state.choice(np.arange(-100, 100), size=num_code, replace=False).astype(np.int16)\n\n event_times = np.concatenate([np.array([0]), np.sort(rng_state.rand(num_code - 1))]) * max_trial_length\n event_times = event_times.astype(np.float64)\n\n return event_codes_per_trial, event_times\n\n\ndef generate_start_and_stop_times(codes, times, num_pair=None, times_delay=None):\n if num_pair is None:\n num_pair = rng_state.randint(1, 5 + 1)\n if times_delay is None:\n no_use_times_pairs = rng_state.randint(1, num_pair + 1)\n times_delay = list(rng_state.rand(num_pair))\n no_use_times_pairs_idx = rng_state.choice(num_pair, no_use_times_pairs, replace=False)\n for idx in no_use_times_pairs_idx:\n times_delay[idx] = None\n # choose pairs\n\n code_pair_idx = np.sort(rng_state.choice(len(codes), num_pair * 2, replace=False))\n start_code_idx = code_pair_idx[0::2]\n end_code_idx = code_pair_idx[1::2]\n start_codes = codes[start_code_idx]\n end_codes = codes[end_code_idx]\n start_times = times[start_code_idx]\n end_times = times[end_code_idx]\n\n assert len(start_codes) == len(end_codes) == num_pair\n\n # directly generate the list usable for import params.\n subtrials = []\n for i_pair in range(num_pair):\n if times_delay[i_pair] is None:\n subtrials.append({'start_code': int(start_codes[i_pair]),\n 'end_code': int(end_codes[i_pair])})\n else:\n subtrials.append({'start_code': int(start_codes[i_pair]),\n 'end_time': float(times_delay[i_pair])})\n end_times[i_pair] = start_times[i_pair] + times_delay[i_pair]\n\n return {\n 'start_times': start_times,\n 'end_times': end_times,\n 'subtrials': subtrials,\n 'num_pair': num_pair,\n 'times_delay': times_delay,\n }\n\n\ndef generate_trial_start_and_stop_times(codes, times, start_times, end_times,\n margin_before=0.0, margin_after=0.0,\n trial_param_type='simple',\n start_code=None, end_code=None, end_time=None):\n assert trial_param_type in {'simple', 'code', 'time'}\n\n if trial_param_type == 'simple':\n trial_start_time = start_times[0]\n trial_end_time = end_times[-1]\n elif trial_param_type == 'code':\n start_code_idx = list(codes).index(start_code)\n trial_start_time = times[start_code_idx]\n end_code_idx = list(codes).index(end_code)\n trial_end_time = times[end_code_idx]\n else:\n assert trial_param_type == 'time'\n start_code_idx = list(codes).index(start_code)\n trial_start_time = times[start_code_idx]\n trial_end_time = trial_start_time + end_time\n\n return trial_start_time - margin_before, trial_end_time + margin_after\n\n\ndef generate_event_data(margin_before=0.0, margin_after=0.0, num_trial=None, num_pair=None, *,\n max_trial_length=1.0, max_flexible_margin=1.0,\n all_codes=True # whether using all event codes, that is, first code being trial start,\n # and last code being trial end\n ):\n num_code = rng_state.randint(10, 20 + 1)\n event_codes_per_trial = rng_state.choice(np.arange(-100, 100), size=num_code, replace=False).astype(np.int16)\n if num_trial is None:\n num_trial = rng_state.randint(1, 500 + 1)\n event_codes = [event_codes_per_trial.copy() for _ in range(num_trial)]\n\n # generate start/end codes.\n if num_pair is None:\n num_pair = rng_state.randint(1, 5 + 1)\n # choose pairs\n\n code_pair_idx = np.sort(rng_state.choice(num_code, num_pair * 2, replace=False))\n start_code_idx = code_pair_idx[0::2]\n end_code_idx = code_pair_idx[1::2]\n if all_codes:\n num_pair = 1\n start_code_idx = np.array([0])\n end_code_idx = np.array([num_code - 1])\n start_codes = event_codes_per_trial[start_code_idx]\n end_codes = event_codes_per_trial[end_code_idx]\n assert len(start_codes) == len(end_codes) == num_pair\n\n # then generate some time stamps.\n trial_length_raw = rng_state.rand(num_trial) * max_trial_length\n\n event_times_truth = [np.concatenate([np.array([0]), np.sort(rng_state.rand(num_code - 1)) * trial_length_raw[i]])\n for i\n in range(num_trial)]\n\n trial_margin_before = rng_state.rand(num_trial) * max_flexible_margin + margin_before\n trial_margin_after = rng_state.rand(num_trial) * max_flexible_margin + margin_after\n\n trial_length_padded = trial_length_raw + trial_margin_before + trial_margin_after\n trial_length_padded_cum = np.cumsum(trial_length_padded)\n\n # ok. now let's combine the margins.\n event_times = []\n trial_start_time = []\n trial_end_time = []\n\n start_times = []\n end_times = []\n\n for trial_idx in range(num_trial):\n if trial_idx == 0:\n previous_time = 0.0\n else:\n previous_time = trial_length_padded_cum[trial_idx - 1]\n times_truth = event_times_truth[trial_idx]\n times_abs = times_truth + previous_time + trial_margin_before[trial_idx]\n trial_start_time.append(previous_time + trial_margin_before[trial_idx] - margin_before)\n trial_end_time.append(times_abs[-1] + margin_after)\n\n event_times.append(times_abs)\n event_times_truth[trial_idx] += margin_before\n\n start_times.append(event_times_truth[trial_idx][start_code_idx])\n end_times.append(event_times_truth[trial_idx][end_code_idx])\n\n trial_start_time = np.asarray(trial_start_time)\n trial_end_time = np.asarray(trial_end_time)\n start_times = np.asarray(start_times)\n end_times = np.asarray(end_times)\n\n result = {\n 'event_codes': event_codes,\n 'event_times': event_times,\n 'event_times_per_trial': event_times_truth,\n 'trial_start_time': trial_start_time,\n 'trial_end_time': trial_end_time,\n 'start_times': start_times,\n 'end_times': end_times,\n 'start_codes': start_codes,\n 'end_codes': end_codes\n }\n\n return result\n","sub_path":"cdttable/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"340650451","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nimport io\nimport base64\nfrom PIL import Image\nfrom predict import predictCaption\n\napp = Flask(__name__)\n\n\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/imageupload'\n# db = SQLAlchemy(app)\n\n# class images(db.Model):\n# sno = db.Column(db.Integer, primary_key=True)\n# name = db.Column(db.String(100), index=True, nullable=False)\n# img = db.Column(db.LargeBinary, nullable=False)\n# datetime = db.Column(db.String(), nullable=False)\n\n\n@app.route(\"/\")\ndef home():\n return render_template('index.html')\n\n\n@app.route(\"/upload\", methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n img = request.files['my_image']\n if img:\n # name = request.form.get('my_image')\n image = Image.open(img.stream)\n\n imagePath = \"static/images/\" + img.filename\n f = open(\"static/imageExt.txt\", \"w\")\n f.write(imagePath)\n f.close()\n\n image.save(imagePath)\n # newfile = images(name=image.filename, img=image.read(), datetime = datetime.now())\n # db.session.add(newfile)\n # db.session.commit()\n caption = predictCaption()\n else:\n return \"Select the File\"\n return render_template('output.html', path= imagePath, cap=caption)\n\n\napp.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"195937975","text":"import logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n\nfrom gensim import corpora, models, similarities \nimport nltk\n\nstoplist = set('for a of the and to in as is'.split())\ntexts = [[word for word in document.lower().split() if word not in stoplist]\n for document in open('trainingdata.txt')]\n\n# remove words that appear only once\nfrom collections import defaultdict\n\nfrequency = defaultdict(int)\n\nfor text in texts:\n for token in text:\n frequency[token] += 1\n\ntexts = [[token for token in text if frequency[token] > 1]\n for text in texts]\n\ntagged = [ nltk.pos_tag(text) for text in texts ]\ntexts = [[word[0] for word in tagged_sent if word[1][0] == \"N\" and word[1][1] == \"N\"] for tagged_sent in tagged]\ntexts = [l1 for l1 in texts if l1]\n\n\n\ndictionary = corpora.Dictionary(texts)\ndictionary.save('/tmp/deerwester.dict')\n\ncorpus = [dictionary.doc2bow(text) for text in texts]\ncorpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus)\n\n\ndictionary = corpora.Dictionary.load('/tmp/deerwester.dict')\ncorpus = corpora.MmCorpus('/tmp/deerwester.mm')\n\ntfidf = models.TfidfModel(corpus)\ncorpus_tfidf = tfidf[corpus]\n\nlda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=5)\ncorpus_lda = lda[corpus_tfidf]\n\nlda.print_topic(1)\nfor doc in corpus_lda: # both bow->tfidf and tfidf->lsi transformations are actually executed here, on the fly\n print(doc[1][1])","sub_path":"NLP_project_alay/topicmodelling.py","file_name":"topicmodelling.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"172474129","text":"import re\nimport numpy as np\nfrom gensim.models import word2vec\n\n\n# 定义文本清洗的功能函数\ndef clean_text(text_string):\n # 剔除文本中的网址、ASCII 码和数字\n text_string = re.sub(r'www\\.[a-zA-Z0-9\\.\\?/&\\=\\:]+|(http\\://[a-zA-Z0-9\\.\\?/&\\=\\:]+)|&.*?;|[0-9]+', ' ', text_string)\n # 剔除文本中的特殊字符\n text_string = re.sub(r'[\\s+\\!\\/_,$%^*(+\\\")]+|[+——(),:;?【】“”!,。?、~@#¥%……&*()]+', ' ', text_string)\n text_string = \" \".join(text_string.split())\n text_string = text_string.lower()\n\n return text_string\n\n\n# 使用第三方停词包去掉停词\ndef segment(content, stopwords):\n if isinstance(content, str) is False:\n content = ' '.join(content)\n\n text = content.split(' ') # 分词,默认是精确分词\n result = []\n for word in text:\n word = word.strip('.')\n word = word.strip(\"'\")\n if len(word) != 0 and word != '-' and not stopwords.__contains__(word): # 去掉在停用词表中出现的内容\n result.append(word)\n\n return result\n\n\n# 生成词向量字典\ndef build_word_dict(textPath):\n ## 计算词向量\n sentences = word2vec.Text8Corpus(textPath)\n model = word2vec.Word2Vec(sentences, size=50, window=10, sg=1, hs=1, iter=10, min_count=1)\n\n ## 将词向量转化为字典输出\n vocab = model.wv.vocab\n index = []\n for word in vocab:\n index.append(model[word])\n\n a = np.array(index, dtype=np.float)\n\n word_vector = {}\n i = 0\n for word in vocab:\n word_vector[word] = list(a[i])\n i += 1\n\n return word_vector\n\n\n","sub_path":"RNNModel/WordToVec.py","file_name":"WordToVec.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"510105869","text":"def getNum(string):\r\n import re\r\n lst=re.findall(\"\\d+\",string)\r\n lst=list(map(int,lst))\r\n return lst\r\n\r\n\r\ndef prime(num):\r\n if num<=2:\r\n return False\r\n for i in range(2,num+1):\r\n if num%i==0:\r\n if i!=num:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\n\r\ndef includeThreeorSeven(num):\r\n if \"3\"in str(num) or \"7\" in str(num):\r\n return True\r\n return False\r\n\r\ndef zuobiao(lst):\r\n if len(lst)%2!=0:\r\n lst[:]=lst[:len(lst)-1]\r\n a=[]\r\n b=[]\r\n for i in lst:\r\n b.append(i)\r\n if len(b)==2:\r\n a.append(b)\r\n b=[]\r\n return a\r\n\r\ndef sumDistance(lst,A):\r\n A=list(A)\r\n distance=0\r\n for i in range(len(lst)):\r\n a=((lst[i][0]-A[0])**2+(lst[i][1]-A[1])**2)**0.5\r\n distance+=a\r\n return distance\r\n\r\ndef avgDistanc(distance):\r\n avg =distance/len(lst)\r\n return avg\r\n\r\n\r\ndef getA():\r\n import random\r\n a=random.uniform(0,100)\r\n b=random.uniform(0,100)\r\n A=(a,b)\r\n\r\n return A\r\n\r\n\r\ndef getALLwords(string):\r\n import re\r\n s=re.findall(\"[A-Za-z]+\",string)\r\n return s\r\n\r\ndef getASCII(str):\r\n sum=0\r\n for i in list(str):\r\n sum+=ord(i)\r\n return sum\r\n\r\n\r\nif __name__==\"__main__\":\r\n A = getA()\r\n print(\"({0:>10.2f},{1:>10.2f})\".format(A[0], A[1]))\r\n\r\n string=\"Regular296expression913patterns465are280compiled102into510a122series48of563bytecodes16which366are262then773executed361by50a949matching556engine509written126in451C760For379advanced982use201it502may282be666necessary566to631pay199careful685attention915to814how577the455engine309will349execute178a341given171RE279and52write744the69RE5 78in190a361certain466way726in969order667to310produce943bytecode760that203runs590faster423Optimization723is787not458covered30in250this747document66because396it803requires530that601you928have208a152good609understanding194of31the772matching17engine599internals806\"\r\n lst=list(filter(prime,getNum(string)))\r\n lst=list(filter(includeThreeorSeven,lst))\r\n count=0\r\n for i in lst:\r\n print(\"{0:>10d}\".format(i),end=\"\")\r\n count+=1\r\n if count%2==0:\r\n print()\r\n if len(lst)%2!=0:\r\n print()\r\n\r\n zuobiaolst=zuobiao(lst)\r\n\r\n\r\n\r\n\r\n print(\"距离之和为:{0:>10.2f}\".format(sumDistance(zuobiaolst,A)))\r\n print(\"平均距离为:{0:>10.2f},素数构成的点的坐标个数:{1:>4d}\".format(avgDistanc(sumDistance(zuobiaolst,A)),len(zuobiaolst)))\r\n\r\n s=getALLwords(string)\r\n lst1=[]\r\n count=0\r\n print(\"单词转化为整数:\")\r\n for i in s:\r\n print(\"{0:<8d}\".format(getASCII(i)),end=\"\")\r\n count+=1\r\n if count%10==0:\r\n print()\r\n\r\n","sub_path":"Python程序设计/2016-3/2016-3(by XuWeiwei).py","file_name":"2016-3(by XuWeiwei).py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"606524340","text":"\"\"\"\nEdited April 28, 2016 by Joe Bailey\ndownload the corpus from: http://spamassassin.apache.org/publiccorpus/\nin particular you want two files. the first file should be in\nthe same directory with this scrips an called \"easy_ham\":\nhttp://spamassassin.apache.org/publiccorpus/20030228_easy_ham.tar.bz2\nthe second file you can get from the following url and should be in a directory called \"spam\":\nhttp://spamassassin.apache.org/publiccorpus/20030228_spam.tar.bz2\nnot sure why cmds shows up in each of these two directories, but be sure to delete it\n\"\"\"\n\n# import the libraries needed\nimport os\nimport nltk\nfrom nltk.corpus import stopwords\nimport random\nimport shutil\nimport string\n\n# define globl variables here\nHAMPATH = \"./easy_ham/\"\nSPAMPATH = \"./spam/\"\nTRAIN_PERCENT = 0.75 # percentage of the corpus used to train\nTEST_PERCENT = 0.25 # percentage of the corpus used to test\n# note that TRAIN_PERCENT + TEST_PERCENT must be less than or equal to 1\nSTOPS = stopwords.words(\"english\")\nEXCLUDE = set(string.punctuation) | set([\"''\", \"BR\", \"--\", \"/td\", \"nbsp\", \"2002\", \"localhost\", \" \"])\n\ndef FilterWord(s):\n\t\"\"\"\n\tReceives a string and determines whether or not it is a string that should be used\n\tfor analysis (keep = 1) and passes back a clean version of the string.\n\t\"\"\"\n\tkeep = 1 #default is to keep the word\n\tcleanstring = s.lower()\n\tdrop_chars = \",.:;!\"\n\tfor c in drop_chars:\n\t\tcleanstring = cleanstring.replace(c, \"\")\n\tbad_chars = \"><#$/=0123456789+()&*@?\"\n\tfor c in bad_chars:\n\t\tif cleanstring.find(c)!=-1:\n\t\t\tkeep=0\n\tif len(cleanstring)<3:\n\t\tkeep=0\n\tif cleanstring in STOPS:\n\t\tkeep =0\n\tif cleanstring in EXCLUDE:\n\t\tkeep=0\n\treturn keep, cleanstring\n\ndef CleanWords(wordlist):\n\t\"\"\"\n\tProcess go go through a list of words and clean each of them up. Passes back\n\ta list of clean words.\n\t\"\"\"\n\tfiltered_words =[]\n\tfor each in wordlist:\n\t\tflag, cleanstring = FilterWord(each)\n\t\tif flag==1:\n\t\t\tfiltered_words.append(cleanstring)\n\treturn filtered_words\n\n\ndef SaveWordlist(wordlist, outfile):\n\t\"\"\"\n\tSaves a list of words to the appropriate file.\n\t\"\"\"\n\tf = open(outfile, \"w\")\n\tfor each in wordlist:\n\t\tf.write(\"%s\\n\" % each)\n\tf.close()\n\ndef GetWordlist(inputfile):\n\t\"\"\"\n\tReads in a file as a string and puts it into a list.\n\t\"\"\"\n\tf = open(inputfile, 'r', encoding=\"Latin-1\")\n\ts = f.read().replace('\\n', '')\n\tf.close()\n\ts = ''.join(filter(lambda x: x in string.printable, s))\n\twordlist=s.split()\n\twordlist = CleanWords(wordlist)\n\treturn wordlist\n\n\ndef DirectorySetup():\n\t\"\"\"\n\tSets up the directory structure for output. We need training and testing\n\tfor both ham and spam examples.\n\t\"\"\"\n\tif not os.path.exists(\"./test_ham/\"):\n\t\tos.makedirs(\"./test_ham/\")\n\telse:\n\t\tshutil.rmtree(\"./test_ham/\")\n\t\tos.makedirs(\"./test_ham/\")\n\tif not os.path.exists(\"./test_spam/\"):\n\t\tos.makedirs(\"./test_spam/\")\n\telse:\n\t\tshutil.rmtree(\"./test_spam/\")\n\t\tos.makedirs(\"./test_spam/\")\n\tif not os.path.exists(\"./train_ham/\"):\n\t\tos.makedirs(\"./train_ham/\")\n\telse:\n\t\tshutil.rmtree(\"./train_ham/\")\n\t\tos.makedirs(\"./train_ham/\")\n\tif not os.path.exists(\"./train_spam/\"):\n\t\tos.makedirs(\"./train_spam/\")\n\telse:\n\t\tshutil.rmtree(\"./train_spam/\")\n\t\tos.makedirs(\"./train_spam/\")\n\ndef HamProcess():\n\t\"\"\"\n\tThis process goes through the ham email samples, decides whether or not they\n\tshould be used for training or testing, and then puts the words from that\n\temail into the appropriate folder.\n\t\"\"\"\n\ttrain_ham_files = 0\n\ttest_ham_files = 0\n\twordlist=[]\n\tfor (dirpath, dirnames, filenames) in os.walk(HAMPATH):\n\t\tfor filename in filenames:\n\t\t\tif filename != \"cmds\":\n\t\t\t\tinfile=(HAMPATH + filename)\n\t\t\t\trandom_number = random.uniform(0,1)\n\t\t\t\tif random_number<TRAIN_PERCENT:\n\t\t\t\t\tprint (\"Ham Training: \" + infile)\n\t\t\t\t\toutfile=(\"./train_ham/\" + filename)\n\t\t\t\t\tSaveWordlist(GetWordlist(infile), outfile)\n\t\t\t\t\ttrain_ham_files = train_ham_files + 1\n\t\t\t\telse:\n\t\t\t\t\tif random_number<(TRAIN_PERCENT + TEST_PERCENT):\n\t\t\t\t\t\tprint (\"Ham Testing: \" + infile)\n\t\t\t\t\t\toutfile=(\"./test_ham/\" + filename)\n\t\t\t\t\t\tSaveWordlist(GetWordlist(infile), outfile)\n\t\t\t\t\t\ttest_ham_files = test_ham_files + 1\n\tprint(\"Ham - training set size is: %d\" % train_ham_files)\n\tprint(\"Ham - testing set size is: %d\" % test_ham_files)\n\tSaveWordlist(wordlist, \"./hamwords.txt\")\n\tinput(\"Press Enter to continue...\")\n\ndef SpamProcess():\n\t\"\"\"\n\tThis routine goes through the spam emails, decides whether or not they are part\n\tof the training or testing sample, then puts the words from each document in the\n\tappropriate directory.\n\t\"\"\"\n\ttrain_spam_files = 0\n\ttest_spam_files = 0\n\twordlist=[]\n\tfor (dirpath, dirnames, filenames) in os.walk(SPAMPATH):\n\t\tfor filename in filenames:\n\t\t\tif filename != \"cmds\":\n\t\t\t\tinfile=(SPAMPATH + filename)\n\t\t\t\trandom_number=random.uniform(0,1)\n\t\t\t\tif random_number<TRAIN_PERCENT:\n\t\t\t\t\tprint (\"Spam Training: \" + infile)\n\t\t\t\t\toutfile=(\"./train_spam/\" + filename)\n\t\t\t\t\tSaveWordlist(GetWordlist(infile), outfile)\n\t\t\t\t\ttrain_spam_files = train_spam_files + 1\n\t\t\t\telse:\n\t\t\t\t\tif random_number<(TRAIN_PERCENT + TEST_PERCENT):\n\t\t\t\t\t\tprint (\"Spam Testing: \" + infile)\n\t\t\t\t\t\toutfile=(\"./test_spam/\" + filename)\n\t\t\t\t\t\tSaveWordlist(GetWordlist(infile), outfile)\n\t\t\t\t\t\ttest_spam_files = test_spam_files + 1\n\tprint(\"Spam - training set size is: %d\" % train_spam_files)\n\tprint(\"Spam - testing set size is: %d\" % test_spam_files)\n\tSaveWordlist(wordlist, \"./spamwords.txt\")\n\tinput(\"Press Enter to continue...\")\n\ndef main():\n\t\"\"\"\n\tThe main part of the script that loops through the input file and processes it\n\t\"\"\"\n\tDirectorySetup()\n\tHamProcess()\n\tSpamProcess()\n\n\n\nif '__main__' == __name__:\n\tmain()\n\n\n\n\n","sub_path":"python3/spam_split.py","file_name":"spam_split.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"161198367","text":"# # #\n# Control API MoIP Resolution Tests\n#\n# This test will run through the MoIP resolution tests\n#\n# # #\n\nimport pytest\nimport time\nimport controlapi\nimport moip\nimport random\n\n@pytest.mark.parametrize(\"resolution\", moip.RESOLUTIONS)\ndef test_resolution(client, resolution):\n \"\"\" MoIP Resolution Test \"\"\"\n\n count = moip.get_devicecount(client)\n devices = count.rstrip().split(\",\")\n\n receivers = int(devices[1])\n\n if receivers == 0:\n pytest.skip(\"No receivers to change resolution on\")\n\n for rx in range(receivers):\n api = \"!Resolution=\" + str(rx+1) + \",\" + resolution\n\n client.send(api + \"\\n\")\n time.sleep(1)\n res = client.receive()\n\n # Example\n #\n # !Resolution=1,1\n if res.rstrip() == controlapi.ERROR:\n pytest.fail(\"Error returned from call \" + api)\n","sub_path":"moip/test_resolution.py","file_name":"test_resolution.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"488700534","text":"import os \nimport marshal\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\ndef main():\n# untuk meng clear text di terminal\n os.system(\"clear\")\n\n# input file\n file = input(\"\\033[94mfile python >\\033[95m\")\n\n# baca isi file\n baca = open(file, \"r\").read()\n\n# compile file yang sudah di baca\n com = compile(baca, \"\",\"exec\")\n\n# encrypt file yang sudah di compile dengan marshal\n encrypt = marshal.dumps(com)\n\n# membuat file yg sudah di complie dengan marshal\n baru = open(\"enc_\"+str(file),\"w\")\n\n# print kode marshal untuk bisa di gunakan\n baru.write(\"import marshal\\n\")\n baru.write(\"exec(marshal.loads(\"+repr(encrypt)+\"))\")\n\n# jika berhasil\n print (bcolors.OKGREEN,\"berhasil di encrypt | file sava as enc_\"+str(file))\nmain()","sub_path":"enkripsi_python.py","file_name":"enkripsi_python.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"89866134","text":"arr = []\n\n# 一数字\nline = int(input())\n\n# 一行目を整数化\nline1 = map(int,input().split())\n\n# 一行で複数のパラメタ\nn,m = map(int,input().split())\n# n行のxを配列に入れる\na = [int(input()) for _ in range(n)]\n# n行の(x,y,...)を配列に入れる\nt = [list(map(int,input().split())) for _ in range(n)]\n# フイルタ(条件を指定)してリストに代入\na = list(filter(lambda x: int(x) % 2 == 1, input().split()))\n#map(<関数>,filter(lambda x: ~~~, リスト)) のようなこともできる\n\ns = 'ghahaheh'\n# 文字列を一文字ずつリストに入れる\nt = list(s)\n\n# タプルかどうか\nisinstance(arr, tuple)\n\n# 出力\nprint('{} {} {}'.format(arr[0], arr[3], arr[6]))\n# リストを出力\nprint(\"\".join(arr))\n\n#2次元配列初期化\nw,h = 100,100\nvisited = [[-1 for _ in range(w)] for _ in range(h)]\n\n# 2次元配列のソート\n# 降順、優先順0->1\narr01 = [[0,3],[2,5],[2,2],[4,6],[-1,2]]\narr01 = sorted(arr01, key=lambda x: (-x[0],-x[1]))\n\n# 文字列\n# 逆順\ns1 = 'abcdef'\ns2 = s1[::-1] #fedcba\n\n# bit-shift\n# 0 <= n\n\n# a*2**n\na << n\n\n# a/(2**n)\na >> n\n\n# ゼロ埋め\na = 124\nprint(str(a).zfill(8)) # '00000124'\n","sub_path":"mylib.py","file_name":"mylib.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"533050578","text":"from nltk.translate import bleu_score\nfrom rouge import Rouge\n\n\ndef get_bleu(targets, predictions):\n bleu_scores = 0\n smooth = bleu_score.SmoothingFunction()\n for i in range(len(predictions)):\n score = bleu_score.sentence_bleu(targets[i], predictions[i], smoothing_function=smooth.method7)\n bleu_scores += score\n\n return float(bleu_scores / len(targets))\n\n\ndef get_rouge(targets, predictions):\n rouge = Rouge()\n rouge_scores = 0\n for i in range(len(predictions)):\n score = rouge.get_scores(targets[i], predictions[i])[0][\"rouge-l\"][\"f\"]\n rouge_scores += score\n\n return float(rouge_scores / len(targets))\n\n\ndef get_distinct_1(sentences):\n unique_unigrams = []\n total_words = 0\n for s in sentences:\n total_words += len(s.split())\n for char in s:\n if char not in unique_unigrams:\n unique_unigrams.append(char)\n\n distinct_1 = float(len(unique_unigrams) / total_words)\n\n return distinct_1\n\n\ndef get_distinct_2(sentences):\n unique_bigrams = []\n total_words = 0\n for s in sentences:\n total_words += len(s.split())\n for i in range(len(s) - 1):\n if s[i:i + 2] not in unique_bigrams:\n unique_bigrams.append(s[i:i + 2])\n\n distinct_2 = float(len(unique_bigrams)/total_words)\n\n return distinct_2\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"525436866","text":"# coding=utf-8\n# created by msgi on 2020/4/28 4:37 下午\nimport os\nimport tensorflow_datasets as tfds\n\nimport tensorflow as tf\nfrom datetime import datetime\nfrom smartnlp.nmt.training import Trainer\nfrom smartnlp.custom.learning_rate.learning_rate import CustomSchedule\nfrom smartnlp.custom.model.transformer import Transformer\nfrom smartnlp.nmt.data_process import DataProcessor\n\n# 设置使用GPU\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n\nexamples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True,\n as_supervised=True)\ntrain_examples, val_examples = examples['train'], examples['validation']\n\ndata_processor = DataProcessor()\ntrain_dataset, test_dataset, tokenizer_feat, tokenizer_tar = data_processor.init_preprocess(train_examples,\n val_examples)\n\nEPOCHS = 100\nnum_layers = 6\nd_model = 128\ndff = 512\nnum_heads = 8\ninput_vocab_size = tokenizer_feat.vocab_size + 2\ntarget_vocab_size = tokenizer_tar.vocab_size + 2\ndropout_rate = 0.1\n\n# Custom Scheduler\nlearning_rate = CustomSchedule(d_model)\noptimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9)\n\n# Transformer\ntransformer = Transformer(d_model=d_model, num_heads=num_heads, num_layers=num_layers,\n target_vocab_size=target_vocab_size, input_vocab_size=input_vocab_size,\n dff=dff, rate=dropout_rate)\n\n# Trainer\nprint(f'\\n\\nBeginning training for {EPOCHS} epochs @ {datetime.now()}...\\n')\ntrainer = Trainer(train_dataset=train_dataset,\n test_dataset=test_dataset,\n learning_rate=learning_rate,\n optimizer=optimizer,\n transformer=transformer,\n epochs=EPOCHS,\n checkpoint_path='./models/checkpoints/',\n tb_log_dir='./logs/gradient_tape/'\n\n )\n\nloss_hist, acc_hist = trainer.train()\n","sub_path":"examples/nmt_transformer_demo.py","file_name":"nmt_transformer_demo.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"62020926","text":"from bokeh.charts import TimeSeries\nfrom bokeh.embed import components\n\n\ndef get_plot_ticker_components(ticker, df_data):\n plot_title = 'Last Month ' + ticker.upper() + ' Closing Price'\n\n p = TimeSeries(df_data.closing_price, legend=True, title=plot_title, xlabel='Date', ylabel='Stock Prices')\n p.title.text_font_size = '14pt'\n\n script, div = components(p)\n\n return script, div\n","sub_path":"plot_stock_prices.py","file_name":"plot_stock_prices.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"28124737","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 21 16:30:59 2019\n\n@author: xie\n\"\"\"\nimport math\ny = eval(input())\na = eval(input())\nans = y**(1/a)\nprint(math.floor(ans))","sub_path":"第一次上机/库函数.py","file_name":"库函数.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"88573148","text":"import random, linecache\n\ndef loadbook():\n line_count = 0\n\n # get number of lines (books) in database\n for line in open('Books.tsv'):\n line_count +=1\n\n return line_count\n\ndef getbook(line_count):\n\n # set x to random number between 1 and total number of books\n line = random.randrange(1, line_count, 1)\n\n # select line x from books database\n bookselection = linecache.getline('Books.tsv', line)\n book = bookselection.split(\"\\t\")\n\n if book[4] == 'y':\n #get new book if book is already read\n getbook(line_count)\n else:\n # print book's info\n print(\"\\n\".join(book[:4]))\n if book[5]: print('edited by: ' + book[5])\n \nif __name__ == '__main__':\n\n \"\"\"Pick a random unread book from my book database.\"\"\"\n\n line_count = loadbook()\n getbook(line_count)\n","sub_path":"choosebook.py","file_name":"choosebook.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"364569780","text":"import tkinter\nfrom rong import custom_widgets, colors, images, game_variables, fonts, \\\n event_names, fonts, utilities, game_modes\nfrom rong.screen_manager import screen_manager\nfrom rong.custom_widgets import StyledButton, miscellaneous_widget_parameters\nfrom rong.game import Game\nfrom rong.game.ball import Ball\nfrom .settings_screen import settings_screen\nfrom . import help_screen, game_over_screen\n\n\n_GUTTER_HEIGHT = 50\n_BORDER_WIDTH = 10\n_SCORE_TEMPLATE = \"{player_one_score} — {player_two_score}\"\n\ncurrent_game = None\n\ngame_screen = tkinter.Frame()\n\n_space_above_canvas = tkinter.Frame(master=game_screen)\n_space_above_canvas.pack(fill=tkinter.X)\n\n_score = tkinter.Label(\n master=_space_above_canvas,\n font=fonts.button_font,\n foreground=\"white\"\n)\n_score.pack(expand=True, side=tkinter.LEFT)\nGame.score_label = _score\n\n_pause_button_container = tkinter.Frame(master=_space_above_canvas)\n_pause_button_container.pack(side=tkinter.RIGHT)\n\n_pause_glyph = tkinter.Label(\n master=_pause_button_container,\n image=images.TKINTER_USEABLE_PAUSE_GLYPH,\n borderwidth=0\n)\n_pause_glyph.pack(pady=10, padx=10)\n\ncanvas = tkinter.Canvas(master=game_screen, highlightthickness=0)\ncanvas.pack(fill=tkinter.BOTH, expand=True, pady=(0, _GUTTER_HEIGHT))\nGame.canvas = canvas\n\ndef _pause_button_callback(*args):\n Game.current_game.pause()\n _pause_menu_container.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)\n\nfor _widget in [_pause_button_container, _pause_glyph]:\n _widget.bind(event_names.LEFT_CLICK, _pause_button_callback)\n\nGame.open_pause_menu = _pause_button_callback\n\n_pause_menu_container = tkinter.Frame(\n master=game_screen,\n **miscellaneous_widget_parameters.SETTINGS_CONTAINER\n)\n\nGame.close_pause_menu = _pause_menu_container.place_forget\n\n_pause_menu_buttons = tkinter.Frame(master=_pause_menu_container)\n_pause_menu_buttons.pack()\n\n_continue_button = custom_widgets.StyledButton(\n master=_pause_menu_buttons,\n text=\"Continue\"\n)\n_settings_button = custom_widgets.StyledButton(\n master=_pause_menu_buttons,\n text=\"Settings\"\n)\n_help_button = custom_widgets.StyledButton(\n master=_pause_menu_buttons,\n text=\"Help\"\n)\n_quit_button = custom_widgets.StyledButton(\n master=_pause_menu_buttons,\n text=\"Quit\"\n)\n\nutilities.pack_widgets_as_vertical_list(\n widgets=[_continue_button, _settings_button, _help_button, _quit_button],\n fill_available_width=True\n)\n\n_quit_confirmation_container = tkinter.Frame(master=_pause_menu_container)\n\n_quit_confirmation_text = tkinter.Label(\n master=_quit_confirmation_container,\n text=\"Are you sure you want to quit?\",\n font=\"Arial 50\",\n foreground=\"white\",\n **custom_widgets.miscellaneous_widget_parameters.SETTINGS_CONTAINER\n)\n_quit_confirmation_text.pack(expand=True)\n\n_quit_confirmation_buttons = tkinter.Frame(master=_quit_confirmation_container)\n_quit_confirmation_buttons.pack()\n\n_quit_cancel_button = custom_widgets.StyledButton(\n master=_quit_confirmation_buttons,\n text=\"No\"\n)\n_quit_confirm_button = custom_widgets.StyledButton(\n master=_quit_confirmation_buttons,\n text=\"Yes\"\n)\n\n_quit_cancel_button.pack(side=tkinter.LEFT, padx=(0, 100))\n_quit_confirm_button.pack()\n\n_widgets_to_have_screen_background = [\n game_screen,\n _pause_menu_container,\n _pause_menu_buttons,\n _quit_confirmation_container,\n _quit_confirmation_text,\n _quit_confirmation_buttons,\n _space_above_canvas,\n _score\n]\n\n_widgets_to_have_button_background = [\n _pause_button_container,\n _pause_glyph\n]\n\ndef _screen_background_color_trace_callback(*args):\n for _widget in _widgets_to_have_screen_background:\n _widget.config(background=colors.screen_background.get())\n\n\ndef _pause_button_background_color_trace_callback(*args):\n for _widget in _widgets_to_have_button_background:\n _widget.config(background=colors.pause_button_background.get())\n\ndef _set_pause_glpyh():\n pause_glpyh = utilities.get_value_corresponding_to_contrast_level(\n regular_value=images.TKINTER_USEABLE_PAUSE_GLYPH,\n high_contrast_value=images.TKINTER_USEABLE_BLACK_PAUSE_GLYPH\n )\n _pause_glyph.config(image=pause_glpyh)\n\n_screen_background_color_trace_callback()\n_pause_button_background_color_trace_callback()\n_set_pause_glpyh()\ncolors.screen_background.trace(\"w\", _screen_background_color_trace_callback)\ncolors.pause_button_background.trace(\n \"w\",\n _pause_button_background_color_trace_callback\n)\ngame_variables.high_contrast_mode_enabled.trace(\n \"w\",\n lambda *args: _set_pause_glpyh()\n)\n\n\ndef destroy():\n Game.current_game.destroy()\n _quit_confirmation_container.pack_forget()\n _pause_menu_buttons.pack()\n _pause_menu_container.place_forget()\n\n_player_one_score_observer_name = tkinter.StringVar()\n_player_two_score_observer_name = tkinter.StringVar()\n\ndef set_score():\n player_one_score = game_variables.player_one_score.get()\n player_two_score = game_variables.player_two_score.get()\n score_limit = game_variables.score_limit.get()\n\n if (\n game_variables.game_mode.get() != game_modes.ZEN and (\n player_one_score >= score_limit\n or player_two_score >= score_limit\n )\n ):\n destroy()\n game_over_screen.init()\n screen_manager.change_screen(game_over_screen.game_over_screen)\n return\n\n score_text = _SCORE_TEMPLATE.format(\n player_one_score=player_one_score,\n player_two_score=player_two_score\n )\n _score.config(text=score_text)\n\nBall.set_score_label = set_score\n\n\ndef _continue_button_callback(*args):\n _pause_menu_container.place_forget()\n Game.current_game.resume()\n\n\ndef _settings_button_callback(*args):\n screen_manager.change_screen(settings_screen)\n\n\ndef _help_button_callback(*args):\n help_screen.back_button.source_screen = game_screen\n screen_manager.change_screen(help_screen.help_screen)\n\n\ndef _quit_button_callback(*args):\n _pause_menu_buttons.pack_forget()\n _quit_confirmation_container.pack(expand=True, anchor=tkinter.CENTER)\n\n\ndef _quit_cancel_button_callback(*args):\n _quit_confirmation_container.pack_forget()\n _pause_menu_buttons.pack()\n\n\ndef _quit_confirm_button_callback(*args):\n destroy()\n screen_manager.change_screen(screen_manager.main_screen)\n\n\n_continue_button.bind(event_names.LEFT_CLICK, _continue_button_callback)\n_settings_button.bind(event_names.LEFT_CLICK, _settings_button_callback)\n_help_button.bind(event_names.LEFT_CLICK, _help_button_callback)\n_quit_button.bind(event_names.LEFT_CLICK, _quit_button_callback)\n_quit_cancel_button.bind(event_names.LEFT_CLICK, _quit_cancel_button_callback)\n_quit_confirm_button.bind(\n event_names.LEFT_CLICK,\n _quit_confirm_button_callback\n)\n","sub_path":"rong/screens/game_screen.py","file_name":"game_screen.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"35730866","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:Erik Chan\n# datetime:2019/4/28 18:26\n# software: PyCharm\nimport tensorflow as tf\n\n# Fetch 运行多个op,并得到运行的结果\na1 = tf.constant(3.0)\na2 = tf.constant(2.0)\na3 = tf.constant(5.0)\n\nadd = tf.add(a1,a2)\nmul = tf.multiply(a1,add)\n\nwith tf.Session() as sess:\n res = sess.run([mul,add])\n print(res)\n\n\n#feed给占位符加数据\n\n\n","sub_path":"PycharmProjects/Practice/数据分析/炼数成金/Fetch&Feed.py","file_name":"Fetch&Feed.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"628710479","text":"def flatten(data):\n transform = []\n for i in data:\n if type(i) == list:\n transform += flatten(i)\n else:\n transform.append(i)\n\n return transform\n\n\nexample = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]\nprint(\"원본:\", example)\nprint(\"변환:\", flatten(example))\n\n\n# 원본: [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]\n# 변환: [1, 2, 3, 4, 5, 6, 7, 8, 9]","sub_path":"혼공파/practice/5_2_1.py","file_name":"5_2_1.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"426051869","text":"import numpy as np\nimport pandas as pd\nimport os\n\nDu = Dv = 1.125\nDw = 13.5\n\nx0 = 64\ny0 = 32\nsigma = 5\n\ncomps = [(\"u\", Du), (\"v\", Dv), (\"w\", Dw)]\nerrors = []\n\nfor file in os.listdir(\"results\"):\n if file.endswith(\".dat\"):\n data = pd.read_csv(\n os.path.join(\"results\", file),\n skiprows=3,\n names=[\"x\", \"y\", \"u\", \"v\", \"w\", \"P_sin_theta\"])\n\n # Compute time from file name\n t = float(os.path.splitext(file)[0])\n\n # Compute distance of each cell to the gaussian center\n data[\"r\"] = np.sqrt(np.power(data[\"x\"] - x0, 2) + np.power(data[\"y\"] - y0, 2))\n\n # Compute the theoretical value\n for comp in comps:\n data[comp[0] + \"_theo\"] = (\n 2 * np.pi * np.power(sigma, 2)\n ) / (\n 4 * np.pi * comp[1] * (t + np.power(sigma, 2) / (2 * comp[1]))\n ) * np.exp(\n -np.power(data[\"r\"], 2) / (\n 4 * comp[1] * (t + np.power(sigma, 2) / (2 * comp[1]))))\n\n # Compute L2 error\n tmp = [t]\n for comp in comps:\n tmp.append(np.sqrt(np.power(data[comp[0]] - data[comp[0] + \"_theo\"], 2).sum() / np.power(data[comp[0]], 2).sum()))\n errors.append(tmp)\n\nfilename = \"errors.dat\"\n\nerr_data = pd.DataFrame(errors, columns=[\"t\", \"err2_u\", \"err2_v\", \"err2_w\"])\nerr_data.sort_values(\"t\").to_csv(filename, index=False)\n","sub_path":"results/validation/diffusion/compute_err2_diffusion.py","file_name":"compute_err2_diffusion.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572532711","text":"#Exercise 57: It is a leap year?\n\ntry:\n#Input data for keyboard.\n year = int(input('Input the year: '))\n\n#If/Else statament\n if (year % 4 == 0) and (year % 100 != 0):\n print('It is a leap year!')\n elif(year % 400 == 0):\n print('It is a leap year!')\n else:\n print('Is is not a leap year!')\n\nexcept ValueError:\n print('Error,you must to input a year.')\n","sub_path":"Chapter2/leap_year.py","file_name":"leap_year.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"84074064","text":"import re\n\nfrom redis import Redis\n\nfrom tenyks.config import settings\n\ndef pubsub_factory(channel):\n \"\"\"\n Returns a Redis.pubsub object subscribed to `channel`.\n \"\"\"\n rdb = Redis(**settings.REDIS_CONNECTION)\n pubsub = rdb.pubsub()\n pubsub.subscribe(channel)\n return pubsub\n\nirc_prefix_re = re.compile(r':?([^!@]*)!?([^@]*)@?(.*)').match\ndef parse_irc_prefix(prefix):\n nick, user, host = irc_prefix_re(prefix).groups()\n return {\n 'nick': nick, \n 'user': user, \n 'host': host\n }\n","sub_path":"tenyks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572532601","text":"\"\"\"\nautomated tests for nlp utility functions used as part of bbx OCR\n\"\"\"\n\nfrom str_cleaners import note_fn, data_fn, header_fn\n\n\ndef test_note_fn():\n \"\"\"\n expected to be Note in some form or other\n \"\"\"\n\n notes_list = ['note',\n 'notes',\n 'Note',\n 'Notes',\n 'n ote',\n 'n.ote',\n 'n,ote',\n 'note\\n',\n 'note\\t',\n 'note\\r',\n 'n,. o ,te\\n\\t\\t\\r',\n '']\n\n processed = [note_fn('note', x) for x in notes_list]\n\n for item in processed:\n assert 'note' in item\n\n return\n\n\ndef test_data_fn():\n \"\"\"\n data values in string for being stripped to misread chars\n \"\"\"\n\n values = ['2013',\n '2012',\n '12 34',\n '99.90',\n '99,90',\n '-',\n '(123',\n '123)',\n '123\\n\\t\\r',\n ''\n ]\n\n processed = [data_fn('6', x) for x in values]\n\n for item in processed:\n # test each str can be converted into an integer\n assert isinstance(int(item), int)\n\n return\n\n\ndef test_header_fn():\n \"\"\"\n row titles for accounts table\n \"\"\"\n\n titles = ['profIt and LoSS',\n 'BALANCE SHEET\\n',\n 'ordianry taxes\\t',\n 'ProFIt/(lOss) on OrDInary aCtIvities \\r'\n ]\n\n processed = [header_fn('nonsense', x) for x in titles]\n\n for item in processed:\n # test each str can be converted into an integer\n assert isinstance(item, str)\n\n return\n","sub_path":"test/tests/test_str_cleaners.py","file_name":"test_str_cleaners.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"76130781","text":"import readline\nimport logging\n\nLOG_FILENAME = '/tmp/completer.log'\nlogging.basicConfig(filename=LOG_FILENAME,\n level=logging.DEBUG,\n )\n\n\nclass SimpleCompleter(object):\n \"\"\"cribbed from python readline documentation\"\"\"\n\n def __init__(self, cl, predicate):\n self.completion_list = sorted(cl)\n self.matches = []\n self.predicate = predicate # function to select completions\n return\n\n def complete(self, text, state):\n response = None\n if state == 0:\n # This is the first time for this text, so find the elements\n # of the completion list that match text\n if text:\n self.matches = [s\n for s in self.completion_list\n if s and self.predicate(text, s)] # s.startswith(text)]\n logging.debug('%s matches: %s', repr(text), self.matches)\n else:\n self.matches = self.completion_list[:]\n logging.debug('(empty input) matches: %s', self.matches)\n\n # Return the state'th item from the match list,\n try:\n response = self.matches[state]\n except IndexError:\n response = None\n logging.debug('complete(%s, %s) => %s', repr(text), state, repr(response))\n return response\n\n\ndef input_loop():\n line = ''\n while line != 'stop':\n #line = raw_input('Prompt (\"stop\" to quit): ')\n line = input('Prompt (\"stop\" to quit): ') #pycharm\n print('Dispatch %s' % line)\n\nif __name__ == \"__main__\":\n # Register our completer function\n cl_predicate = lambda entered_text, cl_candidate: cl_candidate.startswith(entered_text)\n readline.set_completer(SimpleCompleter(['start', 'stop', 'list', 'print'],cl_predicate).complete)\n\n # Use the tab key for completion\n # hack from stackoverflow. os/x python is a bit different because built atop BSD libedit\n #\n if 'libedit' in readline.__doc__:\n readline.parse_and_bind(\"bind ^I rl_complete\")\n else:\n readline.parse_and_bind(\"tab: complete\")\n\n # Prompt the user for text\n input_loop()\n","sub_path":"complete.py","file_name":"complete.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"402909516","text":"\"\"\"\n积极度模型配置文件\n\"\"\"\n\n# 定义最高分\nMAX_SCORE = 899\n\n# 定义最低分\nMIN_SCORE = 350\n\n# 定义初始分\nDEFAULT_SCORE = 450\n\n# 定义名称\nNAME = {\n '学生编号': 'STUDENTCODE',\n '高校名称': 'UNIVERSITYNAME',\n '月份': 'MONTH',\n '登录次数': 'LOG_NUM',\n '登陆时长': 'LOG_DURATION',\n '登陆天数': 'LOG_DAY',\n '课件点击次数': 'CLICK_COURSE',\n '课程问答发回��数量': 'T_F',\n '微学吧栏目点击次数': 'C_PV',\n '有效作业数': 'HOMEWORK_NUM',\n '已完成作业数': 'FIN_HOMEWORE_NUM',\n '作业完成度': 'COMPLETION_WORK',\n '积极度分值': 'ACTIVITY',\n '登录次数分数': 'LOG_NUM_SCORE',\n '登陆时长分数': 'LOG_DURATION_SCORE',\n '登陆天数分数': 'LOG_DAY_SCORE',\n '课件点击次数分数': 'CLICK_COURSE_SCORE',\n '课程问答发回帖数量分数': 'T_F_SCORE',\n '微学吧栏目点击次数分数': 'C_PV_SCORE',\n '作业完成度分数': 'COMPLETION_WORK_SCORE',\n '月活跃度值': 'MONTH_ACTIVITY',\n '积极度算出值': 'CALC_ACTIVITY',\n '积极度减分值': 'CUT_ACTIVITY',\n '上月积极度值': 'LAST_ACTIVITY',\n '积极度最大加分值': 'ALPHA'\n}\n\n# 定义普通指标的权重及范围\nTARGET_WEIGHT_RANGE = [\n # 登录次数\n {\n 'NAME': NAME['登录次数'],\n 'WEIGHT': 100,\n 'MAX_VAL': 10,\n 'MIN_VAL': 0,\n },\n\n # 登录时长\n {\n 'NAME': NAME['登陆时长'],\n 'WEIGHT': 150,\n 'MAX_VAL': 3600,\n 'MIN_VAL': 0,\n },\n\n # 登录天数\n {\n 'NAME': NAME['登陆天数'],\n 'WEIGHT': 100,\n 'MAX_VAL': 8,\n 'MIN_VAL': 0,\n },\n\n # 点击次数_课件\n {\n 'NAME': NAME['课件点击次数'],\n 'WEIGHT': 150,\n 'MAX_VAL': 10,\n 'MIN_VAL': 0,\n },\n\n # 发回帖数量_课程问答\n {\n 'NAME': NAME['课程问答发回帖数量'],\n 'WEIGHT': 100,\n 'MAX_VAL': 8,\n 'MIN_VAL': 0,\n },\n\n # 栏目点击次数_微学吧\n {\n 'NAME': NAME['微学吧栏目点击次数'],\n 'WEIGHT': 100,\n 'MAX_VAL': 15,\n 'MIN_VAL': 0,\n },\n\n # 作业完成度\n {\n 'NAME': NAME['作业完成度'],\n 'WEIGHT': 100,\n 'MAX_VAL': 1,\n 'MIN_VAL': 0,\n }\n]\n\n# 定义特殊指标的权重及范围\nSPECIAL_TARGET_WEIGHT_RANGE = [\n # 登录次数\n {\n 'NAME': NAME['登录次数'],\n 'WEIGHT': 100,\n 'MAX_VAL': 10,\n 'MIN_VAL': 0,\n },\n\n # 登录时长\n {\n 'NAME': NAME['登陆时长'],\n 'WEIGHT': 150,\n 'MAX_VAL': 3600,\n 'MIN_VAL': 0,\n },\n\n # 登录天数\n {\n 'NAME': NAME['登陆天数'],\n 'WEIGHT': 100,\n 'MAX_VAL': 8,\n 'MIN_VAL': 0,\n },\n\n # 点击次数_课件\n {\n 'NAME': NAME['课件点击次数'],\n 'WEIGHT': 0,\n 'MAX_VAL': 10,\n 'MIN_VAL': 0,\n },\n\n # 发回帖数量_课程问答\n {\n 'NAME': NAME['课程问答发回帖数量'],\n 'WEIGHT': 0,\n 'MAX_VAL': 8,\n 'MIN_VAL': 0,\n },\n\n # 栏目点击次数_微学吧\n {\n 'NAME': NAME['微学吧栏目点击次数'],\n 'WEIGHT': 0,\n 'MAX_VAL': 15,\n 'MIN_VAL': 0,\n },\n\n # 作业完成度\n {\n 'NAME': NAME['作业完成度'],\n 'WEIGHT': 0,\n 'MAX_VAL': 1,\n 'MIN_VAL': 0,\n }\n]\n\n\n# 定义减分规则\ndef PUNISH_RULE(data):\n punish_list = [\n # 积极度得分在350到450之间,登录次数小于1,扣除相应月活跃度,PUNISH_ACTIVITY=0 表示从原值开始扣分\n {\n 'PUNISH_INDEX': data[(data[NAME['登录次数']] < 1) &\n ((data[NAME['积极度分值']] > 350) & (data[NAME['积极度分值']] < 450))].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 0\n },\n\n # 积极度得分在450到500之间,登录次数小于1,扣除相应月活跃度,PUNISH_ACTIVITY=450 表示从450开始扣分\n {\n 'PUNISH_INDEX': data[(data[NAME['登录次数']] < 1) &\n ((data[NAME['积极度分值']] >= 450) & (data[NAME['积极度分值']] < 500))].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 450\n },\n\n # 积极度得分在450到500之间,登录时长小于5分钟(300秒),扣除相应月活跃度\n {\n 'PUNISH_INDEX': data[(data[NAME['登陆时长']] < 300) &\n ((data[NAME['积极度分值']] >= 450) & (data[NAME['积极度分值']] < 500))].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 450\n },\n\n # 积极度得分在500到600之间,登录次数小于3,扣除相应月活跃度\n {\n 'PUNISH_INDEX': data[(data[NAME['登录次数']] < 3) &\n ((data[NAME['积极度分值']] >= 500) & (data[NAME['积极度分值']] < 600))].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 500\n },\n\n # 积极度得分在500到600之间,登录时长小于30分钟(1800秒),扣除相应月活跃度\n {\n 'PUNISH_INDEX': data[(data[NAME['登陆时长']] < 1800) &\n ((data[NAME['积极度��值']] >= 500) & (data[NAME['积极度分值']] < 600))].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 500\n },\n\n # 积极度得分在600以上,登录次数小于6,扣除相应月活跃度\n {\n 'PUNISH_INDEX': data[(data[NAME['登录次数']] < 6) &\n (data[NAME['积极度分值']] >= 600)].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 600\n },\n\n # 积极度得分在600以上,登录时长小于60分钟(3600秒),扣除相应月活跃度\n {\n 'PUNISH_INDEX': data[(data[NAME['登陆时长']] < 3600) &\n (data[NAME['积极度分值']] >= 600)].index,\n 'PUNISH_WEIGHT': 0.1,\n 'PUNISH_ACTIVITY': 600\n }\n ]\n return punish_list\n\n# 定义输入的用户信息所包含的内容\nINPUT_DATA_CONTAIN = [\n NAME['学生编号'],\n NAME['高校名称'],\n NAME['登录次数'],\n NAME['登陆时长'],\n NAME['登陆天数'],\n NAME['课件点击次数'],\n NAME['课程问答发回帖数量'],\n NAME['微学吧栏目点击次数'],\n NAME['有效作业数'],\n NAME['已完成作业数'],\n]\n\n# 定义输入的中间表文件所包含的内容\nINPUT_ADD_LIST_FILE_CONTAIN = [\n NAME['学生编号'],\n NAME['积极度分值']\n]\n\n# 定义输出文件所包含的内容\nOUT_PUT_FILE_CONTAIN = [\n NAME['学生编号'],\n NAME['积极度分值'],\n NAME['月份']\n]\n\n# 定义输出的中间表所包含的内容\nOUT_PUT_ADD_LIST_CONTAIN = [\n NAME['学生编号'],\n NAME['登录次数分数'],\n NAME['登陆时长分数'],\n NAME['登陆天数分数'],\n NAME['课件点击次数分数'],\n NAME['课程问答发回帖数量分数'],\n NAME['微学吧栏目点击次数分数'],\n NAME['作业完成度分数'],\n NAME['月活跃度值'],\n NAME['积极度最大加分值'],\n NAME['积极度算出值'],\n NAME['积极度减分值'],\n NAME['积极度分值'],\n NAME['月份']\n]\n\n# 定义需要用特殊指标来建模的学校\nSPECIAL_SCHOOL_LIST = [\n '北京大学',\n '对外经济贸易大学',\n '西南大学',\n '中国人民大学',\n '中国石油大学(北京)',\n '中南大学',\n '北京外国语大学',\n '北京邮电大学',\n '江南大学',\n '西南交通大学',\n '中国传媒大学',\n]\n\n# 定义输入文件名\nINPUT_FILE_NAME = 'activity_out_before.csv'\n\n# 定义积极度输出文件名\nOUT_PUT_FILE_NAME = 'activity_out_before.csv'\n\n# 定义中间表输出文件名\nOUT_PUT_ADD_LIST_FILE_NAME = 'add_list_out'\n\n","sub_path":"oedm/student_activity/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"48728258","text":"import copy\nimport logging\nimport os\nimport sys\n\nimport yaml\n\n# Env variables:\n\n# RAY_REPO Repo to use for finding the wheel\n# RAY_BRANCH Branch to find the wheel\n# RAY_TEST_REPO Repo to use for test scripts\n# RAY_TEST_BRANCH Branch for test scripts\n# FILTER_FILE File filter\n# FILTER_TEST Test name filter\n# RELEASE_TEST_SUITE Release test suite (e.g. manual, nightly)\n\n\nclass ReleaseTest:\n def __init__(self, name: str, smoke_test: bool = False, retry: int = 0):\n self.name = name\n self.smoke_test = smoke_test\n self.retry = retry\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return self.name\n\n def __contains__(self, item):\n return self.name.__contains__(item)\n\n def __iter__(self):\n return iter(self.name)\n\n def __len__(self):\n return len(self.name)\n\n\nclass SmokeTest(ReleaseTest):\n def __init__(self, name: str, retry: int = 0):\n super(SmokeTest, self).__init__(\n name=name, smoke_test=True, retry=retry)\n\n\nCORE_NIGHTLY_TESTS = {\n \"~/ray/release/nightly_tests/nightly_tests.yaml\": [\n \"shuffle_10gb\",\n \"shuffle_50gb\",\n \"shuffle_50gb_large_partition\",\n \"shuffle_100gb\",\n \"non_streaming_shuffle_100gb\",\n \"non_streaming_shuffle_50gb_large_partition\",\n \"non_streaming_shuffle_50gb\",\n \"dask_on_ray_10gb_sort\",\n \"dask_on_ray_100gb_sort\",\n SmokeTest(\"dask_on_ray_large_scale_test_no_spilling\"),\n SmokeTest(\"dask_on_ray_large_scale_test_spilling\"),\n \"stress_test_placement_group\",\n \"shuffle_1tb_1000_partition\",\n \"non_streaming_shuffle_1tb_1000_partition\",\n \"shuffle_1tb_5000_partitions\",\n \"non_streaming_shuffle_1tb_5000_partitions\",\n \"decision_tree_autoscaling\",\n \"autoscaling_shuffle_1tb_1000_partitions\",\n SmokeTest(\"stress_test_many_tasks\"),\n SmokeTest(\"stress_test_dead_actors\"),\n \"shuffle_data_loader\",\n \"dask_on_ray_1tb_sort\",\n ],\n \"~/ray/benchmarks/benchmark_tests.yaml\": [\n \"single_node\",\n \"object_store\",\n ],\n \"~/ray/release/nightly_tests/dataset/dataset_test.yaml\": [\n \"inference\",\n ]\n}\n\nNIGHTLY_TESTS = {\n # \"~/ray/release/horovod_tests/horovod_tests.yaml\": [\n # SmokeTest(\"horovod_test\"),\n # ], # Should we enable this?\n \"~/ray/release/golden_notebook_tests/golden_notebook_tests.yaml\": [\n \"dask_xgboost_test\",\n \"modin_xgboost_test\",\n \"torch_tune_serve_test\",\n ],\n \"~/ray/release/nightly_tests/nightly_tests.yaml\": [\n \"dask_on_ray_large_scale_test_no_spilling\",\n \"dask_on_ray_large_scale_test_spilling\",\n ],\n \"~/ray/release/long_running_tests/long_running_tests.yaml\": [\n SmokeTest(\"actor_deaths\"),\n SmokeTest(\"apex\"),\n SmokeTest(\"impala\"),\n SmokeTest(\"many_actor_tasks\"),\n SmokeTest(\"many_drivers\"),\n SmokeTest(\"many_ppo\"),\n SmokeTest(\"many_tasks\"),\n SmokeTest(\"many_tasks_serialized_ids\"),\n SmokeTest(\"node_failures\"),\n SmokeTest(\"pbt\"),\n # SmokeTest(\"serve\"),\n # SmokeTest(\"serve_failure\"),\n ],\n \"~/ray/release/microbenchmark/microbenchmark.yaml\": [\n \"microbenchmark\",\n ],\n \"~/ray/release/sgd_tests/sgd_tests.yaml\": [\n \"sgd_gpu\",\n ],\n \"~/ray/release/tune_tests/scalability_tests/tune_tests.yaml\": [\n \"bookkeeping_overhead\",\n \"durable_trainable\",\n SmokeTest(\"long_running_large_checkpoints\"),\n SmokeTest(\"network_overhead\"),\n \"result_throughput_cluster\",\n \"result_throughput_single_node\",\n \"xgboost_sweep\",\n ],\n \"~/ray/release/xgboost_tests/xgboost_tests.yaml\": [\n \"train_small\",\n \"train_moderate\",\n \"train_gpu\",\n \"tune_small\",\n \"tune_4x32\",\n \"tune_32x4\",\n \"ft_small_elastic\",\n \"ft_small_non_elastic\",\n \"distributed_api_test\",\n ],\n \"~/ray/release/serve_tests/serve_tests.yaml\": [\n \"single_deployment_1k_noop_replica\",\n ],\n}\n\nWEEKLY_TESTS = {\n \"~/ray/benchmarks/benchmark_tests.yaml\": [\n \"distributed\",\n ],\n \"~/ray/release/nightly_tests/nightly_tests.yaml\": [\n \"stress_test_many_tasks\",\n \"stress_test_dead_actors\",\n ],\n \"~/ray/release/horovod_tests/horovod_tests.yaml\": [\n \"horovod_test\",\n ],\n \"~/ray/release/long_running_distributed_tests\"\n \"/long_running_distributed.yaml\": [\n \"pytorch_pbt_failure\",\n ],\n # Full long running tests (1 day runtime)\n \"~/ray/release/long_running_tests/long_running_tests.yaml\": [\n \"actor_deaths\",\n \"apex\",\n \"impala\",\n \"many_actor_tasks\",\n \"many_drivers\",\n \"many_ppo\",\n \"many_tasks\",\n \"many_tasks_serialized_ids\",\n \"node_failures\",\n \"pbt\",\n \"serve\",\n \"serve_failure\",\n ],\n \"~/ray/release/tune_tests/scalability_tests/tune_tests.yaml\": [\n \"network_overhead\",\n \"long_running_large_checkpoints\",\n ],\n}\n\nMANUAL_TESTS = {\n \"~/ray/release/rllib_tests/rllib_tests.yaml\": [\n \"learning_tests\",\n \"example_scripts_on_gpu_tests\",\n \"stress_tests\",\n ],\n \"~/ray/release/long_running_tests/long_running_tests.yaml\": [\n SmokeTest(\"serve\"),\n SmokeTest(\"serve_failure\"),\n ]\n}\n\nSUITES = {\n \"core-nightly\": CORE_NIGHTLY_TESTS,\n \"nightly\": NIGHTLY_TESTS,\n \"weekly\": WEEKLY_TESTS,\n \"manual\": MANUAL_TESTS,\n}\n\nDEFAULT_STEP_TEMPLATE = {\n \"env\": {\n \"ANYSCALE_CLOUD_ID\": \"cld_4F7k8814aZzGG8TNUGPKnc\",\n \"ANYSCALE_PROJECT\": \"prj_2xR6uT6t7jJuu1aCwWMsle\",\n \"RELEASE_AWS_BUCKET\": \"ray-release-automation-results\",\n \"RELEASE_AWS_LOCATION\": \"dev\",\n \"RELEASE_AWS_DB_NAME\": \"ray_ci\",\n \"RELEASE_AWS_DB_TABLE\": \"release_test_result\",\n \"AWS_REGION\": \"us-west-2\"\n },\n \"agents\": {\n \"queue\": \"runner_queue_branch\"\n },\n \"plugins\": [{\n \"docker#v3.8.0\": {\n \"image\": \"rayproject/ray\",\n \"propagate-environment\": True\n }\n }],\n \"commands\": []\n}\n\n\ndef build_pipeline(steps):\n all_steps = []\n\n RAY_BRANCH = os.environ.get(\"RAY_BRANCH\", \"master\")\n RAY_REPO = os.environ.get(\"RAY_REPO\",\n \"https://github.com/ray-project/ray.git\")\n\n RAY_TEST_BRANCH = os.environ.get(\"RAY_TEST_BRANCH\", RAY_BRANCH)\n RAY_TEST_REPO = os.environ.get(\"RAY_TEST_REPO\", RAY_REPO)\n\n FILTER_FILE = os.environ.get(\"FILTER_FILE\", \"\")\n FILTER_TEST = os.environ.get(\"FILTER_TEST\", \"\")\n\n logging.info(\n f\"Building pipeline \\n\"\n f\"Ray repo/branch to test:\\n\"\n f\" RAY_REPO = {RAY_REPO}\\n\"\n f\" RAY_BRANCH = {RAY_BRANCH}\\n\\n\"\n f\"Ray repo/branch containing the test configurations and scripts:\"\n f\" RAY_TEST_REPO = {RAY_TEST_REPO}\\n\"\n f\" RAY_TEST_BRANCH = {RAY_TEST_BRANCH}\\n\\n\"\n f\"Filtering for these tests:\\n\"\n f\" FILTER_FILE = {FILTER_FILE}\\n\"\n f\" FILTER_TEST = {FILTER_TEST}\\n\\n\")\n\n for test_file, test_names in steps.items():\n if FILTER_FILE and FILTER_FILE not in test_file:\n continue\n\n test_base = os.path.basename(test_file)\n for test_name in test_names:\n if FILTER_TEST and FILTER_TEST not in test_name:\n continue\n\n if not isinstance(test_name, ReleaseTest):\n test_name = ReleaseTest(name=test_name)\n\n logging.info(f\"Adding test: {test_base}/{test_name}\")\n\n cmd = str(f\"python release/e2e.py \"\n f\"--ray-branch {RAY_BRANCH} \"\n f\"--category {RAY_BRANCH} \"\n f\"--test-config {test_file} \"\n f\"--test-name {test_name}\")\n\n if test_name.smoke_test:\n logging.info(\"This test will run as a smoke test.\")\n cmd += \" --smoke-test\"\n\n step_conf = copy.deepcopy(DEFAULT_STEP_TEMPLATE)\n\n if test_name.retry:\n logging.info(f\"This test will be retried up to \"\n f\"{test_name.retry} times.\")\n step_conf[\"retry\"] = {\n \"automatic\": [{\n \"exit_status\": \"*\",\n \"limit\": test_name.retry\n }]\n }\n\n step_conf[\"commands\"] = [\n \"pip install -q -r release/requirements.txt\",\n \"pip install -U boto3 botocore\",\n f\"git clone -b {RAY_TEST_BRANCH} {RAY_TEST_REPO} ~/ray\",\n cmd,\n ]\n\n step_conf[\"label\"] = f\"{test_name} ({RAY_BRANCH}) - \" \\\n f\"{RAY_TEST_BRANCH}/{test_base}\"\n all_steps.append(step_conf)\n\n return all_steps\n\n\ndef alert_pipeline(stats: bool = False):\n step_conf = copy.deepcopy(DEFAULT_STEP_TEMPLATE)\n\n cmd = \"python release/alert.py\"\n if stats:\n cmd += \" --stats\"\n\n step_conf[\"commands\"] = [\n \"pip install -q -r release/requirements.txt\",\n \"pip install -U boto3 botocore\",\n cmd,\n ]\n step_conf[\"label\"] = f\"Send periodic alert (stats_only = {stats})\"\n return [step_conf]\n\n\nif __name__ == \"__main__\":\n alert = os.environ.get(\"RELEASE_ALERT\", \"0\")\n\n if alert in [\"1\", \"stats\"]:\n steps = alert_pipeline(alert == \"stats\")\n else:\n TEST_SUITE = os.environ.get(\"RELEASE_TEST_SUITE\", \"nightly\")\n PIPELINE_SPEC = SUITES[TEST_SUITE]\n\n steps = build_pipeline(PIPELINE_SPEC)\n\n yaml.dump({\"steps\": steps}, sys.stdout)\n","sub_path":"release/.buildkite/build_pipeline.py","file_name":"build_pipeline.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"360573000","text":"# coding=utf-8\nfrom appium import webdriver\nimport appium\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '6.0.1'\ndesired_caps['deviceName'] = 'Nexus 5'\ndesired_caps['appPackage'] = 'com.android.settings'\ndesired_caps['appActivity'] = '.Settings'\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n# driver.execute_script(\"mobile: scroll\", {\"direction\": \"down\"})\ndriver.swipe(0, 0, 0, 1)\ntime.sleep(1)\ndriver.swipe(0, 0, 0, 1)\ntime.sleep(1)\ndriver.find_element_by_name(\"Accounts\").click()\ntime.sleep(1)\ndriver.find_element_by_name(\"Add account\").click()\ntime.sleep(1)\ndriver.find_element_by_name(\"Google\").click()\ntime.sleep(5)\n# driver.find_element_by_xpath(\"//*[@class='android.view.View' and @content-desc='Or create a new \"\n# \"account']\").click()\ndriver.tap([(400, 1450)], 500)\ntime.sleep(5)\ndriver.press_keycode(99)\ndriver.press_keycode(31)\n# driver.find_element_by_id('com.android.settings:id/digit9').click()\n# driver.find_element_by_xpath(\"//android.widget.TextView[@text='Google']\").click()\n# print driver.find_element_by_name(\"1\").click()\n# time.sleep(5)\n# print \"abc\"\n# WebDriverWait(driver, 10).until(\n# EC.presence_of_element_located((By.ID, \"ctl00_ContentPlaceHolder1_repList_ctl00_hypViewBulletin\")))\ndriver.quit()\n","sub_path":"appium_test.py","file_name":"appium_test.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"203661750","text":"import scrapy\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"garbarino\"\n\n def start_requests(self):\n urls = [\n 'https://www.garbarino.com/producto/smart-tv-4k-uhd-lg-43-43uh6500/f70959cfcf'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n for price in response.css('div.gb-main-detail-prices'):\n yield {\n 'actual_price': price.css('div.gb-main-detail-prices-before::text').extract_first(),\n 'original_price': price.css('div.gb-main-detail-prices-current::text').extract_first()\n }","sub_path":"garbarino_spider.py","file_name":"garbarino_spider.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"301443719","text":"#Python Telegram Bot\n#Documentation: https://python-telegram-bot.readthedocs.io\n\nimport os.path\nfrom datetime import datetime, timezone\nfrom telegram.ext import Updater, CommandHandler\n\ndef cleAPIbot():\n\twith open('cleAPI.txt', 'r') as fichierCleAPI:\n\t\tcleAPI = fichierCleAPI.read()\n\treturn cleAPI\n\n#Interruption déclenchée à la réception de nouveau messages\ndef command_handler(update, context):\n\tglobal botActif\n\tmessage = update.message\n\texpediteur = message.from_user.username\n\tutilisateurValide = utilisateur_autorise(expediteur)\n\tcommandeRecue = message.text\n\n\t#On journalise la commande reçue\n\tjournaliserMessage(date_utc_vers_local(message.date),expediteur,utilisateurValide,'bot',commandeRecue,datetime.now())\n\n\tif utilisateurValide == True:\n\t\t#On détermine l'action à faire en fonction de la commande\n\t\tif commandeRecue == '/start' and botActif == False:\n\t\t\tbotActif = True\n\t\t\tenvoyerMessage(update, 'activation_bot')\n\t\t\tprint('Bot activé')\n\n\t\telif commandeRecue == '/stop' and botActif == True:\n\t\t\tbotActif = False\n\t\t\tenvoyerMessage(update, 'desactivation_bot')\n\t\t\tprint('Bot désactivé')\n\n\t\telif commandeRecue == '/statut':\n\t\t\tif botActif: statutBot = 'activé'\n\t\t\telse: statutBot = 'désactivé'\n\n\t\t\tenvoyerMessage(update, 'statut_bot', statutBot)\n\n#Fonction chargée de l'envoi de message standardisé à un utilisateur\ndef envoyerMessage(update, id_message, *parametre):\n\tmessage = update.message\n\texpediteur = message.from_user.username\n\n\t#On envoie le message standard en fonction de l'ID passé en argument\n\tif id_message == 'activation_bot' :\n\t\tmessageBot = \"Bot activé\"\n\n\telif id_message == 'desactivation_bot' :\n\t\tmessageBot = \"Bot désactivé\"\n\n\telif id_message == 'statut_bot':\n\t\tmessageBot = \"Le bot est actuellement %s\" % parametre[0]\n\n\tmessage.reply_text(messageBot)\n\tjournaliserMessage(datetime.now(),'bot',True,expediteur,messageBot)\n\n#Fonction servant à enregistrer les activités du chat dans un fichier de log\ndef journaliserMessage(date_envoi,expediteur,expediteur_valide,destinataire,message,date_reception=None):\n\tnomFichierLOG = 'chat.log'\n\n\t#On formate correctement les dates (retrait des millisecondes)\n\tdate_envoi = date_envoi.isoformat(\" \",\"seconds\")\n\tif date_reception != None:\n\t\tdate_reception = date_reception.isoformat(\" \",\"seconds\")\n\n\t#On prépare la ligne qui sera enregistrée dans le fichier de log\n\tentree_journal_log = '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\\n' % (date_envoi,date_reception,expediteur,destinataire,message,expediteur_valide)\n\n\t#Si le fichier de log n'existe pas, on le créé et on inscrit les titres de colonnes\n\tif os.path.exists(nomFichierLOG) == False:\n\t\twith open(nomFichierLOG,'w') as fichierLOG:\n\t\t\tfichierLOG.write('\"Date d\\'envoi\",\"Date de réception\",\"Expéditeur\",\"Destinataire\",\"Message\",\"Expéditeur autorisé\"\\n')\n\n\t#Écriture de l'entrée dans le journal\n\twith open(nomFichierLOG,'a') as fichierLOG:\n\t\tfichierLOG.write(entree_journal_log)\n\n#Convertit une date/heure UTC en date/heure locale\ndef date_utc_vers_local(date_utc):\n\tdate_locale = date_utc.replace(tzinfo=timezone.utc).astimezone(tz=None)\n\treturn date_locale.replace(tzinfo=None)\n\n#Vérifie si l'utilisateur spécifié est autorisé à dialoguer avec le bot\ndef utilisateur_autorise(utilisateurRecherche):\n\tnomFichierWhitelist = \"whitelist.txt\"\n\n\t#On récupère la liste des utilisateurs autorisés\n\twith open(nomFichierWhitelist, 'r') as fichierWhitelist:\n\t\tlisteUtilisateur = fichierWhitelist.readlines()\n\n\tfor utilisateur in listeUtilisateur:\n\t\t#On supprime le '\\n' au bout de la ligne\n\t\tutilisateur = str(utilisateur.rstrip())\n\n\t\t#S'il s'agit de l'utilisateur recherché, on renvoie True\n\t\tif utilisateur == utilisateurRecherche:\n\t\t\treturn True\n\n\t#Sinon, on renvoie False\n\treturn False\n\nbotActif = False\ncommandesAutorises = ['start','stop', 'statut']\n\n#On essaie de démarrer le bot, en cas d'echec on arrête le script\ntry:\n\t#Initialisation de l'updater avec la clé API du bot\n\tupdater = Updater(token=cleAPIbot(), use_context=True)\n\n\t#Configuration de la capture d'interruptions par le dispatcher\n\tdispatcher = updater.dispatcher\n\n\t#Ajout des différentes commandes pouvant réagir à l'interruption\n\tdispatcher.add_handler(CommandHandler(commandesAutorises, command_handler))\n\n\t#Démarrage du bot\n\tupdater.start_polling()\n\tprint(\"Bot démarré, en attente de messages...\")\n\nexcept:\n\tprint(\"Erreur d'initialisation du bot, arrêt du script\")\n\n#Empêche l'arrêt du script jusqu'à réception d'un signal d'arret (SIGINT, ...)\nupdater.idle()\n","sub_path":"script/telegram/botTelegram.py","file_name":"botTelegram.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"614742109","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 00:14:17 2020\n\n@author: shaun\n\"\"\"\nimport matplotlib as mp \nimport numpy as np\n#create the deltoid function using catesian coordinates\ndef deltoid(theta):\n x=2*np.cos(theta)+np.cos(2*theta)\n y=2*np.sin(theta)-np.sin(2*theta)\n return x,y\n#create deltoid function using polar coordinates\ndef deltoidpolar(theta):\n r=theta**2\n x=r*np.cos(theta)\n y=r*np.sin(theta)\n return x,y\n#create the fey function using polar coordinates\ndef feyfunction(theta):\n r=((np.e)**(np.cos(theta)))-2*np.cos(4*theta)+ \\\n np.sin(theta/12)**5\n x=r*np.cos(theta)\n y=r*np.sin(theta)\n return x,y\n\n#initialize list for deltoid function\nxvals=[]\nyvals=[]\nstep=np.linspace(0,2*np.pi, 100)\n# fill in list for deltoid function\nfor i in step:\n x,y=deltoid(i)\n xvals.append(x)\n yvals.append(y)\n \nfig1=mp.pyplot.figure()\nax=fig1.add_subplot(1,1,1)\nax.plot(xvals, yvals, c='b', marker=\"s\", label='Original Data')\nfig1.suptitle(\"Deltoid\")\nax.set_xlabel(r\"Angle from 0 to $2\\pi$\")\nax.set_ylabel(\"F(x)\")\n\n#initialize polar deltoid lists\nxpol=[]\nypol=[]\nstep2=np.linspace(0,10*np.pi, 100)\n# fill in list for polar deltoid function \nfor i in step2:\n x,y=deltoid(i)\n xpol.append(x)\n ypol.append(y)\n #plot \nfig2=mp.pyplot.figure()\nax1=fig2.add_subplot(1,1,1)\nax1.plot(xpol, ypol, c='b', marker=\"s\", label='Original Data')\nfig2.suptitle(\"Deltoid Polar form\")\nax1.set_xlabel(r\"Angle from 0 to $10\\pi$\")\nax1.set_ylabel(\"F(x)\")\n \n \n \n#initialize fey lists \nxfey=[]\nyfey=[] \nstep3=np.linspace(0,24*np.pi, 5000 )\n#fill in fey lists\nfor i in step3:\n x,y=feyfunction(i)\n xfey.append(x)\n yfey.append(y)\n#plot fey function\nfig3=mp.pyplot.figure()\nax2=fig3.add_subplot(1,1,1)\nax2.plot(xfey, yfey, c='b', marker=\"s\", label='Original Data')\nfig3.suptitle(\"Fey's Function\")\nax2.set_xlabel(\"Angle from 0 to $24\\pi$\")\nax2.set_ylabel(\"F(x)\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"homework2/3.2/fedrick3_2.py","file_name":"fedrick3_2.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"81160661","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 14 16:38:42 2020\n\n@author: Admin\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\ndata = np.genfromtxt(\"irispetal.csv\", delimiter=',', skip_header=1)\n\ndef softmax(z):\n exp_z = np.exp(z)\n return exp_z/np.sum(exp_z, axis=1, keepdims=True)\n\ndef cross_entropy(y, predict):\n return -np.log(predict[range(len(y)), y])\n\nclass SoftmaxRegresstion:\n def __init__(self, data, rate, miniBatchSize = None, epochs = 1000):\n data = data[:].copy()\n self.features = data[:, :-1]\n self.y = data[:, -1].astype(np.int64)\n self.rate = rate\n self.epochs = epochs\n self.nData = len(data)\n self.miniBatchSize = miniBatchSize\n self.nClass = len(np.unique(self.y))\n self.w = np.random.randn(self.features.shape[1], self.nClass)\n self.b = np.random.randn(self.nClass, )\n self.losses = []\n self.accuracy = []\n \n def run(self):\n if self.miniBatchSize == None:\n self.miniBatchSize = self.nData\n iFillter = range(self.nData)\n \n for epoch in range(self.epochs):\n if self.miniBatchSize != self.nData:\n iFillter = np.random.randint(0, self.nData, \n size=(self.miniBatchSize,))\n xFillter = self.features[iFillter]\n yFillter = self.y[iFillter]\n \n predict = softmax(xFillter.dot(self.w) + self.b)\n self.losses.append(cross_entropy(yFillter, predict).mean())\n self.accuracy.append(np.sum(np.argmax(predict, axis=1) == yFillter))\n loss_grd = predict\n loss_grd[range(self.miniBatchSize), yFillter] -= 1\n loss_grd /= self.miniBatchSize\n \n self.w -= self.rate * xFillter.T.dot(loss_grd)\n self.b -= self.rate * np.sum(loss_grd, axis=0)\n \n def showGraph(self):\n plt.figure(figsize=(10, 6))\n plt.scatter(self.features[self.y == 0][:, 0], self.features[self.y == 0][:, 1], color='b', label='0')\n plt.scatter(self.features[self.y == 1][:, 0], self.features[self.y == 1][:, 1], color='r', label='1')\n plt.scatter(self.features[self.y == 2][:, 0], self.features[self.y == 2][:, 1], color='g', label='2')\n plt.legend()\n h = 0.01\n x_min, x_max = self.features[:, 0].min() - 1, self.features[:, 0].max() + 1\n y_min, y_max = self.features[:, 1].min() - 1, self.features[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n Z = np.dot(np.c_[xx.ravel(), yy.ravel()], self.w) + self.b\n Z = np.argmax(Z, axis=1)\n Z = Z.reshape(xx.shape)\n fig = plt.figure()\n plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)\n plt.scatter(self.features[:, 0], self.features[:, 1], c=self.y, s=40, cmap=plt.cm.Spectral)\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(), yy.max())\n \na = SoftmaxRegresstion(data, 0.1)\na.run()\nplt.plot(a.accuracy)\nplt.show()","sub_path":"5_softmax_regresstion/softmaxregresstion.py","file_name":"softmaxregresstion.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"654317280","text":"#키 이벤트 발생\n\nimport numpy as np\nimport cv2\n\nswitch_case = {\n ord('a'):\"a키 입력\", #ord 함수 -문자를 아스키코드로 변환\n ord('b'):\"b키 입력\",\n 0x41:\"A키 입력\",\n int('0x42', 16):\"B키 입력\",\n 2424832 :\"왼쪽 화살표키 입력\",\n 2490368 : \"윗쪽 화살표키 입력\",\n 2555904 : \"오른쪽 화살표 키 입력\",\n 2621440: \"아래쪽 화살표 키 입력\"\n }\n\nimage = np.ones((200,300), np.uint8) #화소값이 1인 행렬 생성\ncv2.namedWindow(\"Keyboard Event\")\ncv2.imshow(\"Keyboard Event\", image)\n\nwhile True: #무한반복\n key = cv2.waitKeyEx(100) #100ms 동안 키 이벤트 대기\n if key == 27:\n break #ESC 누르면 종료\n try:\n result = switch_case[key]\n print(result)\n except KeyError:\n result = -1\n\ncv2.destroyAllWindows() #열린 모든 윈도우 제거\n","sub_path":"open3.py","file_name":"open3.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"443335102","text":"import re\n\nfrom ..hasher import Hasher\n\nfrom ..common import SHORT_ARTIFACT_ID_LEN\n\nclass BuildSpec(object):\n def __init__(self, build_spec):\n self.doc = canonicalize_build_spec(build_spec)\n self.artifact_id = get_artifact_id(self.doc)\n\n\ndef as_build_spec(obj):\n if isinstance(obj, BuildSpec):\n return obj\n else:\n return BuildSpec(obj)\n\ndef canonicalize_build_spec(spec):\n \"\"\"Puts the build spec on a canonical form + basic validation\n\n See module documentation for information on the build specification.\n\n Parameters\n ----------\n spec : json-like\n The build specification\n\n Returns\n -------\n canonical_spec : json-like\n Canonicalized and verified build spec\n \"\"\"\n def canonicalize_source_item(item):\n item = dict(item)\n item.setdefault('strip', 0)\n item.setdefault('target', '.')\n return item\n\n def canonicalize_dependency(item):\n item = dict(item)\n item.setdefault('in_path', True)\n item.setdefault('in_hdist_compiler_paths', True)\n if item.setdefault('ref', None) == '':\n raise ValueError('Empty ref should be None, not \"\"')\n item['before'] = sorted(item.get('before', []))\n return item\n\n result = dict(spec) # shallow copy\n assert_safe_name(result['name'])\n assert_safe_name(result['version'])\n\n result['dependencies'] = [\n canonicalize_dependency(item) for item in result.get('dependencies', ())]\n result['dependencies'].sort(key=lambda item: item['id'])\n \n sources = [canonicalize_source_item(item) for item in result.get('sources', ())]\n sources.sort(key=lambda item: item['key'])\n result['sources'] = sources\n\n result['files'] = sorted(result.get('files', []), key=lambda item: item['target'])\n\n return result\n\n_SAFE_NAME_RE = re.compile(r'[a-zA-Z0-9-_+]+')\ndef assert_safe_name(x):\n \"\"\"Raises a ValueError if x does not match ``[a-zA-Z0-9-_+]+``.\n\n Returns `x`\n \"\"\"\n if not _SAFE_NAME_RE.match(x):\n raise ValueError('version or name \"%s\" is empty or contains illegal characters' % x)\n return x\n\ndef get_artifact_id(build_spec, is_canonical=False):\n \"\"\"Produces the hash/\"artifact id\" from the given build spec.\n\n This can be produced merely from the textual form of the spec without\n considering any run-time state on any system.\n \n \"\"\"\n if not is_canonical:\n build_spec = canonicalize_build_spec(build_spec)\n digest = Hasher(build_spec).format_digest()\n name = assert_safe_name(build_spec['name'])\n version = assert_safe_name(build_spec['version'])\n \n return '%s/%s/%s' % (name, version, digest)\n\ndef shorten_artifact_id(artifact_id, length=SHORT_ARTIFACT_ID_LEN):\n \"\"\"Shortens the hash part of the artifact_id to the desired length\n \"\"\"\n return artifact_id[:artifact_id.rindex('/') + length + 1]\n\n","sub_path":"hashdist/core/build_store/build_spec.py","file_name":"build_spec.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"29381698","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm\nfrom .models import Profile\nfrom django.core.mail import send_mail, BadHeaderError\n\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Your account has been created! You are now able to log in')\n return redirect('login')\n else:\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST,\n request.FILES,\n instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, f'Your account has been updated!')\n return redirect('profile')\n\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n\n context = {\n 'u_form': u_form,\n 'p_form': p_form\n }\n\n return render(request, 'users/profile.html', context)\n \n@login_required\ndef notify(request):\n subject = \"A new user submitted has registered\"\n from_email = \"hello@linguainternational.org\"\n message = \"A new user registered\"\n try:\n send_mail(subject, message, from_email, ['matteo.fusilli90@gmail.com'], fail_silently=False)\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return render(request, 'users/form_submitted.html')\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"653374171","text":"\nimport os.path\nimport fnmatch\nfrom dbt.model import Model, Analysis, TestModel, SchemaFile, Csv\n\nclass Source(object):\n def __init__(self, project, own_project=None):\n self.project = project\n self.project_root = project['project-root']\n self.project_name = project['name']\n\n self.own_project = own_project if own_project is not None else self.project\n self.own_project_root = self.own_project['project-root']\n self.own_project_name = self.own_project['name']\n\n def find(self, source_paths, file_pattern):\n \"\"\"returns abspath, relpath, filename of files matching file_regex in source_paths\"\"\"\n found = []\n for source_path in source_paths:\n root_path = os.path.join(self.own_project_root, source_path)\n for root, dirs, files in os.walk(root_path):\n for filename in files:\n abs_path = os.path.join(root, filename)\n rel_path = os.path.relpath(abs_path, root_path)\n\n if fnmatch.fnmatch(filename, file_pattern):\n found.append((self.project, source_path, rel_path, self.own_project))\n return found\n\n def get_models(self, model_dirs, create_template):\n pattern = \"[!.#~]*.sql\"\n models = [Model(*model + (create_template,)) for model in self.find(model_dirs, pattern)]\n return models\n\n def get_test_models(self, model_dirs, create_template):\n pattern = \"[!.#~]*.sql\"\n models = [TestModel(*model + (create_template,)) for model in self.find(model_dirs, pattern)]\n return models\n\n def get_analyses(self, analysis_dirs):\n pattern = \"[!.#~]*.sql\"\n models = [Analysis(*analysis) for analysis in self.find(analysis_dirs, pattern)]\n return models\n\n def get_schemas(self, model_dirs):\n \"Get schema.yml files\"\n pattern = \"[!.#~]*.yml\"\n schemas = [SchemaFile(*schema) for schema in self.find(model_dirs, pattern)]\n return schemas\n\n def get_csvs(self, csv_dirs):\n \"Get CSV files\"\n pattern = \"[!.#~]*.csv\"\n csvs = [Csv(*csv) for csv in self.find(csv_dirs, pattern)]\n return csvs\n\n","sub_path":"dbt/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"553162292","text":"import asyncio\nimport ssl\nfrom urllib.parse import urlparse\n\nimport pytest\nimport aiosonic\nfrom aiosonic import _get_url_parsed\nfrom aiosonic import HttpResponse\nfrom aiosonic.connectors import TCPConnector\nfrom aiosonic.connection import Connection\nfrom aiosonic.exceptions import ConnectTimeout\nfrom aiosonic.exceptions import ReadTimeout\nfrom aiosonic.exceptions import RequestTimeout\nfrom aiosonic.exceptions import MaxRedirects\nfrom aiosonic.exceptions import HttpParsingError\nfrom aiosonic.exceptions import MissingWriterException\nfrom aiosonic.exceptions import MissingEvent\nfrom aiosonic.exceptions import ConnectionPoolAcquireTimeout\nfrom aiosonic.http2 import Http2Handler\nfrom aiosonic.pools import CyclicQueuePool\nfrom aiosonic.timeout import Timeouts\n\n\n@pytest.mark.asyncio\nasync def test_simple_get(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url)\n assert res.status_code == 200\n assert await res.content() == b'Hello, world'\n assert await res.text() == 'Hello, world'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_python():\n \"\"\"Test simple get.\"\"\"\n url = 'https://www.python.org/'\n\n client = aiosonic.HTTPClient()\n res = await client.get(\n url,\n headers={\n 'user-agent':\n ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0)'\n ' Gecko/20100101 Firefox/70.0')\n },\n http2=True)\n assert res.status_code == 200\n assert '<title>Welcome to Python.org' in await res.text()\n\n\n@pytest.mark.asyncio\nasync def test_get_http2(http2_serv):\n \"\"\"Test simple get to node http2 server.\"\"\"\n url = http2_serv\n connector = TCPConnector(timeouts=Timeouts(sock_connect=3, sock_read=4))\n\n client = aiosonic.HTTPClient(connector)\n res = await client.get(url, verify=False)\n assert res.status_code == 200\n assert 'Hello World' == await res.text()\n\n\n@pytest.mark.asyncio\nasync def test_method_lower(http2_serv):\n \"\"\"Test simple get to node http2 server.\"\"\"\n url = http2_serv\n client = aiosonic.HTTPClient()\n res = await client.request(url, method=\"get\", verify=False)\n assert res.status_code == 200\n assert 'Hello World' == await res.text()\n\n\nclass MyConnection(Connection):\n \"\"\"Connection to count keeped alives connections.\"\"\"\n def __init__(self, *args, **kwargs):\n self.counter = 0\n super(MyConnection, self).__init__(*args, **kwargs)\n\n def keep_alive(self):\n self.keep = True\n self.counter += 1\n\n\n@pytest.mark.asyncio\nasync def test_keep_alive_smart_pool(app, aiohttp_server):\n \"\"\"Test keepalive smart pool.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d' % server.port\n urlparsed = urlparse(url)\n\n connector = TCPConnector(pool_size=2, connection_cls=MyConnection)\n client = aiosonic.HTTPClient(connector)\n\n for _ in range(5):\n res = await client.get(url)\n connection = await connector.pool.acquire(urlparsed)\n assert res.status_code == 200\n assert await res.text() == 'Hello, world'\n assert connection.counter == 5\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_keep_alive_cyclic_pool(app, aiohttp_server):\n \"\"\"Test keepalive cyclic pool.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d' % server.port\n\n connector = TCPConnector(pool_size=2,\n connection_cls=MyConnection,\n pool_cls=CyclicQueuePool)\n client = aiosonic.HTTPClient(connector)\n\n for _ in range(5):\n res = await client.get(url)\n connection = await connector.pool.acquire()\n assert res.status_code == 200\n assert await res.text() == 'Hello, world'\n assert connection.counter == 2\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_with_params(app, aiohttp_server):\n \"\"\"Test get with params.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d' % server.port\n params = {'foo': 'bar'}\n\n client = aiosonic.HTTPClient()\n res = await client.get(url, params=params)\n assert res.status_code == 200\n assert await res.text() == 'bar'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_with_params_tuple(app, aiohttp_server):\n \"\"\"Test get with params as tuple.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d' % server.port\n params = (('foo', 'bar'), )\n\n client = aiosonic.HTTPClient()\n res = await client.get(url, params=params)\n assert res.status_code == 200\n assert await res.text() == 'bar'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_post_form_urlencoded(app, aiohttp_server):\n \"\"\"Test post form urlencoded.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post' % server.port\n data = {'foo': 'bar'}\n\n client = aiosonic.HTTPClient()\n res = await client.post(url, data=data)\n assert res.status_code == 200\n assert await res.text() == 'bar'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_post_tuple_form_urlencoded(app, aiohttp_server):\n \"\"\"Test post form urlencoded tuple.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post' % server.port\n data = (('foo', 'bar'), )\n\n client = aiosonic.HTTPClient()\n res = await client.post(url, data=data)\n assert res.status_code == 200\n assert await res.text() == 'bar'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_post_json(app, aiohttp_server):\n \"\"\"Test post json.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post_json' % server.port\n data = {'foo': 'bar'}\n\n client = aiosonic.HTTPClient()\n res = await client.post(url, json=data, headers=[['x-foo', 'bar']])\n assert res.status_code == 200\n assert await res.text() == 'bar'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_put_patch(app, aiohttp_server):\n \"\"\"Test put.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/put_patch' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.put(url)\n assert res.status_code == 200\n assert await res.text() == 'put_patch'\n\n client = aiosonic.HTTPClient()\n res = await client.patch(url)\n assert res.status_code == 200\n assert await res.text() == 'put_patch'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_delete(app, aiohttp_server):\n \"\"\"Test delete.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/delete' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.delete(url)\n assert res.status_code == 200\n assert await res.text() == 'deleted'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_post_multipart_to_django(live_server):\n \"\"\"Test post multipart.\"\"\"\n url = live_server.url + '/post_file'\n data = {'foo': open('tests/files/bar.txt', 'rb'), 'field1': 'foo'}\n\n client = aiosonic.HTTPClient()\n res = await client.post(url, data=data, multipart=True)\n assert res.status_code == 200\n assert await res.text() == 'bar-foo'\n\n\n@pytest.mark.asyncio\nasync def test_connect_timeout(mocker):\n \"\"\"Test connect timeout.\"\"\"\n url = 'http://localhost:1234'\n\n async def long_connect(*_args, **_kwargs):\n await asyncio.sleep(3)\n\n _connect = mocker.patch('aiosonic.connection.Connection._connect',\n new=long_connect)\n _connect.return_value = long_connect()\n connector = TCPConnector(timeouts=Timeouts(sock_connect=0.2))\n\n with pytest.raises(ConnectTimeout):\n client = aiosonic.HTTPClient(connector)\n await client.get(url)\n\n\n@pytest.mark.asyncio\nasync def test_read_timeout(app, aiohttp_server, mocker):\n \"\"\"Test read timeout.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/slow_request' % server.port\n connector = TCPConnector(timeouts=Timeouts(sock_read=0.2))\n client = aiosonic.HTTPClient(connector)\n\n with pytest.raises(ReadTimeout):\n await client.get(url)\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_timeouts_overriden(app, aiohttp_server, mocker):\n \"\"\"Test timeouts overriden.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/slow_request' % server.port\n\n # request takes 1s so this timeout should not be applied\n # instead the one provided by request call\n connector = TCPConnector(timeouts=Timeouts(sock_read=2))\n\n client = aiosonic.HTTPClient(connector)\n response = await client.get(url)\n assert response.status_code == 200\n\n with pytest.raises(ReadTimeout):\n await client.get(url, timeouts=Timeouts(sock_read=0.3))\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_request_timeout(app, aiohttp_server, mocker):\n \"\"\"Test request timeout.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post_json' % server.port\n\n async def long_request(*_args, **_kwargs):\n await asyncio.sleep(3)\n\n _connect = mocker.patch('aiosonic._do_request', new=long_request)\n _connect.return_value = long_request()\n connector = TCPConnector(timeouts=Timeouts(request_timeout=0.2))\n client = aiosonic.HTTPClient(connector)\n\n with pytest.raises(RequestTimeout):\n await client.get(url)\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_pool_acquire_timeout(app, aiohttp_server, mocker):\n \"\"\"Test pool acquirere timeout.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/slow_request' % server.port\n\n connector = TCPConnector(pool_size=1, timeouts=Timeouts(pool_acquire=0.3))\n client = aiosonic.HTTPClient(connector)\n\n with pytest.raises(ConnectionPoolAcquireTimeout):\n await asyncio.gather(\n client.get(url),\n client.get(url),\n )\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_simple_get_ssl(app, aiohttp_server, ssl_context):\n \"\"\"Test simple get with https.\"\"\"\n server = await aiohttp_server(app, ssl=ssl_context)\n url = 'https://localhost:%d' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url, verify=False)\n assert res.status_code == 200\n assert await res.text() == 'Hello, world'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_simple_get_ssl_ctx(app, aiohttp_server, ssl_context):\n \"\"\"Test simple get with https and ctx.\"\"\"\n server = await aiohttp_server(app, ssl=ssl_context)\n url = 'https://localhost:%d' % server.port\n\n ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, )\n ssl_context.check_hostname = False\n ssl_context.verify_mode = ssl.CERT_NONE\n client = aiosonic.HTTPClient()\n res = await client.get(url, ssl=ssl_context)\n assert res.status_code == 200\n assert await res.text() == 'Hello, world'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_simple_get_ssl_no_valid(app, aiohttp_server, ssl_context):\n \"\"\"Test simple get with https no valid.\"\"\"\n server = await aiohttp_server(app, ssl=ssl_context)\n url = 'https://localhost:%d' % server.port\n client = aiosonic.HTTPClient()\n\n # python 3.5 compatibility\n with pytest.raises(getattr(ssl, 'SSLCertVerificationError', ssl.SSLError)):\n await client.get(url)\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_chunked_response(app, aiohttp_server):\n \"\"\"Test get chunked response.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/chunked' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url)\n assert res.connection\n assert res.status_code == 200\n\n chunks = [b'foo', b'bar']\n\n async for chunk in res.read_chunks():\n assert chunk in chunks\n assert await res.text() == '' # chunks already readed manually\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_read_chunks_by_text_method(app, aiohttp_server):\n \"\"\"Test read chunks by text method.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/chunked' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url)\n assert res.connection\n assert res.status_code == 200\n assert await res.text() == 'foobar'\n assert await res.text() == 'foobar' # cached body in response object\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_body_gzip(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/gzip' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url,\n headers={'Accept-Encoding': 'gzip, deflate, br'})\n content = await res.content()\n assert res.status_code == 200\n assert content == b'Hello, world'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_body_deflate(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/deflate' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url,\n headers=[('Accept-Encoding', 'gzip, deflate, br')])\n content = await res.content()\n assert res.status_code == 200\n assert content == b'Hello, world'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_post_chunked(app, aiohttp_server):\n \"\"\"Test post chunked.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post' % server.port\n client = aiosonic.HTTPClient()\n\n async def data():\n yield b'foo'\n yield b'bar'\n\n res = await client.post(url, data=data())\n assert res.status_code == 200\n assert await res.text() == 'foobar'\n\n def data():\n yield b'foo'\n yield b'bar'\n yield b'a' * 14\n\n res = await client.post(url, data=data())\n assert res.status_code == 200\n assert await res.text() == 'foobaraaaaaaaaaaaaaa'\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_close_connection(app, aiohttp_server):\n \"\"\"Test close connection.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/post' % server.port\n\n connector = TCPConnector(pool_size=1, connection_cls=MyConnection)\n client = aiosonic.HTTPClient(connector)\n\n res = await client.post(url, data=b'close')\n connection = await connector.pool.acquire()\n\n assert res.status_code == 200\n assert not connection.keep\n assert await res.text() == 'close'\n\n\n@pytest.mark.asyncio\nasync def test_cache(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n client = aiosonic.HTTPClient()\n\n for time in range(520):\n url = 'http://localhost:%d/%d' % (server.port, time)\n\n await client.get(url, headers={'Accept-Encoding': 'gzip, deflate, br'})\n assert len(_get_url_parsed.cache) == 512\n assert next(iter(_get_url_parsed.cache)) == url.replace('/519', '/8')\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_close_old_keeped_conn(app, aiohttp_server):\n \"\"\"Test close old conn.\"\"\"\n server1 = await aiohttp_server(app)\n server2 = await aiohttp_server(app)\n url1 = 'http://localhost:%d' % server1.port\n url2 = 'http://localhost:%d' % server2.port\n connector = TCPConnector(pool_size=1, connection_cls=MyConnection)\n client = aiosonic.HTTPClient(connector)\n\n await client.get(url1)\n # get used writer\n connection = await connector.pool.acquire()\n writer = connection.writer\n connection = connector.pool.release(connection)\n\n await client.get(url2)\n # python 3.6 doesn't have writer.is_closing\n is_closing = getattr(writer, 'is_closing', writer._transport.is_closing)\n\n # check that old writer is closed\n assert is_closing()\n await server1.close()\n await server2.close()\n\n\n@pytest.mark.asyncio\nasync def test_get_redirect(app, aiohttp_server):\n \"\"\"Test follow redirect.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/get_redirect' % server.port\n\n client = aiosonic.HTTPClient()\n res = await client.get(url)\n assert res.status_code == 302\n\n res = await client.get(url, follow=True)\n assert res.status_code == 200\n assert await res.content() == b'Hello, world'\n assert await res.text() == 'Hello, world'\n\n url = 'http://localhost:%d/get_redirect_full' % server.port\n res = await client.get(url, follow=True)\n assert res.status_code == 200\n\n await server.close()\n\n\n@pytest.mark.asyncio\nasync def test_max_redirects(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://localhost:%d/max_redirects' % server.port\n client = aiosonic.HTTPClient()\n\n with pytest.raises(MaxRedirects):\n await client.get(url, follow=True)\n await server.close()\n\n\ndef test_parse_response_line():\n \"\"\"Test parsing response line\"\"\"\n response = HttpResponse()\n response._set_response_initial(b'HTTP/1.1 200 OK\\r\\n')\n assert response.status_code == 200\n\n\ndef test_parse_response_line_with_empty_reason():\n \"\"\"Test parsing response line with empty reason-phrase\"\"\"\n response = HttpResponse()\n response._set_response_initial(b'HTTP/1.1 200 \\r\\n')\n assert response.status_code == 200\n\n\ndef test_parse_bad_response_line():\n \"\"\"Test parsing bad response line\"\"\"\n with pytest.raises(HttpParsingError):\n HttpResponse()._set_response_initial(b'foo bar baz')\n\n\ndef test_handle_bad_chunk(mocker):\n \"\"\"Test handling chunks in chunked request\"\"\"\n with pytest.raises(MissingWriterException):\n conn = mocker.MagicMock()\n conn.writer = None\n aiosonic._handle_chunk(b'foo', conn)\n\n\n@pytest.mark.asyncio\nasync def test_sending_chunks_with_error(mocker):\n \"\"\"Sending bad chunck data type.\"\"\"\n conn = mocker.MagicMock()\n conn.writer = None\n mocker.patch('aiosonic._handle_chunk')\n\n def chunks_data():\n yield b'foo'\n\n with pytest.raises(MissingWriterException):\n await aiosonic._send_chunks(conn, chunks_data())\n\n with pytest.raises(ValueError):\n await aiosonic._send_chunks(conn, {})\n\n\n@pytest.mark.asyncio\nasync def test_connection_error(mocker):\n \"\"\"Connection error check.\"\"\"\n async def get_conn(*args, **kwargs):\n conn = Connection(connector)\n conn.connect = connect\n conn.writer = None\n return conn\n\n acquire = mocker.patch('aiosonic.TCPConnector.acquire', new=get_conn)\n connector = mocker.MagicMock()\n\n async def connect(*args, **kwargs):\n return None, None\n\n acquire.return_value = get_conn()\n connector.release.return_value = asyncio.Future()\n connector.release.return_value.set_result(True)\n\n client = aiosonic.HTTPClient()\n\n with pytest.raises(ConnectionError):\n await client.get('foo')\n\n\n@pytest.mark.asyncio\nasync def test_request_multipart_value_error():\n \"\"\"Connection error check.\"\"\"\n client = aiosonic.HTTPClient()\n with pytest.raises(ValueError):\n await client.post('foo', data=b'foo', multipart=True)\n\n\ndef test_encoding_from_header():\n \"\"\"Test use encoder from header.\"\"\"\n response = HttpResponse()\n response._set_response_initial(b'HTTP/1.1 200 OK\\r\\n')\n response._set_header('content-type', 'text/html; charset=utf-8')\n response.body = b'foo'\n assert response._get_encoding() == 'utf-8'\n\n response._set_header('content-type', 'application/json')\n assert response._get_encoding() == 'utf-8'\n\n response._set_header('content-type', 'text/html; charset=weirdencoding')\n assert response._get_encoding() == 'ascii'\n\n\n@pytest.mark.asyncio\nasync def test_json_response_parsing():\n \"\"\"Test json response parsing.\"\"\"\n response = HttpResponse()\n response._set_response_initial(b'HTTP/1.1 200 OK\\r\\n')\n response._set_header('content-type', 'application/json; charset=utf-8')\n response.body = b'{\"foo\": \"bar\"}'\n assert (await response.json()) == {'foo': 'bar'}\n\n\nclass WrongEvent:\n pass\n\n\n@pytest.mark.asyncio\nasync def test_http2_wrong_event(mocker):\n \"\"\"Test json response parsing.\"\"\"\n mocker.patch('aiosonic.http2.Http2Handler.__init__', lambda x: None)\n mocker.patch('aiosonic.http2.Http2Handler.h2conn')\n\n handler = Http2Handler()\n\n async def coro():\n pass\n\n with pytest.raises(MissingEvent):\n await handler.handle_events([WrongEvent])\n\n\n@pytest.mark.asyncio\nasync def test_get_no_hostname(app, aiohttp_server):\n \"\"\"Test simple get.\"\"\"\n server = await aiohttp_server(app)\n url = 'http://:%d' % server.port\n client = aiosonic.HTTPClient()\n\n with pytest.raises(HttpParsingError):\n await client.get(url)\n\n\n@pytest.mark.asyncio\nasync def test_wait_connections_empty(mocker):\n \"\"\"Test simple get.\"\"\"\n client = aiosonic.HTTPClient()\n assert await client.wait_requests()\n\n connector = TCPConnector(pool_cls=CyclicQueuePool)\n client = aiosonic.HTTPClient(connector)\n assert await client.wait_requests()\n\n\n@pytest.mark.asyncio\nasync def test_wait_connections_busy_timeout(mocker):\n \"\"\"Test simple get.\"\"\"\n async def long_connect(*_args, **_kwargs):\n await asyncio.sleep(1)\n return True\n\n _connect = mocker.patch('aiosonic.connectors.TCPConnector.wait_free_pool',\n new=long_connect)\n\n _connect.return_value = long_connect()\n client = aiosonic.HTTPClient()\n assert not await client.wait_requests(0)\n\n connector = TCPConnector(pool_cls=CyclicQueuePool)\n client = aiosonic.HTTPClient(connector)\n assert not await client.wait_requests(0)\n","sub_path":"tests/test_aiosonic.py","file_name":"test_aiosonic.py","file_ext":"py","file_size_in_byte":21623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"572165142","text":"def ValidateUserID():\n\tif len(UserID) != 6:\n\t\tprint ('Invalid. Please enter only 6 characters.')\n\telif ((ord(UserID[0])<= ord('Z') and ord(UserID[0])>=ord('A')) \n\tand (ord(UserID[1])<= ord(('z')) and ord(UserID[1])>=ord('a')) \n\tand (ord(UserID[2])<= ord('z') and ord(UserID[2])>=ord('a')) \nand (UserID[3:6].isdigit())):\n\t\tprint ('Correct Format. Member validation successful.')\n\t\treturn True\n\telse:\n\t\tprint ('Wrong Format. Please try again later.') \n\t\treturn False\n\nf = open('club', 'w')\nfor i in range(3): ### 3 = number of entries we are taking.\n### there's nothing specified in the question so we go with 3 for our ease\n\n\tname = raw_input('Enter member name: ')\n\tUserID = raw_input('Enter member id: ')\n\tValidation = ValidateUserID()\n\tif Validation == True:\n\t\tf.write(name+ ',' + UserID + '\\n')\n\nf.close()\n\n### Printing contents of file\nf = open('club', 'r')\nprint('\\n\\n***MEMBER NAMES AND MEMBER IDs***\\n')\nfor line in f:\n\tprint (line + '\\n')\nf.close()","sub_path":"task3.1.py","file_name":"task3.1.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"280861590","text":"\"\"\"Sphinx configuration file.\"\"\"\nfrom pkg_resources import get_distribution\n\nproject = 'python-measurement'\ncopyright = '2013, Adam Coddington'\nrelease = get_distribution('measurement').version\nversion = '.'.join(release.split('.')[:2])\n\nmaster_doc = 'index'\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.doctest',\n]\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n}\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"86058652","text":"\n#############################################################################\n#\n# PostgreSQL Enterprise Manager\n#\n# Copyright (C) 2015 - 2016, EnterpriseDB Corporation. All rights reserved.\n#\n# security_grp.py - Edit the security group .\n#\n#############################################################################\n\n\nfrom novaclient import client as novaclient\nfrom credentials import get_nova_creds\n\n\ncreds = get_nova_creds()\nnova = novaclient.Client(\"2\", **creds)\n\n\ndef security_grp():\n\ttry:\n\n\t\tsecgroup = nova.security_groups.find(name=\"default\")\n\t\t# nova.security_group_rules.create(secgroup.id,ip_protocol=\"tcp\",from_port=22,to_port=22)\n\t\tnova.security_group_rules.create(secgroup.id,ip_protocol=\"icmp\",from_port=80,to_port=8080)\n\t\treturn 0 \n\t\n\texcept Exception as e:\n\t\tprint(\"Security group not updated {0}\".format(str(e)))\n\t\treturn 1\n\n\nif __name__ == '__main__':\n\tsecurity_grp()\n","sub_path":"openstack/security_grp.py","file_name":"security_grp.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"412370370","text":"__author__ = 'guoliangwei'\n\nimport scrapy\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors import LinkExtractor\n\nclass rock_climbing_item(scrapy.Item):\n name = scrapy.Field()\n location = scrapy.Field()\n phone_number = scrapy.Field()\n offcial_website = scrapy.Field()\n description = scrapy.Field()\n\nclass rock_climbing_spider(scrapy.Spider):\n\n name = \"rock_climbing\"\n allowed_domains = [\"indoorclimbing.com\"]\n start_urls = [\n 'http://www.indoorclimbing.com/worldgyms.html'\n ]\n\n def parse(self, response):\n \n for link in response.css('div.indexcolumns > table a'):\n url = \"http://www.indoorclimbing.com/\" + link.xpath('@href').extract()[0]\n yield scrapy.Request(url,callback=self.strip)\n def strip(self,response):\n for q in response.xpath('//*[@id=\"print\"]/ol/li'):\n item = rock_climbing_item()\n item['name'] = q.xpath('b/text()').extract()[0]\n list=q.xpath('span[@class=\"red\"]/preceding-sibling::text()').extract()\n if len(list) > 2:\n item['location'] = list[0:2]\n if len(list)>=3:\n item['phone_number'] = list[2]\n list=q.xpath('span[@class=\"red\"]/following-sibling::text()').extract()\n if len(list)>0:\n item['description']=list[0]\n item['offcial_website'] = q.xpath('a/@href').extract()\n yield item\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Sportsman/crawlers/crawlers/spiders/rock_climbing.py","file_name":"rock_climbing.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"20547515","text":"from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom .forms import FoodFitnessForm\nfrom django.contrib.auth.models import User\n\n\n# function to test with\ndef index(request):\n return HttpResponse(\"You made it.\")\n\n\n# function to create new user\ndef createUser(request):\n form = FoodFitnessForm(request.POST or None)\n context = {\n \"form\": form\n }\n if request.method == \"POST\":\n print(request.POST)\n User.objects.create_user(request.POST[\"username\"], request.POST[\"calories\"], request.POST[\"date\"])\n return render(request, \"authenticationCwApp/confirmUser.html\")\n\n return render(request, 'authenticationCwApp/createUser.html', context)\n\n\n\n# function to confirm new user\ndef confirmUser(request):\n form = FoodFitnessForm(request.GET or None)\n context = {\n \"form\": form\n }\n\n if request.method == 'GET':\n User.objects.create_user(request.GET[\"username\"], \"\", request.GET[\"calories\"], request.GET[\"date\"])\n form.save()\n return HttpResponse(\"New Food Calorie Tracker Created!!!!!\")\n\n return render(request, \"authenticationCwApp/confirmUser.html\", context)\n","sub_path":"authenticationCwProject/authenticationCwApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"12588413","text":"from django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import simplejson as json\n\nfrom .models import Building\n\n\ndef building_list(request):\n response = HttpResponse(mimetype=\"application/json\")\n json.dump([\n {\"name\": b.name, \"id\": b.pk}\n for b in Building.objects.all()\n ], response)\n return response\n\ndef building_detail(request, pk):\n building = get_object_or_404(Building, pk=pk)\n response = HttpResponse(mimetype=\"application/json\")\n json.dump({\n \"name\": building.name,\n \"id\": building.pk,\n \"floors\": [\n {\"id\": f.pk, \"name\": f.name}\n for f in building.floors.all()\n ],\n }, response)\n return response\n\ndef floor_detail(request, building_pk, floor_pk):\n building = get_object_or_404(Building, pk=building_pk)\n floor = get_object_or_404(building.floors.all(), pk=floor_pk)\n response = HttpResponse(mimetype=\"application/json\")\n json.dump({\n \"name\": floor.name,\n \"id\": floor.pk,\n \"rooms\": [\n {\"id\": r.pk, \"name\": r.name, \"nickname\": r.nickname, \"capacity\": r.capacity}\n for r in floor.rooms.all()\n ]\n }, response)\n return response","sub_path":"rooms_project/rooms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"350354571","text":"import os\nimport sys\n\n\nclass Plugin:\n\n def __init__(self, GLOBAL_MODES):\n self.path = \"./packages/asteria/applications/\"\n plugins = {}\n sys.path.insert(0, self.path)\n for f in os.listdir(self.path):\n fname, ext = os.path.splitext(f)\n if ext == '.py':\n mod = __import__(fname)\n class_ = getattr(mod, mod.__name__)\n plugins[fname] = class_(GLOBAL_MODES)\n sys.path.pop(0)\n print(plugins)","sub_path":"asteria-v3/packages/asteria/modes/Plugin.py","file_name":"Plugin.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"145165526","text":"from datetime import datetime\n\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.http import JsonResponse\n\n\nclass MyJsonResponse(JsonResponse):\n\n def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs):\n data['meta'] = 'me'\n super().__init__(data, encoder, safe, json_dumps_params, **kwargs)\n\n\ndef hello(request):\n time = datetime.now().isoformat(' ')\n\n return MyJsonResponse(\n {\n 'time': time,\n 'items': [\n {\n 'username': 'Misho'\n },\n {\n 'username': 'Tsotne'\n },\n ]\n }\n )\n # return render(request, 'blog/hello.html', context={\n # 'time': time,\n # 'items': [\n # {\n # 'username': 'Misho'\n # },\n # {\n # 'username': 'Tsotne'\n # },\n # ]\n # })\n","sub_path":"back-end/djangotutorial/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"29269095","text":"from abaqus import *\nfrom abaqusConstants import *\nimport __main__\n# Import relevant modules \ndef Mode_Shape():\n import section\n import regionToolset\n import displayGroupMdbToolset as dgm\n import part\n import material\n import assembly\n import step\n import interaction\n import load\n import mesh\n import optimization\n import job\n import sketch\n import visualization\n import xyPlot\n import displayGroupOdbToolset as dgo\n import connectorBehavior\n import os\n import csv\n # Get input data from input file \n ## f = open('C:/Users/tw15036/OneDrive - University of Bristol/Documents/Year 4/GIP/InputFile.txt','r')\n ## File = f.readline()\n density = float(7850)\n elasticity = float(210000000000)\n poisson = float(0.3)\n ## if '/n' in File:\n ## File = File[0:-1]\n ## # Import geometry as STEP file to create the part, change geometryFile property for other part types\n ## filename_w_ext = os.path.basename(File)\n ## filename, file_extension = os.path.splitext(filename_w_ext)\n step = mdb.openStep(\n 'C:/Users/tw15036/OneDrive - University of Bristol/Documents/Year 4/GIP/BeamGeom.stp', \n scaleFromFile=OFF)\n mdb.models['Model-1'].PartFromGeometryFile(name='BeamGeom', geometryFile=step, \n combine=False, dimensionality=THREE_D, type=DEFORMABLE_BODY, \n scale=0.001)\n #Then change part name to Beam\n ## if filename!='Beam':\n mdb.models['Model-1'].parts.changeKey(fromName='BeamGeom', toName='Beam') # To fit with the pre-written variable names \n p = mdb.models['Model-1'].parts['Beam']\n ## material properties and name\n mdb.models['Model-1'].Material(name='Steel') # Could build in prperty inputs\n mdb.models['Model-1'].materials['Steel'].Density(table=((7850, ), ))\n mdb.models['Model-1'].materials['Steel'].Elastic(table=((210000000000, 0.3), ))\n mdb.models['Model-1'].HomogeneousSolidSection(name='Section-1', \n material='Steel', thickness=None)\n ## applying it to the model\n p = mdb.models['Model-1'].parts['Beam']\n c = p.cells\n region = (c,)\n p = mdb.models['Model-1'].parts['Beam']\n p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0, \n offsetType=MIDDLE_SURFACE, offsetField='', \n thicknessAssignment=FROM_SECTION)\n a = mdb.models['Model-1'].rootAssembly\n session.viewports['Viewport: 1'].setValues(displayedObject=a)\n session.viewports['Viewport: 1'].assemblyDisplay.setValues(\n optimizationTasks=OFF, geometricRestrictions=OFF, stopConditions=OFF)\n a = mdb.models['Model-1'].rootAssembly\n a.DatumCsysByDefault(CARTESIAN)\n p = mdb.models['Model-1'].parts['Beam']\n a.Instance(name='Beam-1', part=p, dependent=ON)\n session.viewports['Viewport: 1'].assemblyDisplay.setValues(\n adaptiveMeshConstraints=ON)\n ## create frequency analysis step\n mdb.models['Model-1'].FrequencyStep(name='Frequency', previous='Initial', \n limitSavedEigenvectorRegion=None, numEigen=10) # numEigen = no of modes analysed\n session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Frequency')\n session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=ON, bcs=ON, \n predefinedFields=ON, connectors=ON, adaptiveMeshConstraints=OFF)\n ## Clamped boundary conditions\n session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Initial')\n a = mdb.models['Model-1'].rootAssembly\n f1 = a.instances['Beam-1'].faces\n fixed_ptx=0\n fixed_pty=0\n fixed_ptz=0\n fixed_pt=(fixed_ptx,fixed_pty,fixed_ptz)\n fixed_end_face = f1.findAt((fixed_pt,))\n myRegion = regionToolset.Region(faces=fixed_end_face)\n mdb.models['Model-1'].EncastreBC(name='Clamped-1', createStepName='Initial', \n region=myRegion, localCsys=None)\n session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=OFF, \n engineeringFeatures=OFF, mesh=ON)\n session.viewports['Viewport: 1'].partDisplay.meshOptions.setValues(\n meshTechnique=ON)\n ## Viewport\n p1 = mdb.models['Model-1'].parts['Beam']\n session.viewports['Viewport: 1'].setValues(displayedObject=p1)\n ##Meshing\n p = mdb.models['Model-1'].parts['Beam']\n c=p.cells\n e=p.edges\n pickedregions=(c)\n p.setMeshControls(regions=pickedregions, elemShape=HEX)\n elemType1 = mesh.ElemType(elemCode=C3D20R, elemLibrary=STANDARD)\n elemType2 = mesh.ElemType(elemCode=C3D15, elemLibrary=STANDARD)\n elemType3 = mesh.ElemType(elemCode=C3D10, elemLibrary=STANDARD)\n p = mdb.models['Model-1'].parts['Beam']\n c = p.cells\n cells = c[0]\n pickedRegions =(cells, )\n p.setElementType(regions=pickedRegions, elemTypes=(elemType1, elemType2, \n elemType3))\n ##Seeding edge - short xy edges\n ## e1=e.findAt(([0.015,0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## e1=e.findAt(([-0.015,0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## e1=e.findAt(([0.015,-0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## e1=e.findAt(([-0.015,-0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## e1=e.findAt(([0,0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## e1=e.findAt(([0,-0.001,0.037],))\n ## p.seedEdgeByNumber(edges=e1, number=4)\n ## long z-dir sides\n e1=e.findAt(([0.015,0.001,0.37],))\n p.seedEdgeByNumber(edges=e1, number=27)\n e1=e.findAt(([-0.015,0.001,0.37],))\n p.seedEdgeByNumber(edges=e1, number=27)\n e1=e.findAt(([0.015,-0.001,0.37],))\n p.seedEdgeByNumber(edges=e1, number=27)\n e1=e.findAt(([-0.015,-0.001,0.37],))\n p.seedEdgeByNumber(edges=e1, number=27)\n ## short x-dir sides\n ## e1=e.findAt(([0.01,0.001,0],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([-0.01,0.001,0],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([0.01,-0.001,0],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([-0.01,-0.001,0],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([0.01,0.001,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([-0.01,0.001,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([0.01,-0.001,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## e1=e.findAt(([-0.01,-0.001,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=3)\n ## longer x-dir sides\n e1=e.findAt(([0,-0.001,0.65],))\n p.seedEdgeByNumber(edges=e1, number=5)\n e1=e.findAt(([0,-0.001,0.65],))\n p.seedEdgeByNumber(edges=e1, number=5)\n e1=e.findAt(([0,-0.001,0],))\n p.seedEdgeByNumber(edges=e1, number=5)\n e1=e.findAt(([0,-0.001,0],))\n p.seedEdgeByNumber(edges=e1, number=5)\n ## vertical edges\n e1=e.findAt(([0.015,0,0],))\n p.seedEdgeByNumber(edges=e1, number=2)\n e1=e.findAt(([-0.015,0,0],))\n p.seedEdgeByNumber(edges=e1, number=2)\n ## e1=e.findAt(([0,0,0],))\n ## p.seedEdgeByNumber(edges=e1, number=2)\n ## e1=e.findAt(([-0.015,0,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=2)\n ## e1=e.findAt(([0.015,0,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=2)\n ## e1=e.findAt(([0,0,0.075],))\n ## p.seedEdgeByNumber(edges=e1, number=2)\n e1=e.findAt(([0.015,0,0.65],))\n p.seedEdgeByNumber(edges=e1, number=2)\n e1=e.findAt(([-0.015,0,0.65],))\n p.seedEdgeByNumber(edges=e1, number=2) \n p = mdb.models['Model-1'].parts['Beam']\n p.generateMesh()\n ##Viewport\n a = mdb.models['Model-1'].rootAssembly\n a.regenerate()\n ## ACCELEROMETER INERTIAS\n # End of main beam\n a = mdb.models['Model-1'].rootAssembly\n pt1 = (0,0.001,0.645)\n a.ReferencePoint(point=pt1)\n r1 = a.referencePoints\n region2=a.Set(referencePoints=(r1[5],), name='Set-Acc1')\n mdb.models['Model-1'].rootAssembly.engineeringFeatures.PointMassInertia(\n name='AccInertia-1', region=region2, mass=0.006, alpha=0.0, composite=0.0)\n s1 = a.instances['Beam-1'].faces\n side1Faces1 = s1.findAt((pt1,))\n region1=a.Surface(side1Faces=side1Faces1, name='TopMainBeam')\n mdb.models['Model-1'].Tie(name='AccTie-1', master=region1, slave=region2, \n positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, \n thickness=ON)\n # 2/3 along beam\n a = mdb.models['Model-1'].rootAssembly\n pt1 = (0,0.001,0.433)\n a.ReferencePoint(point=pt1)\n r1 = a.referencePoints\n region2=a.Set(referencePoints=(r1[8],), name='Set-Acc2')\n mdb.models['Model-1'].rootAssembly.engineeringFeatures.PointMassInertia(\n name='AccInertia-2', region=region2, mass=0.006, alpha=0.0, composite=0.0)\n s1 = a.instances['Beam-1'].faces\n side1Faces1 = s1.findAt((pt1,))\n region1=a.Surface(side1Faces=side1Faces1, name='TopCrossBeam')\n mdb.models['Model-1'].Tie(name='AccTie-2', master=region1, slave=region2, \n positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, \n thickness=ON)\n # 1/3 along beam\n a = mdb.models['Model-1'].rootAssembly\n pt1 = (0,0.001,0.217)\n a.ReferencePoint(point=pt1)\n r1 = a.referencePoints\n region2=a.Set(referencePoints=(r1[11],), name='Set-Acc3')\n mdb.models['Model-1'].rootAssembly.engineeringFeatures.PointMassInertia(\n name='AccInertia-3', region=region2, mass=0.006, alpha=0.0, composite=0.0)\n s1 = a.instances['Beam-1'].faces\n side1Faces1 = s1.findAt((pt1,))\n region1=a.Surface(side1Faces=side1Faces1, name='TopCrossBeam')\n mdb.models['Model-1'].Tie(name='AccTie-3', master=region1, slave=region2, \n positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, \n thickness=ON)\n##Apply Loading\n mdb.models['Model-1'].StaticStep(name='Step-1', previous='Initial', nlgeom=ON)\n instanceNodes = mdb.models['Model-1'].rootAssembly.instances['Beam-1'].nodes\n #Import Forces\n file=csv.reader(open('C:\\\\Users\\\\tw15036\\\\OneDrive - University of Bristol\\\\Documents\\\\Year 4\\\\GIP\\\\Abaqus Output Files\\\\myFile2.csv','r'))\n n=[]\n for row in file:\n n.append(row)\n for i in range(0,len(n)): \n #nodeLabel = tuple(range(1,100))\n nodeLabel=[i]\n [cf11,cf22,cf33]=map(float,n[i])\n meshNodeObj = instanceNodes.sequenceFromLabels(nodeLabel)\n myRegion = regionToolset.Region(nodes=meshNodeObj)\n mdb.models['Model-1'].ConcentratedForce(name='Load-'+str(i), createStepName='Step-1', \n region=myRegion, cf1=cf11, cf2=cf22, cf3=cf33, distributionType=UNIFORM, field='', \n localCsys=None)\n## Run job\n mdb.Job(name='Mode_Shape', model='Model-1', description='Mode Shape', \n type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None, \n memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True, \n explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF, \n modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='', \n scratch='', resultsFormat=ODB, multiprocessingMode=DEFAULT, numCpus=1, \n numGPUs=0)\n mdb.jobs['Mode_Shape'].submit(consistencyChecking=OFF)\nMode_Shape()\n\n##def Saving():\n## import section\n## import regionToolset\n## import displayGroupMdbToolset as dgm\n## import part\n## import material\n## import assembly\n## import step\n## import interaction\n## import load\n## import mesh\n## import optimization\n## import job\n## import sketch\n## import visualization\n## import xyPlot\n## import displayGroupOdbToolset as dgo\n## import connectorBehavior\n## #mdb.saveAs(pathName='C:/Users/tw15036/OneDrive - University of Bristol/Documents/Year 4/ExperimentalBeamFreq')\n## mdb.saveAs(pathName='C:/temp/ExperimentalBeamFreq')\n##Saving()\n\n## o3 = session.openOdb(name='C:/temp/Frequency.odb')\n## session.viewports['Viewport: 1'].setValues(displayedObject=o3)\n## session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=3)\n## session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=3)\n## session.animationController.setValues(animationType=HARMONIC, viewports=(\n## 'Viewport: 1', ))\n## session.animationController.play(duration=UNLIMITED)\n## session.animationController.setValues(animationType=TIME_HISTORY)\n## session.animationController.play(duration=UNLIMITED)\n## session.animationController.setValues(animationType=SCALE_FACTOR)\n## session.animationController.play(duration=UNLIMITED)\n## session.animationController.setValues(animationType=HARMONIC)\n## session.animationController.play(duration=UNLIMITED)\n## session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=3)\n## session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=3)\n## session.viewports['Viewport: 1'].odbDisplay.display.setValues(plotState=(\n## CONTOURS_ON_DEF, ))\n\n\n","sub_path":"NLFEA_mk2/Canti/Mode_Shape.py","file_name":"Mode_Shape.py","file_ext":"py","file_size_in_byte":12913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"365028640","text":"import time\nimport numpy as np\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport scipy.signal as signal\n\n# silence harmless warnings\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", module=\"numpy.ma\", category=np.RankWarning)\nwarnings.filterwarnings(action=\"ignore\", category=RuntimeWarning)\n\n\ndef fS(waves, calcs, wfin=\"wf_trap\", calc=\"fS\"):\n \"\"\"\n grab first ADC sample of each trap-filtered waveform\n \"\"\"\n wfs = waves[wfin]\n\n # grab first samle\n first_sample = wfs[:, 0]\n\n # add the result as a new column\n calcs[calc] = first_sample\n\n\ndef avg_bl(waves, calcs, ilo=0, ihi=500, wfin=\"waveform\", calc=\"bl_p0\", test=False):\n \"\"\"\n simple mean, vectorized baseline calculator\n \"\"\"\n wfs = waves[\"waveform\"]\n\n # find wf means\n avgs = np.mean(wfs[:, ilo:ihi], axis=1)\n\n # add the result as a new column\n calcs[calc] = avgs\n\n if test:\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n plt.plot(ts, wf, '-b', lw=2, alpha=0.7, label='raw wf')\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel(\"ADC\", ha='right', y=1)\n plt.legend()\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.001)\n\n\ndef dADC(waves, calcs, ilo_1=0, ihi_1=500, ilo_2=1499, ihi_2=3000, wfin=\"waveform\", calc=\"dADC\", test=False):\n \"\"\"\n subtracting average inside a window on baseline from average inside window on tail\n \"\"\"\n wfs = waves[\"waveform\"]\n\n # find wf means\n dADC = np.mean(wfs[:, ilo_2:ihi_2], axis=1) - np.mean(wfs[:, ilo_1:ihi_1], axis=1)\n\n # add the result as a new column\n calcs[calc] = dADC\n\n if test:\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n plt.plot(ts, wf, '-b', lw=2, alpha=0.7, label='raw wf')\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel(\"ADC\", ha='right', y=1)\n plt.legend()\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.001)\n\n\ndef fit_bl(waves, calcs, ilo=0, ihi=500, order=1, wfin=\"waveform\", test=False):\n \"\"\"\n baseline calculator, uses np.polyfit\n discussed on a Feb 2019 legend S/A call that using a 2nd order term\n in the baseline might be useful in high event-rate situations where the\n baseline hasn't yet fully recovered to flat. it's also good to reject noise\n \"\"\"\n wfs = waves[wfin]\n\n # grab baselines\n x = np.arange(ilo, ihi)\n wfbl = wfs[:, ilo:ihi]\n\n # run polyfit\n pol = np.polyfit(x, wfbl.T, order).T\n pol = np.flip(pol, 1) # col0:p0, col1:p1, col2:p2, etc.\n wfstd = np.std(wfbl, axis=1) # get the rms noise too\n\n # save results\n calcs[\"bl_rms\"] = wfstd\n for i, col in enumerate(pol.T):\n calcs[\"bl_p{}\".format(i)] = col\n\n if test:\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n ts = np.arange(wfs[iwf].shape[0])\n plt.plot(ts, wfs[iwf], '-k', label=wfin)\n\n blwf, blts = wfbl[iwf], np.arange(len(wfbl[iwf]))\n plt.plot(blts, blwf, '-r')\n\n b, m = pol[iwf]\n fit = lambda t: m * t + b\n plt.plot(blts, fit(blts), c='k', lw=3,\n label='baseline, pol1: \\n{:.2e}*ts + {:.1f}'.format(m, b))\n\n plt.xlim(0, 1100)\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend(loc=2)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef get_max(waves, calcs, wfin=\"wf_trap\", calc=\"trap_max\", test=False):\n \"\"\"\n calculate maxima of each row of a waveform block (e.g. a trap filter).\n note that this is very general and works w/ any wf type.\n creates two columns: max value, and index of maximum.\n \"\"\"\n wfs = waves[wfin]\n clk = waves[\"settings\"][\"clk\"] # Hz\n\n maxes = np.amax(wfs, axis=1)\n imaxes = np.argmax(wfs, axis=1)\n\n cname = wfin.split(\"_\")[-1]\n calcs[\"{}_max\".format(cname)] = maxes\n calcs[\"{}_imax\".format(cname)] = imaxes\n\n if test:\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n plt.plot(ts, wfs[iwf], '-k', label=wfin)\n\n raw_wf = waves[\"wf_blsub\"][iwf]\n raw_wf *= np.amax(wf) / np.amax(raw_wf)\n ts = np.arange(len(wf))\n\n plt.plot(ts, raw_wf, '-b', alpha=0.7, label=\"raw_wf, normd\")\n plt.plot(ts, wf, \"-k\", label=wfin)\n plt.plot(ts[imaxes[iwf]], maxes[iwf], \".m\", ms=20, label=\"max\")\n\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend(loc=2)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\ndef get_zacmax(waves, calcs, wfin=\"wf_zac\", calc=\"zac_max\", test=False):\n \"\"\"\n calculate maxima of each row of a waveform block\n creates two columns: max value and index of maximum.\n \"\"\"\n wfs = waves[wfin]\n clk = waves[\"settings\"][\"clk\"] # Hz\n \n maxes = np.amax(wfs, axis=1)\n imaxes = np.argmax(wfs, axis=1)\n \n cname = wfin.split(\"_\")[-1]\n calcs[\"{}_max\".format(cname)] = maxes\n calcs[\"{}_imax\".format(cname)] = imaxes\n \n if test:\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n print(\"zac max = \",maxes[iwf])\n print(\"zac max position = \", imaxes[iwf])\n plt.cla()\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n plt.plot(ts, wfs[iwf], '-k', label=wfin)\n plt.plot(ts[imaxes[iwf]], maxes[iwf], \".m\", ms=20, label=\"max\")\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend()\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n \n\ndef timepoint(waves, calcs, pct, wfin=\"wf_savgol\", calc=\"tp\", test=False):\n \"\"\"\n for an estimate of where the wf tail starts, just use pct = 100 + (delta).\n \"\"\"\n wfs = waves[wfin]\n max = wfin.split('_')[-1] + \"_max\"\n smax = calcs[max].values\n\n for p in pct:\n tp_idx = np.argmax(wfs >= smax[:, None] * (p / 100.), axis=1)\n calcs[\"tp{}\".format(p)] = tp_idx\n\n if test:\n wfraw = waves[\"wf_blsub\"]\n iwf = -1\n while True:\n if iwf != -1:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n iwf += 1\n print(iwf)\n\n wf = wfs[iwf]\n ts = np.arange(len(wf))\n\n plt.cla()\n plt.plot(ts, wfraw[iwf], \"-b\", alpha=0.6, label='raw wf')\n plt.plot(ts, wf, \"-k\", label=wfin)\n\n cmap = plt.cm.get_cmap('jet', len(pct) + 1)\n for i, tp in enumerate(pct):\n\n idx = calcs[\"tp{}\".format(tp)].iloc[iwf]\n print(\"tp{}: idx {} val {:.2f}\".format(tp, idx, wf[idx]))\n\n plt.plot(idx, wf[idx], \".\", c=cmap(i), ms=20,\n label=\"tp{}\".format(tp))\n\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel(\"ADC\", ha='right', y=1)\n plt.legend()\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef ftp(waves, calcs, wf1=\"wf_etrap\", wf2=\"wf_atrap\", test=False):\n \"\"\"\n Jason says the fixed time pickoff for MJD ends up being 2 us into the\n 2.5 us trap, and the choice is not super important.\n\n Ian says the trap flat top needs to be as long as a typical rising edge,\n should verify that 2.5 us is good enough for MJ60\n\n It looks like the asym trap (0.04-0.1-2) is much better at finding\n the t0 time than the short trap (1-1.5-1). And, by padding it half the\n asym trap's width (in `transforms.trap`), the t0 we find is actually a\n pretty good t0 estimate for the raw waveform as well.\n \"\"\"\n wflong = waves[wf1]\n wfshort = waves[wf2]\n\n # get trap settings from metadata\n trap1, trap2 = None, None\n for tr in waves[\"settings\"][\"trap\"]:\n if tr[\"wfout\"] == wf1: trap1 = tr\n if tr[\"wfout\"] == wf2: trap2 = tr\n\n # define the fixed time pickoff based on the energy trap settings\n nsamp = 1e10 / waves[\"settings\"][\"clk\"]\n ftp = int(nsamp * (trap1[\"rise\"] + trap1[\"flat\"]))\n\n # \"walk back\" from the short trap's max to get t0.\n # this is less dependent on the trap's baseline noise.\n # Majorana uses a threshold of 2 ADC, hardcoded.\n thresh = 2\n short = wf2.split(\"_\")[-1]\n t0 = np.zeros(wfshort.shape[0], dtype=int)\n\n # print(\"WFSHAPE\",wfshort.shape, short)\n # print(calcs.columns)\n # print(calcs)\n # exit()\n\n # damn, i guess i have to loop over the rows\n for i, wf in enumerate(wfshort):\n try:\n imax = calcs[short + \"_imax\"].iloc[i]\n except:\n print(\"it happened again!\")\n exit()\n trunc = wfshort[i][:imax][::-1]\n t0[i] = len(trunc) - np.where(trunc < thresh)[0][0]\n\n # save the t0 idx\n calcs['t0'] = t0\n\n # save the t_ftp idx\n t_ftp = t0 + ftp\n t_ftp[t_ftp >= wflong.shape[1]] = 0 # if t_ftp > len(wf), it failed\n calcs['t_ftp'] = t_ftp\n\n # save the e_ftp energy\n row_idx = np.arange(wflong.shape[0])\n e_ftp = wflong[np.arange(wflong.shape[0]), t_ftp]\n calcs['e_ftp'] = e_ftp\n\n if test:\n\n wfs = waves[\"wf_blsub\"]\n wfsg = waves[\"wf_savgol\"]\n\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n\n plt.cla()\n plt.plot(ts, wf, '-k', lw=2, alpha=0.5, label='raw wf')\n plt.plot(ts, wfsg[iwf], '-k', lw=1, label='savgol wf')\n plt.plot(ts, wflong[iwf], '-r', label='long: ' + wf1)\n plt.plot(ts, wfshort[iwf], '-b', label='short: ' + wf2)\n\n smax = calcs[short+\"_max\"].iloc[iwf]\n simax = calcs[short+\"_imax\"].iloc[iwf]\n plt.plot(ts[simax], smax, \".k\", ms=20, label=\"short trap max\")\n\n # t0 and t_ftp\n plt.plot(\n ts[t0[iwf]], wfshort[iwf][t0[iwf]], '.g', ms=20, label=\"t0\")\n plt.axvline(\n t_ftp[iwf], c='orange', lw=2, label=\"t_ftp: {}\".format(ftp))\n\n # e_ftp\n plt.axhline(\n e_ftp[iwf], c='g', label=\"e_ftp: {:.2f}\".format(e_ftp[iwf]))\n\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel(\"ADC\", ha='right', y=1)\n plt.legend(loc=2, fontsize=12)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.001)\n\n\ndef num_peaks(waves, calcs, wfin=\"wf_maxc\", test=False):\n \"\"\"\n take the peakdet wf block and output:\n - the number of maxima\n - the sum of all the maxima\n \"\"\"\n pks = waves[wfin]\n\n npeaks = np.count_nonzero(pks, axis=1)\n nsum = np.sum(pks, axis=1)\n\n calcs[\"n_curr_pks\"] = npeaks\n calcs[\"s_curr_pks\"] = nsum\n\n if test:\n wfs = waves[\"wf_notch\"]\n wfc = waves[\"wf_current\"]\n\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n\n plt.cla()\n plt.plot(ts, wf / np.amax(wf), '-k', lw=2, alpha=0.5,\n label='raw wf')\n plt.plot(ts, wfc[iwf] / np.amax(wfc[iwf]), '-b',\n label='current wf, {} pks found'.format(npeaks[iwf]))\n\n ipk = np.where(pks[iwf] > 0)\n for pk in ipk[0]:\n plt.plot(ts[ipk], pks[iwf][ipk] / np.amax(wfc[iwf]), \".m\", ms=20)\n\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend()\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef overflow(waves, calcs, wfin=\"wf_blsub\", nbit=14, test=False):\n \"\"\"\n simple overflow checker. asks if the max value is at the limit\n of the digitizer's range. clint had to add a 0.45 factor to get the\n MJ60 wfs to be correctly tagged (ben used 0.5)\n \"\"\"\n wfs = waves[\"wf_blsub\"]\n maxes = np.amax(wfs, axis=1)\n ovr = maxes > 0.45 * 2**nbit\n calcs[\"overflow\"] = ovr\n\n if test:\n iwf = 9\n while True:\n if iwf != 9:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n wf, ts = wfs[iwf], np.arange(wfs[iwf].shape[0])\n\n plt.cla()\n plt.plot(\n ts, wf, '-k', label='raw wf. overflow? {}'.format(ovr[iwf]))\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend(loc=4)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef tail_fit(waves, calcs, wfin=\"wf_blsub\", delta=1, tp_thresh=0.8, n_check=3,\n order=1, vec=True, test=False):\n \"\"\"\n this is a \"fast\" wf fit, not a super duper accurate (slow) one.\n since curve_fit can't be vectorized, this uses np.polyfit.\n we take the log of the wf tail, then fit to a 1st-order pol.\n y(t) = log(A exp(-t/tau)) = log(A) + (-1/tau) * t\n = pfit[0] + pfit[1] * t\n amp = np.exp(pfit[0])\n tau = -1 / pfit[1]\n \"\"\"\n wfs = waves[wfin]\n ts = np.arange(wfs.shape[1])\n\n # add a delta to the 100 pct timepoint so we're sure we're on the tail\n nsamp = 1e10 / waves[\"settings\"][\"clk\"] # Hz\n dt = int(nsamp * delta)\n tp100 = calcs[\"tp100\"] + dt\n\n # fix out of range timepoints\n tp100[tp100 > tp_thresh * wfs.shape[1]] = 0\n\n # create a masked array to handle the different-length wf tails\n tails = np.full_like(wfs, np.nan)\n for i, tp in enumerate(tp100):\n tails[i, tp:] = wfs[i, tp:]\n tails = np.ma.masked_invalid(tails)\n log_tails = np.ma.log(tails) # suppress neg value warnings\n\n t_start = time.time()\n if vec:\n \"\"\"\n run the vectorized fit, which is faster but sensitive to timepoints\n being too near the end of the wfs -- it throws off the whole matrix.\n so check the fit results against `n_check` random single tail fits.\n \"\"\"\n pfit = np.ma.polyfit(ts, log_tails.T, 1).T\n\n amps = np.exp(pfit[:,1])\n taus = -1 / pfit[:,0]\n calcs[\"tail_amp\"] = amps\n calcs[\"tail_tau\"] = taus\n\n # run a second, higher-order fit to estimate error\n # (i'm lazy and did this instead of returning the covariance matrix)\n pol_fit = np.ma.polyfit(ts, log_tails.T, order).T\n pol_fit = np.flip(pol_fit, axis=1)\n for i, col in enumerate(pol_fit.T):\n calcs[\"tail_p{}\".format(i)] = col\n\n for iwf in np.random.choice(log_tails.shape[0], n_check):\n check_fit = np.ma.polyfit(ts, log_tails[iwf], order)\n ch_amp = np.exp(check_fit[1])\n ch_tau = -1 / check_fit[0]\n\n # if within 90%, they're fine. a polyfit mistake is OOM wrong\n pct1 = 100 * (ch_amp - amps[iwf]) / amps[iwf]\n pct2 = 100 * (ch_tau - taus[iwf]) / taus[iwf]\n if (pct1 > 90) | (pct2 > 90):\n print(\"WARNING: there are probably invalid values in tails.\")\n print(\"iwf {}, check amp: {:.3e} tau: {:.3e}\".format(iwf, ch_amp, ch_tau))\n print(\" original amp: {:.3e} tau: {:.3e}\".format(amps[iwf], taus[iwf]))\n print(\" amp pct diff: {:.2f}% tau: {:.2f}%\".format(pct1, pct2))\n else:\n \"\"\"\n run a non-vectorized fit with np.polyfit and np.apply_along_axis.\n for 200 wfs, this is about half as fast as the vectorized mode.\n \"\"\"\n def poly1d(wf, ts, ord):\n if np.ma.count(wf)==0:\n return np.array([1, 0])\n return np.ma.polyfit(wf, ts, ord)\n\n if len(log_tails):\n pfit = np.apply_along_axis(poly1d, 1, log_tails, ts, order)\n\n amps = np.exp(pfit[:,1])\n taus = -1 / pfit[:,0]\n calcs[\"tail_amp\"] = amps\n calcs[\"tail_tau\"] = taus\n\n # print(\"Done. Elapsed: {:.2e} sec.\".format(time.time()-t_start))\n # exit()\n\n if test:\n wfbl = waves[\"wf_blsub\"]\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n plt.plot(ts, wfs[iwf], '-k', label=wfin)\n plt.plot(ts, wfbl[iwf], '-b', alpha=0.4, label=\"wf_blsub\")\n\n # get the wf tail\n wf_tail = np.ma.filled(tails[iwf,:], fill_value = np.nan)\n idx = np.where(~np.isnan(wf_tail))\n wf_tail, ts_tail = wf_tail[idx], ts[idx]\n plt.plot(ts_tail, wf_tail, '-g', label='tail')\n\n # show the np.polyfit result\n amp, tau = amps[iwf], taus[iwf]\n plt.plot(ts_tail, amp * np.exp(-ts_tail/tau), '-r',\n label=\"polyfit dc: {:.1f}\".format(tau/100))\n\n # compare against curve_fit, with exponential. (not easily vectorized)\n from scipy.optimize import curve_fit\n tmax = np.amax(wf_tail)\n def gaus(t, a, tau):\n return a * np.exp(-t/tau)\n pars, pcov = curve_fit(gaus, ts_tail, wf_tail,\n p0=(tmax,8000),\n bounds=[[0.8*tmax, 5000],[1.2*tmax, 20000]])\n perr = np.sqrt(np.diag(pcov))\n dc, dc_err = pars[1] / 100, perr[1] / 100\n plt.plot(ts_tail, gaus(ts_tail, *pars), '-m', lw=3,\n label=\"curve_fit dc: {:.1f} +/- {:.3f}\".format(dc, dc_err))\n\n plt.xlabel(\"clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend(loc=4)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef dcr(waves, calcs, delta=1, t_win2=25, wlen=2, tp_thresh=0.8, wfin=\"wf_savgol\", test=False):\n \"\"\"\n calculate the slope of the wf tail from taking the average of two windows.\n first one is a (tp100+delta), the second one is (t_win2).\n (delta, t_win2, wlen) are in us.\n\n TODO:\n - try \"true\" pole zero correction: (applying de-convolution of the full\n channel-specific electronic response function before searching for a\n remaining slow component. i.e. use `wf_pz` as the input)\n - charge trapping correction, v1 (ftp vs trap_max energy params, this\n is the \"effective pole zero\" described in the DCR unidoc)\n - charge trapping correction, v2 (use drift time (tp20-t0) to calculate\n the expected amount of charge lost in the bulk.)\n - could try fitting each window to a line with np.polyfit, then comparing\n the two slopes\n - add a \"mode\" option which selects the various improvements above.\n \"\"\"\n wfs = waves[wfin]\n ts = np.arange(wfs.shape[1])\n\n # add a delta to the 100 pct timepoint so we're sure we're on the tail\n nsamp = 1e10 / waves[\"settings\"][\"clk\"] # Hz\n win = int(nsamp * wlen)\n dt = int(nsamp * delta)\n tp100 = calcs[\"tp100\"] + dt\n iwin2 = int(nsamp * t_win2)\n\n # fix out of range timepoints\n tp100[tp100 > tp_thresh * wfs.shape[1]] = 0\n\n # compute average in window 1 (use masked arrays)\n win_1 = np.full_like(wfs, np.nan)\n for i, ilo in enumerate(tp100):\n win_1[i, ilo:ilo+win] = wfs[i, ilo:ilo+win]\n win_1 = np.ma.masked_invalid(win_1)\n avg_1 = np.sum(win_1, axis=1) / np.count_nonzero(win_1, axis=1)\n\n # compute average in window 2 (always fixed)\n win_2 = np.full_like(wfs, np.nan)\n win_2[:, iwin2:iwin2+win] = wfs[:, iwin2:iwin2+win]\n win_2 = np.ma.masked_invalid(win_2)\n avg_2 = np.sum(win_2, axis=1) / np.count_nonzero(win_2, axis=1)\n\n # get two-point tail slope\n # sig = (y1 - y2) / (t1 - t2) # pg 4, dcr unidoc\n y1, y2 = avg_1, avg_2\n t1 = (tp100.values) + win/2\n t2 = (iwin2 + win/2) * np.ones_like(tp100.values)\n num, den = y1 - y2, t1 - t2\n slope = np.divide(num, den)\n\n # # apply charge trapping correction (\"v1\", pg. 12 of DCR unidoc).\n # relies on input parameters A and \\lambda. Maybe better to do this\n # in Tier 2 processing, or skip straight to the v2 algorithm\n # e_max, e_ftp = calcs[\"etrap_max\"], calcs[\"e_ftp\"]\n\n # # apply charge trapping correction (\"v2\")\n # t0, t20 = calcs[\"t0\"], calcs[\"tp50\"]\n # drift_time = t20 - t0\n\n # name the output parameter based on the input wf name\n wf_type = wfin.split(\"_\")[-1]\n calcs[\"tslope_{}\".format(wf_type)] = slope\n\n if test:\n wfbl = waves[\"wf_blsub\"]\n # from pygama.utils import set_plot_style\n # set_plot_style(\"clint\")\n iwf = 2\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n if inp == \"p\": iwf -= 2\n if inp.isdigit(): iwf = int(inp) - 1\n iwf += 1\n print(iwf)\n plt.cla()\n plt.plot(ts, wfs[iwf], '-k', label=wfin)\n plt.plot(ts, wfbl[iwf], '-b', alpha=0.4, label=\"wf_blsub\")\n\n idx1 = np.where(~np.isnan(win_1[iwf]))\n idx2 = np.where(~np.isnan(win_2[iwf]))\n\n plt.plot(ts[idx1], win_1[iwf][idx1], '-r', lw=10, alpha=0.5)\n plt.plot(ts[idx2], win_2[iwf][idx2], '-r', lw=10, alpha=0.5)\n\n slo = (avg_1[iwf] - avg_2[iwf]) / (t1[iwf] - t2[iwf])\n xv = np.arange(t1[iwf], t2[iwf])\n yv = slo * (xv - t1[iwf]) + avg_1[iwf]\n\n plt.plot(xv, yv, '-r', label=\"slope: {:.2e}\".format(slo))\n # plt.plot(np.nan, np.nan, \".w\", label=\"main: {:.2e}\".format(slope[iwf]))\n\n plt.plot(t1[iwf], avg_1[iwf], \".g\", ms=20)\n plt.plot(t2[iwf], avg_2[iwf], \".g\", ms=20)\n\n plt.xlabel(\"Clock ticks\", ha='right', x=1)\n plt.ylabel('ADC', ha='right', y=1)\n plt.legend(loc=4)\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(0.01)\n\n\ndef drift_time(waves, calcs, test=False):\n \"\"\"\n do the tp[pct] - t0 time.\n could maybe also try a np polyfit to roughly\n estimate the curvature? idk, maybe simpler is better\n \"\"\"\n wfs = waves[wfin]\n t0 = calcs['t0']\n energy = calcs['e_ftp']\n\n if test:\n\n iwf = 0\n while True:\n if iwf != 2:\n inp = input()\n if inp == \"q\": exit()\n\n\n\n xvals = np.arange(0,3000)\n start = time.time()\n\n plt.plot(xvals, wfs[iwf], lw=1)\n plt.vlines(t0[i], np.amin(wfs[i]), np.amax(wfs[i]), color='r', linewidth=1.5)\n plt.hlines(energy[i], 0, 3000, color='r', linewidth=1.5, zorder=10)\n plt.xlabel('Sample Number', ha='right', x=1.0)\n plt.ylabel('ADC Value', ha='right', y=1.0)\n plt.tight_layout()\n plt.show()\n\n iwf += 1\n\n print(\"hi clint\")\n\n\ndef gretina_overshoot(rc_us, pole_rel, freq=100E6):\n \"\"\"\n for use with scipy.signal.lfilter\n \"\"\"\n zmag = np.exp(-1. / freq / (rc_us * 1E-6))\n pmag = zmag - 10.**pole_rel\n num = [1, -zmag]\n den = [1, -pmag]\n return (num, den)\n\n\ndef fir():\n \"\"\"\n FIR Filter, fir the win ;-)\n https://docs.scipy.org/doc/scipy-1.2.1/reference/generated/scipy.signal.firwin.html\n\n This might be better than computing a whole bunch of notch filters.\n Just do a study on the MJ60 power spectrum, and create a multiband filter\n\n FIR FAQ\n https://dspguru.com/dsp/faqs/fir/basics/\n \"\"\"\n print(\"hi clint\")\n numtaps = 3\n f = 0.1\n signal.firwin(numtaps, f)\n\n\ndef cfit():\n \"\"\"\n a curve_fit (or optimize.minimize, or lmfit)\n apply_along_axis function might be good, for special cases\n when we don't care about using more computation time\n \"\"\"\n # # curve_fit, with exponential. (not easily vectorized)\n # from scipy.optimize import curve_fit\n # tmax = np.amax(wf_tail)\n # def gaus(t, a, tau):\n # return a * np.exp(-t/tau)\n # pars, pcov = curve_fit(gaus, ts_tail, wf_tail,\n # p0=(tmax,8000),\n # bounds=[[0.8*tmax, 5000],[1.2*tmax, 20000]])\n # perr = np.sqrt(np.diag(pcov))\n # dc, dc_err = pars[1] / 100, perr[1] / 100\n # plt.plot(ts_tail, gaus(ts_tail, *pars), '-m', lw=3,\n # label=\"curve_fit dc: {:.1f} +/- {:.3f}\".format(dc, dc_err))\n print(\"hi clint\")\n","sub_path":"attic/sandbox/old_dsp/calculators.py","file_name":"calculators.py","file_ext":"py","file_size_in_byte":26228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"541254123","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------\n# xoutil.params\n# ---------------------------------------------------------------------\n# Copyright (c) 2015 Merchise and Contributors\n# All rights reserved.\n#\n# Author: Medardo Rodriguez\n# Contributors: see CONTRIBUTORS and HISTORY file\n#\n# This is free software; you can redistribute it and/or modify it under the\n# terms of the LICENCE attached (see LICENCE file) in the distribution\n# package.\n#\n# Created 2015-07-13\n\n\nr'''Conformer for function parameter passing.\n\nIt's usual to declare functions with generic prototypes::\n\n def func(*args, **kwargs):\n ...\n\nActual parameters must be identified in a smart way. This module provide a\ntool to solve argument identification from a definition in a dictionary::\n\n {\n 'main-name': (checker, pos-definition, aliases, default-value),\n ...\n }\n\n\n- checker: A function that must validate a value; if valid return the same or\n a coerced value; if invalid must return the special value `Invalid`. If not\n given, identity function is used (check as valid all values, avoid this).\n\n- pos-definition: Define if the parameter could appear as a positional\n argument or not. Must be a set of positive integers defining priority\n orders, parameters with minor values must appear first. More than value\n means several alternatives.\n\n If not given, means that the parameter could not appear in positional\n arguments.\n\n- aliases: A set of strings (valid Python identifiers), alternatives that\n could be used as keyword names.\n\n- default: The default value to use if the argument is not given. The special\n value `Undefined` is used to specify that the parameter is required.\n\nThe value with each definition could miss several elements, each concept is\nidentified by its type, but ambiguities must be avoided; if default value is\nconfusing with some concept, must be the last one.\n\nFor example::\n\n scheme = {\n 'stream': (check_file_like, {0, 3}, {'output'}, sys.stdout),\n 'indent': (check_positive_int, {1}, 1),\n 'width': (check_positive_int, {2}, {'max_width'}, 79),\n 'newline': (check_str, '\\n'),\n }\n\n.. versionadded:: 1.7.0\n\n'''\n\n\n# TODO: Make a decorator to annotate function from a scheme. See\n# `xoutil.annotate`:mod: for more information.\n\nfrom __future__ import (division as _py3_division,\n print_function as _py3_print,\n unicode_literals as _py3_unicode,\n absolute_import)\n\n\nfrom xoutil.values import coercer\n\n\ndef _prepare_schema_coercer_global_cache():\n '''Prepare global cache for scheme coercer.'''\n from xoutil import Undefined\n from xoutil.eight import zip\n from xoutil.values import (coercer as checker_coerce,\n iterable,\n identity_coerce, identifier_coerce,\n positive_int_coerce)\n pos_coerce = iterable(positive_int_coerce, outer_coerce=set)\n alias_coerce = iterable(identifier_coerce, outer_coerce=set)\n default_coerce = identity_coerce\n checker_default = identity_coerce\n pos_default = set()\n alias_default = set()\n default_default = Undefined\n names = ('checker', 'pos', 'aliases', 'default')\n coercers = dict(zip(names, (checker_coerce, pos_coerce, alias_coerce,\n default_coerce)))\n defaults = dict(zip(names, (checker_default, pos_default, alias_default,\n default_default)))\n return (names, coercers, defaults)\n\n\n_SCHEME_COERCER_CACHE = _prepare_schema_coercer_global_cache()\n\n\n@coercer\ndef scheme_coerce(arg):\n '''Coerce a scheme definition into a precise formalized dictionary.'''\n from xoutil.values import valid, Invalid\n names, coercers, defaults = _SCHEME_COERCER_CACHE\n if arg is Invalid:\n res = arg\n elif isinstance(arg, dict):\n res = arg\n i = 0\n keys = tuple(res)\n while valid(res) and i < len(keys):\n concept = keys[i]\n if concept in coercers:\n coercer = coercers[concept]\n value = coercer(res[concept])\n if valid(value):\n res[concept] = value\n i += 1\n else:\n res = Invalid\n else:\n res = Invalid\n else:\n if not isinstance(arg, tuple):\n arg = (arg,)\n res = {}\n i = 0\n while valid(res) and i < len(arg):\n value = arg[i]\n j, found = 0, False\n while j < len(names) and not found:\n concept = names[j]\n if concept not in res:\n coercer = coercers[concept]\n v = coercer(value)\n if valid(v):\n found = True\n res[concept] = v\n j += 1\n if found:\n i += 1\n else:\n res = Invalid\n if valid(res):\n # Complete and check default value\n for concept in defaults:\n if concept not in res:\n res[concept] = defaults[concept]\n concept = 'default'\n default = res[concept]\n if default is not defaults[concept]:\n coercer = res['checker']\n value = coercer(default)\n if valid(value):\n res[concept] = value\n else:\n res = Invalid\n return res\n\n\ndel coercer\n\n\nclass ParamConformer(object):\n '''Standardize actual parameters using a scheme.'''\n __slots__ = ('scheme', 'positions', 'strict')\n\n def __init__(self, *schemes, **kwargs):\n '''Create the conformer.\n\n :param schemes: Each item must be a dictionary with a scheme portion.\n See the module documentation for more information.\n\n :param kwargs: Except by the below special keyword argument, represent\n additional scheme definition, each keyword argument will\n represent the schema of a parameter with the same name.\n\n :param __strict__: Special keyword argument; if True, only scheme\n definitions could be used as actual arguments.\n\n '''\n self.strict = kwargs.pop('__strict__', False)\n self._formalize_schemes(schemes, kwargs)\n self._normalize_positions()\n\n def _formalize_schemes(self, schemes, kwargs):\n '''Formalize scheme in a more precise internal dictionary.'''\n from itertools import chain\n from xoutil.values import identifier_coerce, check as ok\n self.scheme = {}\n for scheme in chain((kwargs,), reversed(schemes)):\n for par in scheme:\n par = ok(identifier_coerce, par)\n if par not in self.scheme:\n self.scheme[par] = ok(scheme_coerce, scheme[par])\n if self.scheme:\n self._check_duplicate_aliases()\n else:\n raise TypeError('Invalid empty scheme definition!')\n\n def _check_duplicate_aliases(self):\n '''Check if there are duplicate aliases and parameter names.'''\n from xoutil.eight import iteritems\n used = set(self.scheme)\n duplicated = set()\n for par, ps in iteritems(self.scheme):\n for alias in ps['aliases']:\n if alias in used:\n duplicated.add(alias)\n else:\n used.add(alias)\n if duplicated:\n msg = 'Duplicate identifiers detected: \"{}\"'\n raise TypeError(msg.format(', '.join(duplicated)))\n\n def _normalize_positions(self):\n '''Update the `positions` dictionaries.'''\n from xoutil.eight import range, iteritems\n aux = {}\n for par, ps in iteritems(self.scheme):\n for pos in ps['pos']:\n l = aux.setdefault(pos, [])\n l.append(par)\n res, pivot = {}, 0\n for pos in range(min(aux), max(aux) + 1):\n if pos in aux:\n res[pivot] = sorted(aux[pos])\n pivot += 1\n self.positions = res\n\n def __call__(self, args, kwargs):\n '''Consolidate in `kwargs` all actual parameters.\n\n :param args: The positional arguments received by the calling function.\n\n :param kwargs: The keyword arguments received by the calling function.\n\n '''\n from xoutil.eight import iteritems\n assert isinstance(args, tuple) and isinstance(kwargs, dict)\n\n def clean(name):\n '''If argument with name is not yet assigned.'''\n return name not in kwargs\n\n def settle(name, value):\n '''Settle a value if not yet assigned, raises an error if not.'''\n if clean(name):\n kwargs[str(name)] = value\n else:\n msg = 'Got multiple values for \"{}\" argument: \"{}\" and \"{}\"!'\n raise TypeError(msg.format(name, value, kwargs[name]))\n\n def solve_aliases():\n '''Solve keyword arguments that have aliases.'''\n from xoutil import Unset\n for par, ps in iteritems(self.scheme):\n for alias in ps['aliases']:\n value = kwargs.pop(alias, Unset)\n if value is not Unset:\n settle(par, value)\n\n def check_kwargs():\n '''Check all formal keyword arguments.'''\n from xoutil.values import valid\n for key, arg in iteritems(kwargs):\n if key in self.scheme:\n checker = self.scheme[key]['checker']\n value = checker(arg)\n if valid(value):\n kwargs[str(key)] = value\n else:\n msg = 'Invalid argument value \"{}\": \"{}\"!'\n raise ValueError(msg.format(key, arg))\n elif self.strict:\n msg = 'Invalid keyword argument \"{}\": \"{}\"!'\n raise ValueError(msg.format(key, arg))\n\n def solve_results():\n '''Assign default values for missing arguments.'''\n from xoutil.values import valid\n for par, ps in iteritems(self.scheme):\n if clean(par):\n default = ps['default']\n if valid(default):\n kwargs[str(par)] = default\n else:\n msg = 'Missing required argument \"{}\"!'\n raise TypeError(msg.format(par))\n\n def get_valid():\n '''Get the valid parameter name in current position pivot.\n\n Return a tuple (name, value) if valid.\n\n '''\n from xoutil.values import valid\n names = positions[pivot]\n i, count = 0, len(names)\n res = ()\n while not res and i < count:\n name = names[i]\n if clean(name):\n checker = self.scheme[name]['checker']\n value = checker(arg)\n if valid(value):\n res = (name, value)\n i += 1\n return res\n\n def get_duplicate():\n '''Get a possible all not settled valid parameter names.'''\n from xoutil.values import valid\n res = None\n pos = last_pivot\n while not res and pos < len(positions):\n names = positions[pos]\n i = 0\n while not res and i < len(names):\n name = names[i]\n if name not in settled:\n checker = self.scheme[name]['checker']\n value = checker(arg)\n if valid(value):\n res = name\n i += 1\n pos += 1\n return res\n\n solve_aliases()\n check_kwargs()\n # Solve positional arguments\n settled = set()\n positions = self.positions\n positionals = {p for p, ps in iteritems(self.scheme) if ps['pos']}\n max_args = len({name for name in positionals if clean(name)})\n i, count = 0, len(args)\n pivot = last_pivot = 0\n if count <= max_args:\n while i < count and pivot < len(positions):\n arg = args[i]\n res = get_valid()\n if res:\n name, value = res\n settle(name, value)\n settled.add(name)\n last_pivot = pivot\n i += 1\n else:\n pivot += 1\n if i == count:\n solve_results()\n else:\n from xoutil.eight import typeof\n dup = get_duplicate()\n extra = 'duplicate \"{}\" '.format(dup) if dup else ''\n msg = ('Invalid {}argument \"{}\" at position \"{}\" of type '\n '\"{}\".')\n tname = typeof(arg).__name__\n raise TypeError(msg.format(extra, arg, i, tname))\n else:\n msg = 'Expecting at most {} positional arguments ({} given)!'\n raise TypeError(msg.format(max_args, count))\n\n\nif __name__ == '__main__':\n print('Testing module \"xoutil.params\"')\n\n import sys\n from xoutil.eight import string_types\n from xoutil.values import file_coerce, positive_int_coerce\n\n sample_scheme = {\n 'stream': (file_coerce, {0, 3}, {'output'}, sys.stdout),\n 'indent': (positive_int_coerce, {1}, 1),\n 'width': (positive_int_coerce, {2}, {'max_width'}, 79),\n 'newline': (string_types, '\\n'), }\n\n def test(*args, **kwargs):\n print('-'*80)\n print(\">>>\", args, \"--\", kwargs)\n try:\n conformer(args, kwargs)\n print(\"...\", kwargs)\n except BaseException as error:\n print(\"???\", '{}:'.format(type(error).__name__), error)\n\n conformer = ParamConformer(sample_scheme)\n\n test(4, 80)\n test(2, '80')\n test(4)\n test(80, indent=4, extra=\"I'm OK!\")\n test(width=80)\n test(sys.stderr, 4, 80)\n test(4, sys.stderr, newline='\\n\\r')\n test(sys.stderr, 4, output=sys.stderr)\n test(sys.stderr, 4, 80, output=sys.stderr)\n test(4, -79)\n\n conformer = ParamConformer(sample_scheme, __strict__=True)\n\n test(80, indent=4, extra=\"I'm not OK!\")\n","sub_path":"xoutil/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":14429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"375065408","text":"#-*- coding:utf8 -*-\nimport datetime\n\nfrom django.db import models\nfrom django.utils.encoding import smart_unicode, force_unicode\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom shopback import paramconfig as pcfg\nfrom shopback.base.options import SimpleListFilter,FieldListFilter\nfrom shopback.items.models import Product\n\n\n\nclass ChargerFilter(SimpleListFilter):\n # Human-readable title which will be displayed in the\n title = u'接管状态'\n\n # Parameter for the filter that will be used in the URL query.\n parameter_name = 'charger'\n\n def lookups(self, request, model_admin):\n \"\"\"\n Returns a list of tuples. The first element in each\n tuple is the coded value for the option that will\n appear in the URL query. The second element is the\n human-readable name for the option that will appear\n in the right sidebar.\n \"\"\"\n return (('mycharge',u'我接管的'),\n ('uncharge',u'未接管的'),)\n \n\n def queryset(self, request, queryset):\n \"\"\"\n Returns the filtered queryset based on the value\n provided in the query string and retrievable via\n `self.value()`.\n \"\"\"\n status_name = self.value()\n myuser_name = request.user.username\n if not status_name:\n return queryset\n elif status_name == 'mycharge':\n return queryset.filter(models.Q(sale_charger=myuser_name)|models.Q(storage_charger=myuser_name))\n \n else:\n return queryset.exclude(sale_charger=myuser_name).exclude(storage_charger=myuser_name)\n \n \nclass DateScheduleFilter(FieldListFilter):\n def __init__(self, field, request, params, model, model_admin, field_path):\n self.field_generic = '%s__' % field_path\n self.date_params = dict([(k, v) for k, v in params.items()\n if k.startswith(self.field_generic)])\n\n now = timezone.now()\n # When time zone support is enabled, convert \"now\" to the user's time\n # zone so Django's definition of \"Today\" matches what the user expects.\n if now.tzinfo is not None:\n current_tz = timezone.get_current_timezone()\n now = now.astimezone(current_tz)\n if hasattr(current_tz, 'normalize'):\n # available for pytz time zones\n now = current_tz.normalize(now)\n\n if isinstance(field, models.DateTimeField):\n today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n else: # field is a models.DateField\n today = now.date()\n tomorrow = today + datetime.timedelta(days=1)\n \n self.lookup_kwarg_since = '%s__gte' % field_path\n self.lookup_kwarg_until = '%s__lt' % field_path\n self.links = (\n (_('All'), {}),\n (_(u'五天后'), {\n self.lookup_kwarg_since: str(today + datetime.timedelta(days=5)),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=6)),\n }),\n (_(u'四天后'), {\n self.lookup_kwarg_since: str(today + datetime.timedelta(days=4)),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=5)),\n }),\n (_(u'大后天'), {\n self.lookup_kwarg_since: str(today + datetime.timedelta(days=3)),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=4)),\n }),\n (_(u'后天'), {\n self.lookup_kwarg_since: str(today + datetime.timedelta(days=2)),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=3)),\n }),\n (_(u'明日'), {\n self.lookup_kwarg_since: str(tomorrow),\n self.lookup_kwarg_until: str(today + datetime.timedelta(days=2)),\n }),\n (_(u'今日'), {\n self.lookup_kwarg_since: str(today),\n self.lookup_kwarg_until: str(tomorrow),\n }),\n (_(u'昨天'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=1)),\n self.lookup_kwarg_until: str(today ),\n }),\n (_(u'前天'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=2)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=1)),\n }),\n (_(u'三天前'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=3)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=2)),\n }),\n (_(u'四天前'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=4)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=3)),\n }),\n (_(u'五天前'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=5)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=4)),\n }),\n (_(u'六天前'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=6)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=5)),\n }),\n (_(u'七天前'), {\n self.lookup_kwarg_since: str(today - datetime.timedelta(days=7)),\n self.lookup_kwarg_until: str(today - datetime.timedelta(days=6)),\n }),\n )\n super(DateScheduleFilter, self).__init__(\n field, request, params, model, model_admin, field_path)\n\n def expected_parameters(self):\n return [self.lookup_kwarg_since, self.lookup_kwarg_until]\n\n def choices(self, cl):\n for title, param_dict in self.links:\n yield {\n 'selected': self.date_params == param_dict,\n 'query_string': cl.get_query_string(\n param_dict, [self.field_generic]),\n 'display': title,\n }\n\nFieldListFilter.register(\n lambda f: isinstance(f, models.DateField), DateScheduleFilter)\n\n\nfrom flashsale.dinghuo.models_user import MyUser,MyGroup\n\n\nclass GroupNameFilter(SimpleListFilter):\n \"\"\"\"\"\"\n title = u'采购分组'\n parameter_name = 'groupname'\n\n def lookups(self, request, model_admin):\n group_list = []\n groups = MyGroup.objects.all()\n for group in groups:\n group_list.append((str(group.id), group.name))\n return tuple(group_list)\n\n def queryset(self, request, queryset):\n group_id = self.value()\n if not group_id:\n return queryset\n else:\n user_list = MyUser.objects.filter(group_id__in=group_id)\n my_users = [my_user.user.username for my_user in user_list]\n return queryset.filter(sale_charger__in=my_users)\n \n\nfrom shopback.categorys.models import ProductCategory\n \nclass CategoryFilter(SimpleListFilter):\n \"\"\" \"\"\"\n title = u'商品类别'\n parameter_name = 'category'\n\n def lookups(self, request, model_admin):\n \n cat_id = request.GET.get(self.parameter_name,'')\n cat_parent_id = None\n try:\n cat_parent_id = ProductCategory.objects.get(cid=cat_id).parent_cid\n except:\n pass\n \n cate_list = []\n cate_qs = ProductCategory.objects.filter(is_parent=True,status=ProductCategory.NORMAL)\n for cate in cate_qs:\n cate_list.append((str(cate.cid), str(cate)))\n if cat_id and int(cat_id) == cate.cid or (cat_parent_id and int(cat_parent_id) == cate.cid):\n sub_cates = ProductCategory.objects.filter(parent_cid=cate.cid, is_parent=False, \n status=ProductCategory.NORMAL)\n for sub_cate in sub_cates:\n cate_list.append((str(sub_cate.cid), str(sub_cate)))\n\n return tuple(cate_list)\n\n def queryset(self, request, queryset):\n \n cat_id = self.value()\n if not cat_id:\n return queryset\n else:\n categorys = ProductCategory.objects.filter(parent_cid=cat_id)\n cate_ids = [cate.cid for cate in categorys]\n if len(cate_ids) == 0:\n return queryset.filter(category=cat_id)\n else:\n cate_ids.append(int(cat_id))\n return queryset.filter(category__in=cate_ids)\n \n \n","sub_path":"shopmanager/shopback/items/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"232371520","text":"''' Exercise 1\n\tVariables, \n\tformatted output,\n\ttypes\n\tconversions\n'''\n\nname = \"Alice\" # string \nage = 34 # integer\nheight = 1.7 # float \nsingle = True # bool\n\nout = \"My name is %-20s. I am %-04d years old. I am %08.2f metres tall\" % (name, age, height)\nprint(out)\n\n\n\nname = \"Bob\" \nage = 7 \nheight = 0.8 \nsingle = True \n\nout = \"My name is %-20s. I am %-04d years old. I am %08.2f metres tall\" % (name, age, height)\nprint(out)\n\nprint(\"I am married: %r\" % (not single))\n\n\ndef toFloat(value):\n try:\n float(value)\n return float(value)\n except:\n return 0.0\n\n\nprint(\"My name is %f. I am %s years old. I am %d metres tall\" % (toFloat(name), str(age), int(height)))\n\n\n","sub_path":"python-intro-3/e013-variables-formatted-output.py","file_name":"e013-variables-formatted-output.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"52445141","text":"from .core import Stream, get_io_loop\nfrom .bus import log\nfrom .pipe import P\nfrom tornado import gen\n\n\n@Stream.register_api()\nclass run_future(Stream):\n \"\"\"获取上游进来的future的最终值并放入下游\n 注意上游流要限速,这个是并发执行,速度很快\n\n examples::\n\n @gen.coroutine\n def foo():\n yield gen.sleep(3)\n return range<<10>>sample>>first\n\n async def foo2():\n import asyncio\n await asyncio.sleep(3)\n return range<<10>>sample>>first\n\n s = Stream()\n s.rate_limit(1).run_future()>>log\n\n for i in range(3):\n foo()>>s\n foo2()>>s\n\n [2020-02-26 18:14:37.991321] INFO: deva.log: 1\n [2020-02-26 18:14:37.993260] INFO: deva.log: 7\n [2020-02-26 18:14:37.995112] INFO: deva.log: 5\n\n run = run_future()\n run>>log\n\n foo()>>run\n foo2()>>run\n \"\"\"\n\n def __init__(self, upstream=None, **kwargs):\n # from tornado import httpclient\n Stream.__init__(self, upstream=upstream, ensure_io_loop=True)\n\n def emit(self, x, **kwargs):\n self.update(x)\n return x\n\n def update(self, x, who=None):\n assert isinstance(x, gen.Awaitable)\n futs = gen.convert_yielded(x)\n self.loop.add_future(futs, lambda x: self._emit(x.result()))\n\n\n# @P\n# def attend(stream: Stream = log):\n \"\"\"安排future执行,并将结果入流\n server=from_http_request()\n server>>log\n server.start()\n\n\n '你好'>>post_to() | attend(log)\n\n[20:49:07] 你好 bus.py:31\n[20:49:08] HTTPResponse(_body=None,_error_is_response_code=False,buffe bus.py:31\n r=<_io.BytesIO object at 0x106930310>,code=200,effective_ur\n l='http://127.0.0.1:7777',error=None,headers=,reason='OK',request=\n ,requ\n est_time=0.04534506797790527,start_time=1606567747.946251,t\n ime_info={})\n\n \"\"\"\n # def _attend(x):\n # assert isinstance(x, gen.Awaitable)\n # futs = gen.convert_yielded(x)\n # get_io_loop().add_future(futs, lambda x: stream._emit(x.result()))\n\n # if isinstance(stream, Stream):\n # return _attend @ P\n # else:\n # futs, stream = stream, log\n # return _attend(futs)\n","sub_path":"deva/future.py","file_name":"future.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"89816871","text":"\"\"\"\n\n Command 'get_ether'\n\n\"\"\"\n\nfrom .command_base import CommandBase\nfrom .send_ether_command import SendEtherCommand\nfrom .send_token_command import SendTokenCommand\n\nDEFAULT_AMOUNT = 10\n\n\nclass SendCommand(CommandBase):\n\n def __init__(self, subparser):\n self._command_list = []\n super().__init__('send', subparser)\n\n def create_parser(self, subparser):\n\n parser = subparser.add_parser(\n self._name,\n description='Send ether or tokens from one account to another',\n help='Send some tokens or ether from one account to another'\n )\n\n parser_send = parser.add_subparsers(\n title='send command',\n description='send command',\n help='Send command',\n dest='send_command'\n )\n\n self._command_list = [\n SendEtherCommand(parser_send),\n SendTokenCommand(parser_send)\n ]\n\n def execute(self, args, output):\n for command_item in self._command_list:\n if command_item.is_command(args.send_command):\n command_item.execute(args, output)\n break\n","sub_path":"starfish/tool/send_command.py","file_name":"send_command.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"296574330","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 6 20:56:44 2018\n@author: kevzo\n\"\"\"\n\nimport re\n# import numpy as np\nfrom numpy import random\nfrom nltk.tokenize import wordpunct_tokenize\nfrom scraper import kafka\n\n\ndef genmarkov(tokens):\n # beginner simplification : eliminate all punctuation and capitalization\n # the LAST WORD might need some special handling which is ignored for now\n f = [i.lower() for i in tokens if re.search('\\\\w', i)]\n markov = {}\n i = 0\n j = len(f)\n # flat = ' '.join(f)\n # norm = {i: len(re.findall(i, flat)) for i in g}\n for i in range(j-1):\n a = f[i]\n b = f[i+1]\n if a not in markov:\n markov[a] = {b: 1}\n else:\n if b in markov[a]:\n markov[a][b] += 1\n else:\n markov[a][b] = 1\n # convert word occurence count to local probability distribution\n # R(count) = (0,inf) --> R(pdist) = (0,1)\n for w in markov:\n n = markov[w]\n m = sum([n[i] for i in n])\n p = {k: (v / m) for k, v in n.items()}\n markov[w] = p\n\n return markov\n\n\ndef test1():\n tokens = wordpunct_tokenize(kafka())\n markov = genmarkov(tokens)\n q = [random.choice(list(markov.keys()))]\n for i in range(50):\n w = markov[q[-1]]\n n = []\n p = []\n for k, v in w.items():\n n.append(k)\n p.append(v)\n q.append(random.choice(n, p=p))\n return q\n\n\nr = test1()\nprint(' '.join(r))\n","sub_path":"markov.py","file_name":"markov.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"280724121","text":"# Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers.\n\n# Notice\n\n# You may assume that each input would have exactly one solution.\n\n# For example, given array S = [-1 2 1 -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n\n\nclass Solution:\n \"\"\"\n @param numbers: Give an array numbers of n integer\n @param target : An integer\n @return : return the sum of the three integers, the sum closest target.\n \"\"\"\n def threeSumClosest(self, numbers, target):\n # write your code here\n #method 1\n numbers.sort()\n closest=None\n for i in range(len(numbers)):\n l=i+1\n r=len(numbers)-1\n while lcnt: data.pop()\n return\n\ndef get_key(key, data):\n for item in data[::-1]:\n if key in item: return item[key]\n return \"\"\n\ndef expand(data):\n nbuilds = []\n for item in data:\n nbuilds.append({})\n for k in item:\n if k=='.variables': continue\n v = item[k]\n while True:\n m = regex_var.match(v)\n if not m: break\n v = \"%s%s%s\" % (m.group(1), get_key(m.group(2), data), m.group(3))\n nbuilds[-1][k]=v\n return nbuilds\n\ndef get_docker_images(name, repository='cmssw'):\n images = []\n setup_file = join(dirname(dirname(abspath(__file__))), name, \"config.yaml\")\n if not exists(setup_file):\n print(\"Warnings: No such file %s\" % setup_file)\n return images\n setup = yaml.load(open(setup_file))\n data = [{}]\n data[-1]['repository'] = repository\n data[-1]['name'] = name\n data[-1]['contianer'] = join(repository, name)\n push_info(setup, data)\n for tag in setup['tags']:\n cnt = len(data)\n push_info(setup['tags'][tag], data)\n data[-1]['tag']=tag\n img_data = expand(data)\n pop_info(data, cnt)\n\n images.append({})\n images[-1]['DOCKER_REPOSITORY']=get_key('repository', img_data)\n images[-1]['DOCKER_NAME']=get_key('name', img_data)\n images[-1]['DOCKER_CONTAINER']=get_key('contianer', img_data)\n images[-1]['IMAGE_NAME']=get_key('contianer', img_data) + \":\"+get_key('tag', img_data)\n images[-1]['IMAGE_TAG']=get_key('tag', img_data)\n\n base_image = get_key('from', img_data)\n if not '/' in base_image: base_image=\"library/\"+base_image\n if not ':' in base_image: base_image=base_image+\":latest\"\n images[-1]['BASE_DOCKER_REPOSITORY']= base_image.split(\"/\")[0]\n images[-1]['BASE_DOCKER_NAME']=base_image.split(\":\")[0].split(\"/\")[1]\n images[-1]['BASE_DOCKER_CONTAINER']=base_image.split(\":\")[0]\n images[-1]['BASE_IMAGE_NAME']=base_image\n images[-1]['BASE_IMAGE_TAG']=base_image.split(\":\")[1]\n\n images[-1]['IMAGE_BUILD_ARGS']=get_key('args', img_data)\n images[-1]['IMAGE_PUSH']=get_key('push', img_data)\n images[-1]['DOCKER_FILE']=get_key('docker', img_data)\n images[-1]['TEST_SCRIPT']=get_key('script', img_data)\n images[-1]['TEST_NODE']=get_key('node', img_data)\n if \".variables\" in data[0]:\n for v in data[0][\".variables\"]:\n images[-1][v] = get_key(v, img_data)\n return images\n\nif __name__ == \"__main__\":\n for name in sys.argv[1:]:\n for img in get_docker_images(name):\n print (img)\n","sub_path":"bin/get_image_config.py","file_name":"get_image_config.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"225402939","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[17]:\n\n\nimport matplotlib.pyplot\nimport csv\nimport sys\nimport numpy as np\nimport math\nimport tkinter\n\n# In[18]:\n\n\n# Set up numpy so that it prints everything in an array\nnp.set_printoptions(threshold=sys.maxsize, precision=2)\n\n\n# In[19]:\n\n\n#open the files and load the data\nf = open('death.rats', newline='') # open file\nreader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)\nrats = []\nfor row in reader:\t\t\t\t# for each row in csv file\n rowlist = [] # make a new list\n for value in row:\t\t\t# for each value\t\n rowlist.append(value) # append value to the rowlist\n rats.append(rowlist) # append the rowlist to the environment\nf.close() # close file\n\nf = open('death.parishes', newline='') # open file\nreader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)\nparishes = []\nfor row in reader:\t\t\t\t# for each row in csv file\n rowlist = [] # make a new list\n for value in row:\t\t\t# for each value\t\n rowlist.append(value) # append value to the rowlist\n parishes.append(rowlist) # append the rowlist to the environment\nf.close() # close file\n\n\n# In[20]:\n\n\n# plot the rats\ndef ratplot():\n matplotlib.pyplot.imshow(rats)\n matplotlib.pyplot.show() \n \n# plot the parishes\ndef parishplot():\n matplotlib.pyplot.imshow(parishes)\n matplotlib.pyplot.show() \n\n\n# In[21]:\n\n\nparishplot()\n\n\n# In[22]:\n\n\nratplot()\n\n\n# In[23]:\n\n\n# Calculate average weekly deaths\nA = np.array(rats)\nB = np.array(parishes)\ndeath = (A * 0.8) * (1.3 * B)\n\n\n# In[24]:\n\n\n#Plot deaths\ndef deathplot():\n matplotlib.pyplot.imshow(death)\n matplotlib.pyplot.show() \n\n\n# In[25]:\n\n\n# Print deaths\ndeathplot()\n\n\n# In[26]:\n\n\n# Write deaths to a csv file\nf2 = open('deaths.csv', 'w', newline='') \nwriter = csv.writer(f2, delimiter=',')\nfor row in death:\n\twriter.writerow(row)\nf2.close()\n\n\n# In[27]:\n\n\n# Calculating the totals for the area\n\n\n# In[28]:\n\n\npop = np.sum(parishes)\nprint(f'population is {pop}')\n\nrat = np.sum(rats)\nprint(f'rats killed each week is {rat}')\n\ntot_death = np.sum(death)/16\nprint(f'Weekly average death is {tot_death}')\n\n\n# In[29]:\n\n\nmatplotlib.use('TkAgg') \n# set up the plot\nfig = matplotlib.pyplot.figure(figsize=(2, 2))\nax = fig.add_axes([0, 0, 4, 4])\n\n\n# In[30]:\n\n\n#A window that lets the user adjust the parameters for the equation\nroot = tkinter.Tk()\n\nroot.wm_title(\"Black Death model\")\n\nmenu_bar = tkinter.Menu(root)\nroot.config(menu=menu_bar)\nmenu_bar.add_command(label=\"Quit\", command=root.destroy)\n\nnewRat = Scale(root, orient=HORIZONTAL, label=\"parameter for average weekly rats caught\", from_=0, to=1, resolution=0.01, length=250)\nnewRat.pack(anchor=CENTER)\n\nnewPar = Scale(root, orient=HORIZONTAL, label=\"parameter for average population per 100m2\", from_=0, to=1, resolution=0.01, length=250)\nnewPar.pack(anchor=CENTER)\n\nbutton = Button(root, text=\"go\", command = inputdeath)\nbutton.pack(anchor=CENTER)\n\nv = StringVar()\nlabel = Label(root, textvariable=v)\nlabel.pack()\n\ntkinter.mainloop()\n\n\n# In[104]:\n\n\ndef inputdeath():\n # Calculate new weekly deaths, and print result in the window\n r = newRat.get()\n p = newPar.get()\n newdeath = ((A * r) * (B * p))\n \n tot_newdeath = np.sum(newdeath)/16\n v.set(f'New weekly death number is {tot_newdeath}')\n \n\n","sub_path":"blackDeath-Copy1.py","file_name":"blackDeath-Copy1.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"432589968","text":"from flask import (Flask, request, jsonify,\n\t\t\t\t\trender_template, g, redirect,\n\t\t\t\t\tabort)\nfrom webargs import fields, validate\nfrom webargs.flaskparser import use_args, parser\n\nimport sqlite3\n\nfrom backend import *\n\n\nAPP_CONFIG = {\n\t\"ENV\": \"development\",\n\t\"DEBUG\": True,\n\t\"JSON_SORT_KEYS\": False,\n\t\"DATABASE\": 'data/genomes.db'\n}\n\n# Create the application instance\napplication = Flask(__name__, template_folder=\"templates\")\napplication.config.update(APP_CONFIG)\n\n# Manage database connection\ndef connect_db():\n\tconnection = sqlite3.connect('data/geonames.db')\n\treturn connection\n\nconnection = connect_db()\n\ndef get_db():\n\tif not hasattr(g, 'db'):\n\t\tg.db = connect_db()\n\treturn g.db\n\n@application.teardown_appcontext\ndef teardown_db(error):\n\tif hasattr(g, 'db'):\n\t\tg.db.close()\n\n\n# Create a URL route in our application for \"/\"\n@application.route('/')\ndef home():\n\t\"\"\"\n\tThis function just responds to the browser URL\n\tlocalhost:5000/\n\n\t:return:\t\tthe rendered template 'home.html'\n\t\"\"\"\n\treturn render_template('home.html')\n\nsuggestions_args = {\n\t'q': fields.Str(required=True),\n\t'latitude': fields.Float(required=False),\n\t'longitude': fields.Float(required=False)\n}\n\n# REST endpoint page\n@application.route('/suggestions', methods=['GET'])\n@use_args(suggestions_args)\ndef suggestions_endpoint(args):\n\t\"\"\"\n\n\t:return: \t\tthe JSON string with the suggestion\n\t\"\"\"\n\tconn = get_db()\n\n\tq = args['q']\n\tlatitude = None\n\tlongitude = None\n\tif 'latitude' in args:\n\t\tlatitude = args['latitude']\n\tif 'longitude' in args:\n\t\tlongitude = args['longitude']\n\n\tresult = get_autocomplete(conn, q, latitude, longitude)\n\n\treturn jsonify(result)\t\t\n\n# Run the app\nif __name__ == '__main__':\n\tapplication.run(host='0.0.0.0', port=80)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"504536847","text":"from telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram import ParseMode\nimport matplotlib.pyplot as plt\nfrom googletrans import Translator\nimport pyowm\nimport requests\nimport os\nimport sqlite3\n\n\ndef save(name='', fmt='png'):\n pwd = os.getcwd()\n iPath = '{}'.format(fmt)\n if not os.path.exists(iPath):\n os.mkdir(iPath)\n os.chdir(iPath)\n plt.savefig('{}.{}'.format(name, fmt), fmt='png')\n os.chdir(pwd)\n\n\ndef print_pic(self, bot, translator, place, update):\n try:\n path = ''\n place = translator.translate(place, dest='en').text\n reg = self.owm.city_id_registry()\n loc = str(reg.ids_for(place)[0][0])\n mas1, mas2 = [], []\n res = requests.get('http://api.openweathermap.org/data/2.5/forecast?id=' +\n loc + '&appid=a69b90b4f9e76a35a3a0b224344ec614&units=metric&lang=ru')\n for i in res.json()['list'][::4]:\n x = i['dt_txt']\n res = x[8:10] + \" числа\"\n mas1.append(res)\n mas2.append(int(i['main']['temp']))\n fig, ax = plt.subplots()\n plt.bar(mas1, mas2)\n plt.title('График погоды на 5 дней')\n ax.set_ylabel('Температура (℃)')\n plt.grid(True)\n save(name='pic', fmt='png')\n k = os.getcwd()\n for source_direct, sub_direct, files in os.walk(k):\n for f in files:\n path = os.path.join(source_direct, f)\n\n bot.send_photo(chat_id=update.message.chat_id,\n photo=open(path, 'rb'))\n\n except pyowm.exceptions.not_found_error.NotFoundError:\n place = translator.translate(place, dest='ru').text\n text = place + \" не найден. Введите корректный запрос, например:\"\n text += \"\\n/weather Moscow\"\n bot.send_message(chat_id=update.message.chat_id, text=text)\n\n\ndef form_msg(place, status, status_rus, wind, humi, temp):\n msg = \"Погода в \" + place.capitalize()\n if status == \"Clouds\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" ☁️\"\n elif status == \"Sun\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" ☀️\"\n elif status == \"Rain\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" 🌧\"\n elif status == \"Snow\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" ☃️\"\n elif status == \"Clear\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" ☀️\"\n elif status == \"Storm\":\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" ⛈\"\n else:\n msg += \"\\nСтатус: \" + status_rus.capitalize() + \" 🌤\"\n msg += \"\\n\\n🌪 Ветер: \" + str(wind['speed']) + \" км/ч\"\n msg += \"\\n💨 Влажность: \" + str(humi) + \"%\"\n msg += \"\\n\\n🌡Температура: \" + str(temp['temp']) + \" ℃\"\n msg += \"\\n\\t📉 Мин: \" + str(temp['temp_min']) + \" ℃\"\n msg += \"\\n\\t📈 Макс: \" + str(temp['temp_max']) + \" ℃\"\n return msg\n\n\ndef print_weather(self, bot, update, translator, place):\n try:\n yes = False\n status_rus = loc = ''\n place = translator.translate(place, dest='en').text\n reg = self.owm.city_id_registry()\n for i in range(len(reg.ids_for(place))):\n if reg.ids_for(place)[i][2] == 'RU':\n loc = str(reg.ids_for(place)[i][0])\n yes = True\n if not yes:\n loc = str(reg.ids_for(place)[0][0])\n w = self.owm.weather_at_place(place).get_weather()\n status = w.get_status()\n wind = w.get_wind()\n humi = w.get_humidity()\n temp = w.get_temperature('celsius')\n res = requests.get(\n 'http://api.openweathermap.org/data/2.5/weather?id=' + loc + '&appid=a69b90b4f9e76a35a3a0b224344ec614&units=metric&lang=ru')\n for i in res.json()['weather']:\n status_rus = i['description']\n place = translator.translate(place, dest='ru').text\n\n msg = form_msg(place, status, status_rus, wind, humi, temp)\n\n database(res.json()['id'], res.json()['name'], res.json()['cod'],\n float(temp['temp']), status_rus.capitalize())\n\n bot.send_message(chat_id=update.message.chat_id, text=msg)\n\n except pyowm.exceptions.not_found_error.NotFoundError:\n place = translator.translate(place, dest='ru').text\n text = place.capitalize() + \" не найден. Введите корректный запрос, например:\"\n text += \"\\n/weather Moscow\"\n bot.send_message(chat_id=update.message.chat_id, text=text)\n\n return res\n\n\ndef database(id, city, code_city, temp, desc):\n conn = sqlite3.connect('info.db')\n cur = conn.cursor()\n s = \"INSERT INTO weather (id, city, code_city, temp, desc) VALUES (\" + str(id) + \", '\" + str(city) + \"', \" + str(code_city) + \", \" + str(int(temp)) + \", '\" + desc + \"')\"\n cur.execute(s)\n conn.commit()\n conn.close()\n\n\nclass WeatherBot(object):\n def __init__(self, tg_token, weather_token):\n self._tg_token = tg_token\n self._weather_token = weather_token\n self.owm = pyowm.OWM(self._weather_token, language='ru')\n self.updater = Updater(token=self._tg_token)\n self.dispatcher = self.updater.dispatcher\n self.dispatcher.add_handler(\n CommandHandler('start', self.start_handler))\n self.dispatcher.add_handler(CommandHandler('help', self.help_handler))\n self.dispatcher.add_handler(CommandHandler(\n 'weather', self.weather_handler, pass_args=True))\n\n def start_polling(self):\n self.updater.start_polling()\n\n def start_handler(self, bot, update):\n bot.send_message(chat_id=update.message.chat_id,\n text=\"Привет) Нажмите /help для показа инструкций\")\n\n def help_handler(self, bot, update):\n msg = \"*Команды*\"\n msg += \"\\n/help для просмотра инструкций\"\n msg += \"\\n/weather показывает погоду\"\n bot.send_message(chat_id=update.message.chat_id,\n text=msg, parse_mode=ParseMode.MARKDOWN)\n\n\n def weather_handler(self, bot, update, args):\n if len(args) > 0:\n place = ' '.join(args)\n translator = Translator()\n\n print_weather(self, bot, update, translator, place)\n print_pic(self, bot, translator, place, update)\n\n else:\n text = \"Вы должны ввести место, где нужно посмотреть прогноз погоды. Например:\"\n text += \"\\n/weather Moscow\"\n bot.send_message(chat_id=update.message.chat_id, text=text)\n\n\ndef main():\n telegram_token = '574145205:AAGKB9TJwThrOf1YWLBebB1fVspD6M3xCps'\n weather_token = 'a69b90b4f9e76a35a3a0b224344ec614'\n weatherBot = WeatherBot(telegram_token, weather_token)\n weatherBot.start_polling()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"298517008","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/svpino/dev/tensorflow-object-detection-sagemaker/todl/tensorflow-object-detection/official/r1/resnet/cifar10_main.py\n# Compiled at: 2020-04-05 19:50:57\n# Size of source mod 2**32: 10503 bytes\n\"\"\"Runs a ResNet model on the CIFAR-10 dataset.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nfrom absl import app as absl_app\nfrom absl import flags\nfrom absl import logging\nfrom six.moves import range\nimport tensorflow as tf\nfrom official.r1.resnet import resnet_model\nfrom official.r1.resnet import resnet_run_loop\nimport official.utils.flags as flags_core\nfrom official.utils.logs import logger\nHEIGHT = 32\nWIDTH = 32\nNUM_CHANNELS = 3\n_DEFAULT_IMAGE_BYTES = HEIGHT * WIDTH * NUM_CHANNELS\n_RECORD_BYTES = _DEFAULT_IMAGE_BYTES + 1\nNUM_CLASSES = 10\n_NUM_DATA_FILES = 5\nNUM_IMAGES = {'train':50000, \n 'validation':10000}\nDATASET_NAME = 'CIFAR-10'\n\ndef get_filenames(is_training, data_dir):\n \"\"\"Returns a list of filenames.\"\"\"\n assert tf.io.gfile.exists(data_dir), 'Run cifar10_download_and_extract.py first to download and extract the CIFAR-10 data.'\n if is_training:\n return [os.path.join(data_dir, 'data_batch_%d.bin' % i) for i in range(1, _NUM_DATA_FILES + 1)]\n return [\n os.path.join(data_dir, 'test_batch.bin')]\n\n\ndef parse_record(raw_record, is_training, dtype):\n \"\"\"Parse CIFAR-10 image and label from a raw record.\"\"\"\n record_vector = tf.io.decode_raw(raw_record, tf.uint8)\n label = tf.cast(record_vector[0], tf.int32)\n depth_major = tf.reshape(record_vector[1:_RECORD_BYTES], [\n NUM_CHANNELS, HEIGHT, WIDTH])\n image = tf.cast(tf.transpose(a=depth_major, perm=[1, 2, 0]), tf.float32)\n image = preprocess_image(image, is_training)\n image = tf.cast(image, dtype)\n return (\n image, label)\n\n\ndef preprocess_image(image, is_training):\n \"\"\"Preprocess a single image of layout [height, width, depth].\"\"\"\n if is_training:\n image = tf.image.resize_with_crop_or_pad(image, HEIGHT + 8, WIDTH + 8)\n image = tf.image.random_crop(image, [HEIGHT, WIDTH, NUM_CHANNELS])\n image = tf.image.random_flip_left_right(image)\n image = tf.image.per_image_standardization(image)\n return image\n\n\ndef input_fn(is_training, data_dir, batch_size, num_epochs=1, dtype=tf.float32, datasets_num_private_threads=None, parse_record_fn=parse_record, input_context=None, drop_remainder=False):\n \"\"\"Input function which provides batches for train or eval.\n\n Args:\n is_training: A boolean denoting whether the input is for training.\n data_dir: The directory containing the input data.\n batch_size: The number of samples per batch.\n num_epochs: The number of epochs to repeat the dataset.\n dtype: Data type to use for images/features\n datasets_num_private_threads: Number of private threads for tf.data.\n parse_record_fn: Function to use for parsing the records.\n input_context: A `tf.distribute.InputContext` object passed in by\n `tf.distribute.Strategy`.\n drop_remainder: A boolean indicates whether to drop the remainder of the\n batches. If True, the batch dimension will be static.\n\n Returns:\n A dataset that can be used for iteration.\n \"\"\"\n filenames = get_filenames(is_training, data_dir)\n dataset = tf.data.FixedLengthRecordDataset(filenames, _RECORD_BYTES)\n if input_context:\n logging.info('Sharding the dataset: input_pipeline_id=%d num_input_pipelines=%d', input_context.input_pipeline_id, input_context.num_input_pipelines)\n dataset = dataset.shard(input_context.num_input_pipelines, input_context.input_pipeline_id)\n return resnet_run_loop.process_record_dataset(dataset=dataset,\n is_training=is_training,\n batch_size=batch_size,\n shuffle_buffer=(NUM_IMAGES['train']),\n parse_record_fn=parse_record_fn,\n num_epochs=num_epochs,\n dtype=dtype,\n datasets_num_private_threads=datasets_num_private_threads,\n drop_remainder=drop_remainder)\n\n\ndef get_synth_input_fn(dtype):\n return resnet_run_loop.get_synth_input_fn(HEIGHT,\n WIDTH, NUM_CHANNELS, NUM_CLASSES, dtype=dtype)\n\n\nclass Cifar10Model(resnet_model.Model):\n __doc__ = 'Model class with appropriate defaults for CIFAR-10 data.'\n\n def __init__(self, resnet_size, data_format=None, num_classes=NUM_CLASSES, resnet_version=resnet_model.DEFAULT_VERSION, dtype=resnet_model.DEFAULT_DTYPE):\n \"\"\"These are the parameters that work for CIFAR-10 data.\n\n Args:\n resnet_size: The number of convolutional layers needed in the model.\n data_format: Either 'channels_first' or 'channels_last', specifying which\n data format to use when setting up the model.\n num_classes: The number of output classes needed from the model. This\n enables users to extend the same model to their own datasets.\n resnet_version: Integer representing which version of the ResNet network\n to use. See README for details. Valid values: [1, 2]\n dtype: The TensorFlow dtype to use for calculations.\n\n Raises:\n ValueError: if invalid resnet_size is chosen\n \"\"\"\n if resnet_size % 6 != 2:\n raise ValueError('resnet_size must be 6n + 2:', resnet_size)\n num_blocks = (resnet_size - 2) // 6\n super(Cifar10Model, self).__init__(resnet_size=resnet_size,\n bottleneck=False,\n num_classes=num_classes,\n num_filters=16,\n kernel_size=3,\n conv_stride=1,\n first_pool_size=None,\n first_pool_stride=None,\n block_sizes=([\n num_blocks] * 3),\n block_strides=[\n 1, 2, 2],\n resnet_version=resnet_version,\n data_format=data_format,\n dtype=dtype)\n\n\ndef cifar10_model_fn(features, labels, mode, params):\n \"\"\"Model function for CIFAR-10.\"\"\"\n features = tf.reshape(features, [-1, HEIGHT, WIDTH, NUM_CHANNELS])\n learning_rate_fn = resnet_run_loop.learning_rate_with_decay(batch_size=(params['batch_size'] * params.get('num_workers', 1)),\n batch_denom=128,\n num_images=(NUM_IMAGES['train']),\n boundary_epochs=[\n 91, 136, 182],\n decay_rates=[1, 0.1, 0.01, 0.001])\n weight_decay = 0.0002\n\n def loss_filter_fn(_):\n return True\n\n return resnet_run_loop.resnet_model_fn(features=features,\n labels=labels,\n mode=mode,\n model_class=Cifar10Model,\n resnet_size=(params['resnet_size']),\n weight_decay=weight_decay,\n learning_rate_fn=learning_rate_fn,\n momentum=0.9,\n data_format=(params['data_format']),\n resnet_version=(params['resnet_version']),\n loss_scale=(params['loss_scale']),\n loss_filter_fn=loss_filter_fn,\n dtype=(params['dtype']),\n fine_tune=(params['fine_tune']))\n\n\ndef define_cifar_flags():\n resnet_run_loop.define_resnet_flags()\n flags.adopt_module_key_flags(resnet_run_loop)\n flags_core.set_defaults(data_dir='/tmp/cifar10_data/cifar-10-batches-bin', model_dir='/tmp/cifar10_model',\n resnet_size='56',\n train_epochs=182,\n epochs_between_evals=10,\n batch_size=128,\n image_bytes_as_serving_input=False)\n\n\ndef run_cifar(flags_obj):\n \"\"\"Run ResNet CIFAR-10 training and eval loop.\n\n Args:\n flags_obj: An object containing parsed flag values.\n\n Returns:\n Dictionary of results. Including final accuracy.\n \"\"\"\n if flags_obj.image_bytes_as_serving_input:\n logging.fatal('--image_bytes_as_serving_input cannot be set to True for CIFAR. This flag is only applicable to ImageNet.')\n return\n input_function = flags_obj.use_synthetic_data and get_synth_input_fn(flags_core.get_tf_dtype(flags_obj)) or input_fn\n result = resnet_run_loop.resnet_main(flags_obj,\n cifar10_model_fn, input_function, DATASET_NAME, shape=[\n HEIGHT, WIDTH, NUM_CHANNELS])\n return result\n\n\ndef main(_):\n with logger.benchmark_context(flags.FLAGS):\n run_cifar(flags.FLAGS)\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n define_cifar_flags()\n absl_app.run(main)","sub_path":"pycfiles/todl-0.1.1.tar/cifar10_main.cpython-37.py","file_name":"cifar10_main.cpython-37.py","file_ext":"py","file_size_in_byte":8189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"135498547","text":"from itertools import chain\nfrom math import ceil\nfrom operator import attrgetter, itemgetter\n\nfrom sqlalchemy import and_, or_\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.sql.functions import func, coalesce\n\nfrom alchemist.helpers.main_search import get_strict_query\nfrom alchemist.models import Connection\nfrom alchemist.models.base import DBSession\nfrom alchemist.models.company import BaseCompany\nfrom alchemist.models.tag import Tag\nfrom alchemist.models.user_company import UserXCompany\nfrom alchemist.system.route import route\n\nPAGE_SIZE = 3\n\n\n@route(path='/companies', permission='company_list', renderer='templates/grid.jinja2')\n@route(path='/startups', permission='company_list', renderer='templates/grid.jinja2')\n@route(path='/enterprise', permission='company_list', renderer='templates/grid.jinja2')\n@route(path='/funds', permission='company_list', renderer='templates/grid.jinja2')\n@route(path='/alchemist_startups', permission='company_list', renderer='templates/grid.jinja2')\ndef grid_view(request):\n query = DBSession.query(BaseCompany).options(joinedload(BaseCompany.tags)).options(\n joinedload(BaseCompany.users_rel).joinedload(UserXCompany.user))\n total = DBSession.query(func.count(BaseCompany.id))\n query = query.filter(*get_filters(request))\n total = total.filter(*get_filters(request)).scalar()\n results = add_pagination(request, query).all()\n results = add_connection_info(results, request.user)\n request.session['query'] = request.params.get('query', '')\n # If the user is not coming from similar path then set select_all checkbox parameter to False\n if request.referer and request.path_info not in request.referer:\n request.session['select_all_comp'] = False\n return {'items': results,\n 'select_all': request.session.get('select_all_comp'),\n 'repost': request.params,\n 'page': int(request.params.get('p', 1)),\n 'page_size': PAGE_SIZE,\n 'total': total,\n 'num_pages': int(ceil(float(total) / PAGE_SIZE))\n }\n\n\ndef add_connection_info(results, by_user):\n if by_user.primary_type == 'customer':\n return results\n empl_ids = map(attrgetter('id'), chain.from_iterable(map(attrgetter('all_users'), results)))\n if empl_ids:\n last_conns = DBSession.query(Connection.user_id, Connection.accepted,\n Connection.accept_at, Connection.sent_at). \\\n filter(Connection.by_user == by_user, Connection.user_id.in_(empl_ids)) \\\n .order_by(coalesce(Connection.accept_at, Connection.sent_at)).all()\n conn_data_by_user_id = dict(zip(map(itemgetter(0), last_conns), last_conns))\n for comp in results:\n for employee in comp.all_users:\n setattr(employee, 'connection', conn_data_by_user_id.get(employee.id))\n return results\n\n\ndef get_company_typestr(input_str):\n company_types = {'enterprises': 'enterprise',\n 'startups': 'startup',\n 'alchemist_startups': 'startup',\n 'funds': 'fund'}\n return company_types.get(input_str, input_str)\n\n\ndef where_from_query(request):\n where = []\n if hasattr(request, 'params'):\n rp = request.params\n query = rp.get('query', '').strip().lower()\n elif request.get('sessquery'):\n rp = request\n query = request.get('sessquery').strip().lower()\n else:\n query = ''\n if not query:\n return where\n strict_queries = get_strict_query(query)\n for type_name, type_queries in strict_queries.iteritems():\n same_type = []\n for query in type_queries:\n if type_name == 'tags':\n same_type.append(BaseCompany.tags.any(func.lower(Tag.text) == query))\n elif type_name == 'type':\n same_type.append(BaseCompany.companytype == get_company_typestr(query))\n elif type_name == 'class':\n same_type.append(BaseCompany.alchemistclass == int(query.strip()))\n elif type_name == 'round':\n same_type.append(BaseCompany.startup_lastraise == query)\n elif type_name == 'query':\n different_type = []\n for search_field in BaseCompany.search_fields:\n if 'class' in search_field:\n if 'class' in query:\n query = query.replace('alchemistclass', '').replace('class', '').strip().split(' ')[0]\n try:\n different_type.append(BaseCompany.alchemistclass == int(query))\n except:\n pass\n else:\n different_type.append(getattr(BaseCompany, search_field).ilike('%' + query + '%'))\n different_type.append(BaseCompany.tags.any(Tag.text.ilike('%' + query + '%')))\n for bool_field in BaseCompany.boolean_fields:\n if rp.get(bool_field) or bool_field.split('_')[-1] in (query or ''):\n different_type.append(getattr(BaseCompany, bool_field) == True)\n same_type.append(or_(*different_type))\n where.append(and_(*same_type))\n return where\n\n\ndef get_filters(request):\n filters = []\n if not request.user.is_admin:\n filters.append(BaseCompany.activated == True)\n type_from_mdict = request.path[1:]\n if 'companies' not in request.path and type_from_mdict:\n company_typestr = get_company_typestr(type_from_mdict)\n filters.append(BaseCompany.companytype == company_typestr)\n if 'alchemist' in request.path[1:]:\n filters.append(BaseCompany.is_alchemist == True)\n where = where_from_query(request)\n filters.append(and_(*where))\n return filters\n\n\ndef add_pagination(request, query):\n query = query.order_by(BaseCompany.id.desc()).limit(PAGE_SIZE).offset(\n (int(request.params.get('p', 1)) - 1) * PAGE_SIZE)\n return query\n","sub_path":"alchemist/companies/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"94449486","text":"from blessed import Terminal\n\nterm = Terminal()\n\n\nclass Panel:\n \"\"\"Creates customized Rectangles\"\"\"\n\n def __init__(\n self,\n string: str,\n size: tuple = None,\n padding: int = 1,\n offset: tuple = None,\n color: str = '',\n align: str = 'center',\n valign: str = 'center'\n ):\n ox, oy = offset or term.get_location()\n width, height = size or (None, None)\n color = getattr(term, color, None)\n align = getattr(term, align, term.ljust)\n\n mx_width = width - padding * 2 if width else self._find_default_width(string)\n\n row_format = f'{ term.move_x( ox ) }{ \" \" * padding }{ {} }{ \" \" * padding }{ term.move_down }'\n empty_row = row_format.format(' ' * mx_width)\n\n rows = string.strip()\n rows = term.wrap(rows, width=mx_width)\n\n rows = [row_format.format(align(row, mx_width)[:mx_width]) for row in rows]\n\n mx_height = height - padding * 2 if height else len(rows)\n\n extra_top_pad = extra_bottom_pad = 0\n if mx_height > len(rows):\n diff = mx_height - len(rows)\n extra_top_pad, extra_bottom_pad = self._find_extra_pad(diff, valign)\n\n total_top_pad, total_bottom_pad = padding + extra_top_pad, padding + extra_bottom_pad\n rows = [empty_row] * total_top_pad + rows[:mx_height] + [empty_row] * total_bottom_pad\n\n self._string = term.move_y(oy) + (''.join(rows))\n\n if color:\n self._string = color(self._string)\n\n def __str__(self):\n return self._string\n\n def __repr__(self):\n return repr(self._string)\n\n def __add__(self, string: str):\n return self._string + str(string)\n\n def _find_default_width(self, string: str) -> int:\n return max(map(len, string.split('\\n')))\n\n def _find_extra_pad(self, diff: int, valign: str) -> tuple:\n\n if valign == 'top':\n return 0, diff\n elif valign == 'bottom':\n return diff, 0\n else:\n return diff // 2 + diff % 2, diff // 2\n\n\nif __name__ == '__main__':\n print(\n term.home+term.clear,\n Panel('', size=(4, 4), offset=(100, 25), color='on_green'),\n Panel('', size=(2, 2), offset=(101, 26), color='on_blue')\n )\n","sub_path":"samples/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"626697198","text":"import json\nimport subprocess\nimport os\nimport boto3\n\n\ndef lambda_handler(event, context):\n filename = event['filename']\n\n s3 = boto3.resource('s3')\n s3.Bucket('masteraula-documents').download_file('html/{}.html'.format(filename), '/tmp/{}.html'.format(filename))\n \n subprocess.getoutput('/opt/pandoc --reference-doc reference.docx -o /tmp/{}.docx /tmp/{}.html'.format(filename, filename))\n \n s3.Bucket('masteraula-documents').upload_file('/tmp/{}.docx'.format(filename), 'docx/{}.docx'.format(filename))\n stdoutdata = subprocess.getoutput('/opt/pandoc -v')\n \n return {\n 'statusCode': 200,\n 'body': filename\n }\n\n","sub_path":"lambda_document/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"293032194","text":"#!/usr/bin/python\n# coding=utf-8\n\nimport os \nimport platform\nimport sys\nfrom types import BooleanType, FloatType, IntType, ListType, StringType\n\nfrom guidata.dataset import datatypes, dataitems\nfrom guidata.qthelpers import get_icon\nfrom guidata.qt.QtGui import (QAction, QActionGroup, QColor, QMainWindow, QMenu, \n QMessageBox, QTextCursor, QTreeWidgetItem)\nfrom guidata.qt.QtCore import (QPoint, QSettings, QSize, QStringList, QVariant, \n Slot)\nfrom guidata.qt.QtCore import PYQT_VERSION, QT_VERSION\n\nfrom zupport.resources.ui_toolloader import Ui_MainWindow\nfrom zupport.core import (ExtentContainer, Manager, Parameter)\nfrom zupport.utilities import (APP_RESOURCES, USER_DATA_DIR, __version__)\nfrom zupport.zlogging import Logger\n\n\"\"\"\nZupport specific GUI operations.\n\nThis module provides wrappers and parsers for :mod:guidata module. Main purpose\nis to provide an easy way to provide a GUI for :mod:Zupport plugins by \ndynamically constructing the GUI from Parameters object.\n\"\"\"\n\n#------------------------------------------------------------------------------ \n# Main graphical components\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n '''Mainwindow for initial loading of different plugins.\n '''\n \n def __init__(self):\n QMainWindow.__init__(self)\n self.setWindowIcon(get_icon(os.path.join(APP_RESOURCES, 'icons',\n 'python.png')))\n self.setupUi(self)\n \n # Redirect output to GUI's QTextEdit\n sys.stdout = OutLog(self.outputTextEdit, sys.stdout)\n sys.stderr = OutLog(self.outputTextEdit, sys.stderr, QColor(255,0,0) )\n \n settings = QSettings()\n size = settings.value(\"MainWindow/Size\",\n QVariant(QSize(600, 500))).toSize()\n self.resize(size)\n position = settings.value(\"MainWindow/Position\",\n QVariant(QPoint(0, 0))).toPoint()\n self.move(position)\n self.restoreState(\n settings.value(\"MainWindow/State\").toByteArray())\n \n self.logger = Logger('Zupport.GUIloader')\n self.logger.debugging = settings.value(\"Logging/debugging\").toBool()\n \n # Set up a ZupportManager to deal with the plugins\n self.manager = Manager(self)\n self.plugins = {}\n\n # Set up the extents menu\n self.extent = ExtentContainer()\n self.menuExtent = QMenu(\"Extent\")\n resolutions = self.extent.resolutions\n self.extenactiongroup = QActionGroup(self.menuExtent) \n noneaction = QAction(\"None\", self.menuExtent)\n self.extenactiongroup.addAction(noneaction)\n self.menuExtent.addAction(noneaction)\n for resolution in resolutions:\n resolution_text = str(resolution)\n submenu = self.menuExtent.addMenu(resolution_text) \n self.menuExtent.addMenu(submenu)\n for area in self.extent.get_names(resolution):\n subaction = QAction(str(area) + \": %s\" % resolution_text, \n submenu)\n subaction.setCheckable(True)\n self.extenactiongroup.addAction(subaction)\n submenu.addAction(subaction)\n \n noneaction.isChecked()\n self.menuSettings.addMenu(self.menuExtent)\n \n self.actionDebugging_messages.setChecked(self.logger.debugging)\n\n self.setWindowTitle(\"Zupport GUI\")\n \n self.load_tools()\n \n self.toolTreeWidget.itemSelectionChanged.connect(self.update_ui)\n self.actionDebugging_messages.toggled.connect(self._set_debugging)\n self.menuExtent.triggered.connect(self.update_ui)\n self.actionLoad_tool.triggered.connect(self.show_tool_gui)\n self.toolTreeWidget.doubleClicked.connect(self.show_tool_gui)\n \n def closeEvent(self, event):\n settings = QSettings()\n settings.setValue(\"Logging/debugging\", self.logger.debugging)\n settings.setValue(\"MainWindow/Size\", QVariant(self.size()))\n settings.setValue(\"MainWindow/Position\",\n QVariant(self.pos()))\n settings.setValue(\"MainWindow/State\",\n QVariant(self.saveState()))\n \n def load_tools(self):\n plugins = self.manager.plugins\n for name, plugin in plugins.iteritems():\n item = QTreeWidgetItem(QStringList(name.capitalize()))\n tool_items = []\n for tool_name in plugin.tool_names():\n tool_items.append(QTreeWidgetItem(QStringList(tool_name)))\n item.addChildren(tool_items)\n self.toolTreeWidget.addTopLevelItem(item)\n item.setExpanded(True)\n \n self.statusbar.showMessage(\"Succesfully loaded %s plugins\" % len(plugins), \n 4000)\n \n def show_tool_gui(self):\n selected_tool = self.toolListWidget.currentItem()\n toolname = str(selected_tool.text())\n parameters = self.manager.plugins[toolname]\n \n # Check if extent is available\n extent = self.extenactiongroup.checkedAction()\n if extent:\n extent = str(extent.text())\n # Extent is a String of the form \"area: resolution\"\n area, resolution = extent.split(':')\n resolution = int(resolution)\n self.extent.resolution = resolution\n # This is a list of coordinates\n coordinates = self.extent.get_extent(area)\n # Create a string for the GUI\n coord_text = ', '.join([str(coord) for coord in coordinates])\n self.manager.plugins[toolname].set_parameter_value('extent', coord_text)\n \n dataset = ToolLoader(toolname, parameters)\n if dataset.edit():\n self.logger.debug('User pressed OK, proceeding to execution')\n self.manager.plugins[toolname] = dataset.get_parameters()\n \n # Run the tool\n \n if self.actionArcGIS.isChecked():\n backend = 'arcgis'\n else:\n backend = 'osgeo'\n \n else:\n self.logger.debug('User pressed cancel')\n return\n \n self.manager.executetool(toolname, backend)\n \n def update_ui(self):\n if self.toolTreeWidget.currentItem():\n self.actionLoad_tool.setEnabled(True)\n selected_tool = str(self.toolTreeWidget.currentItem().text(0))\n help_text = self.manager.plugins[selected_tool].help\n self.helpTextEdit.setText(help_text)\n \n extent = self.extenactiongroup.checkedAction()\n if extent: \n self.extentLabel.setText(\"Current extent: %s\" % extent.text())\n \n @Slot()\n def on_actionAbout_triggered(self):\n QMessageBox.about(self, \"About Zupport GUI\",\n \"\"\"Zupport GUI v %s\n

Copyright © 2011 Joona Lehtomaki \n .\n All rights reserved.\n

Support zools for Zonation related pre- and post-processing operations.

\n

Python %s - Qt %s - PySide %s on %s

\"\"\" % (\n __version__, platform.python_version(),\n QT_VERSION,\n PYQT_VERSION, platform.system()))\n \n @Slot()\n def on_actionOpen_log_triggered(self):\n logfile = os.path.join(USER_DATA_DIR, 'zupport.log')\n if os.path.exists(logfile):\n import webbrowser\n webbrowser.open(logfile)\n self.logger.debug('Opened log file %s' % logfile)\n else:\n msg = \"Zupport log file cannot be found in default location %s\" % os.path.dirname(logfile)\n self.logger.debug(msg)\n QMessageBox.warning(self, \"File not found\", \n msg, \n buttons=QMessageBox.Ok, \n defaultButton=QMessageBox.NoButton)\n \n def _set_debugging(self, toggle):\n self.logger.debugging = toggle\n \nclass OutLog:\n def __init__(self, edit, out=None, color=None):\n \"\"\"(edit, out=None, color=None) -> can write stdout, stderr to a\n QTextEdit.\n edit = QTextEdit\n out = alternate stream ( can be the original sys.stdout )\n color = alternate color (i.e. color stderr a different color)\n Example usage:\n import sys\n sys.stdout = OutLog( edit, sys.stdout)\n sys.stderr = OutLog( edit, sys.stderr, QtGui.QColor(255,0,0) )\n \"\"\"\n self.edit = edit\n self.out = out\n self.color = color\n\n def write(self, m):\n if self.color:\n tc = self.edit.textColor()\n self.edit.setTextColor(self.color)\n\n self.edit.moveCursor(QTextCursor.End)\n self.edit.insertPlainText( m )\n\n if self.color:\n self.edit.setTextColor(tc)\n\n if self.out:\n self.out.write(m)\n \n#------------------------------------------------------------------------------ \n# Zupport DataSets\n\nclass ToolLoader(datatypes.DataSet):\n '''Base class for other loaders. \n \n Parameters' value modification will be done in-place after which the actual \n tool is executed. If parameter values are provided as args or kwargs these \n will be used as default values for the GUI, else parameter definition \n default values will be used if present.\n '''\n \n def __init__(self, toolname, parameters, *args, **kwargs):\n \n # HACK - by default there seems to be object persistent between the \n # creation of different ToolLoader objects\n self._items = []\n \n datatypes.DataSet.__init__(self, title=toolname, comment='', \n *args, **kwargs)\n \n self.logger = Logger('Zupport.GUIloader.ToolLoader', debugging=True)\n self.logger.debug(\"Creating GUI for tool %s\" % toolname)\n self.parameters = parameters\n \n for parameter in parameters:\n self.add_dataitem(parameter)\n \n def add_dataitem(self, item):\n ''' Adds a data item to a :mod:`guidata` DataSet. \n \n Normally items are created from class attributes by metaclass \n DataSetMeta and dynamically created class attributes are not converted\n into data items. \n \n TODO: Method is a hack to guidata and a more clean API access should be\n implemented.\n \n Parameters:\n item - Object to be converted to a DataItem\n '''\n\n if isinstance(item, Parameter):\n dataitem = self.parameter_to_dataitem(item)\n name = item.name\n else:\n name = ''\n \n # Following block borrowed from DataSetMeta, self._items is a list of \n # DataItems\n \n if isinstance(dataitem, datatypes.DataItem):\n dataitem.set_name(name)\n # Check if the attribute is already in self._items\n for _item in self._items:\n if name == _item._name:\n dataitem._order = _item._order\n self._items.insert(dataitem._order, dataitem)\n \n def parameter_to_dataitem(self, parameter):\n ''' Method converts a given Parameter object to a suitable guidata \n DataItem\n '''\n \n param_type = type(parameter.value)\n dataitem = None\n \n if param_type is BooleanType:\n dataitem = dataitems.BoolItem(label=parameter.label, \n default=parameter.value,\n required=parameter.required,\n help=parameter.tip)\n elif param_type is FloatType:\n dataitem = dataitems.FloatItem(label=parameter.label, \n default=parameter.value,\n required=parameter.required,\n help=parameter.tip)\n elif param_type is IntType:\n dataitem = dataitems.IntItem(label=parameter.label, \n default=parameter.value,\n required=parameter.required,\n help=parameter.tip)\n elif param_type is ListType:\n dataitem = dataitems.ChoiceItem(label=parameter.label, \n choices=parameter.value,\n required=parameter.required,\n help=parameter.tip)\n elif param_type is StringType:\n if parameter.name == 'help':\n #dataitem = dataitems.TextItem(label=parameter.name,\n # default=parameter.value,\n # help=parameter.tip)\n self.__doc__ = parameter.value\n return None\n else:\n values = parameter.value.split(':')\n if 'PATH' in values[0]:\n path = ''\n if len(values) > 1:\n path = path + ''.join(values[1:])\n dataitem = dataitems.DirectoryItem(label=parameter.label,\n default=path,\n notempty=parameter.required,\n help=parameter.tip)\n else:\n dataitem = dataitems.StringItem(label=parameter.label,\n default=parameter.value,\n required=parameter.required,\n help=parameter.tip)\n return dataitem\n \n def get_parameters(self):\n \n # TODO: guidata apparently mangles the object attribute names so that\n # attributeA becomes object._attributeA --> shouldn't be so, might \n # have something to do with the dynamic creation of object attributes\n \n for parameter in self.parameters:\n try:\n if parameter.name != 'help':\n parameter.value = getattr(self, '_' + parameter.name)\n self.logger.debug(\"Updated dataset parameter %s to value %s\" % (parameter.name, parameter.value))\n except AttributeError:\n self.logger.error(\"Parameter / attribute mismatch: %s \" % parameter.name)\n \n return self.parameters\n\n#------------------------------------------------------------------------------ \n# Run the main GUI\n\ndef main():\n \n # Init the Qt basics\n from guidata.qt.QtGui import QApplication\n app = QApplication(sys.argv)\n app.setApplicationName(\"Zupport\")\n app.setApplicationVersion(__version__)\n app.setOrganizationName(\"HU\")\n app.setOrganizationDomain(\"MRG\")\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n \nif __name__ == '__main__':\n main()\n ","sub_path":"build/lib/zupport/ui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":15332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"505373829","text":"version = \"2s\"\n\nepoch = 60000\nlearning_rate1 = 1e-3 # 0.25e-3 # 1e-3\nlearning_rate2 = 1e-2 #learning_rate1 # 1e-2\nstep2_start = 100\n\nall_trains = 1000\nbatch_size = 24\nmomentum = 0.9\nweight_decay = 5e-4\ndilation = True\nuse_crop = True\nuse_rotate = True\n# iterations = 10\ngpu = True\nmulti_gpu = True # only useful when gpu=True\npixel_weight = 2\nlink_weight = 1\n\nr_mean = 123.\ng_mean = 117.\nb_mean = 104.\nmean = (r_mean, g_mean, b_mean)\n\nimage_size_train = (512, 512)\nimage_size_test = (720, 1280)\nimage_channel = 3\n\nlink_weight = 1\npixel_weight = 2\nneg_pos_ratio = 3 # parameter r in paper\n\ntrain_images_dir = \"train_images/images/\"\ntrain_labels_dir = \"train_images/ground_truth/\"\nretrain_model_index = 26200 # retrain from which model, e.g. ${saving_model_dir}/156600.mdl\ntest_model_index = 300 # test for which model, e.g. ${saving_model_dir}/156600.mdl\ntest_batch = 1\n\ntest_images_dir = \"test_images/images/\"\ntest_labels_dir = \"test_images/ground_truth/\"\nall_tests = 500\n\n","sub_path":"configs/vgg_2s_3gpu_crop.py","file_name":"vgg_2s_3gpu_crop.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"311448885","text":"from tg import expose, TGController, AppConfig\nfrom wsgiref.simple_server import make_server\nimport webhelpers2\nimport webhelpers2.text\nfrom tg.util import Bunch\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy import Column, Integer, DateTime, String, Boolean\n\n\nDBSession = scoped_session(sessionmaker(autoflush=True, autocommit=False))\nDeclarativeBase = declarative_base()\n\n#model\nclass Schueler(DeclarativeBase):\n \"\"\"\n creates a model for the Database table with which it can be accessed\n \"\"\"\n\n #name of the table\n __tablename__ = 'schueler'\n\n #list all field with its datatypes and attributes\n knr = Column(Integer, primary_key=True)\n firstname = Column(String(255))\n lastname = Column(String(255))\n gender = Column(Boolean)\n\n\ndef init_model(engine):\n \"\"\"\n init the model for the database table\n :param engine: database engie\n \"\"\"\n DBSession.configure(bind=engine)\n DeclarativeBase.metadata.create_all(engine) # Create tables if they do not exist\n\nclass RootController(TGController):\n \"\"\"\n holds the pages to render\n \"\"\"\n\n @expose(content_type='text/plain')\n def index(self):\n \"\"\"\n :return: the string which will be displayed when the page is called in the browser\n \"\"\"\n\n #get all entries in the database table\n schueler = DBSession.query(Schueler).all()\n\n #build string for return\n tmpstr = '';\n\n #adds foramted strings to the \"return string\" containing the cols of every entry in the table\n for p in schueler:\n tmpGender = ''\n if p.gender:\n tmpGender = 'M'\n else:\n tmpGender = 'W'\n\n\n tmpstr += \"Katalognummer: \"+ str(p.knr) +\" | Vorname: \"+ p.firstname +\" | Nachname: \" + p.lastname + \" | Geschlecht: \" + str(tmpGender)\n tmpstr += \"\\n\"\n\n #returns the string which will be displayed on the page\n return tmpstr;\n\n\n#sets the RootCOntroller\nconfig = AppConfig(minimal=True, root_controller=RootController())\n#sets the template to kajiki (recommenden by doku)\nconfig.renderers = ['kajiki']\nconfig['helpers'] = webhelpers2\n#db engine (for queries)\nconfig['use_sqlalchemy'] = True\n#path to db\nconfig['sqlalchemy.url'] = 'sqlite:///devdata.db'\n\n#configure the model\nconfig['model'] = Bunch(\n DBSession=DBSession,\n init_model=init_model\n)\napplication = config.make_wsgi_app()\n\n#hosting the server on localhost:8080\nprint(\"Serving on port 8080...\")\nhttpd = make_server('', 8080, application)\nhttpd.serve_forever()\n","sub_path":"sew/TurboGears/tgapp.py","file_name":"tgapp.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"276484367","text":"import sys, os\nimport subprocess as sub\nfrom threading import Thread\nfrom queue import Queue, Empty\nfrom PyQt5 import Qt, QtWidgets, uic\nfrom bioservices import KEGG\n\n\ndef iter_except(function, exception):\n \"\"\"Works like builtin 2-argument `iter()`, but stops on `exception`.\"\"\"\n try:\n while True:\n yield function()\n except exception:\n return\n\n\nclass NewGenome(QtWidgets.QMainWindow):\n def __init__(self):\n super(NewGenome, self).__init__()\n uic.loadUi('NewGenome.ui', self)\n\n self.k = KEGG()\n\n #---Button Modifications---#\n self.setWindowIcon(Qt.QIcon(\"cas9image.png\"))\n self.whatsthisButton.clicked.connect(self.whatsthisclicked)\n self.lineEdit_1.textEdited(self.updatekegglist)\n self.keggsearchresults.setReadOnly(True)\n\n\n #show functionalities on window\n self.show()\n\n ####---FUNCTIONS TO RUN EACH BUTTON---####\n def findFasta(self):\n choice = QtWidgets.QMessageBox.question(self, \"Extract!\", \"Are you sure you want to Quit?\",\n QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)\n if choice == QtWidgets.QMessageBox.Yes:\n sys.exit()\n else:\n pass\n\n def testcheckandradio(self, state):\n if state == QtCore.Qt.Checked:\n pass\n\n def whatsthisclicked(self):\n QtWidgets.QMessageBox.information(self, \"Organism Code\", \"The organism code is the manner in which CASPER will\"\n \"label it's data files and references for the organism\"\n \"you are importing here. It is HIGHLY RECOMMENDED that\"\n \"you use the 3-4 letter code used by KEGG as this will\"\n \"aid in automatic accession of annotations from the\"\n \"database.\", QtWidgets.QMessageBox.Ok)\n\n def updatekegglist(self):\n self.keggsearchresults.clear()\n kegg_orglist = self.k.lookfor_organism(self.lineEdit_1.text())\n for item in kegg_orglist:\n item += \"\\n\"\n self.keggsearchresults.insertPlainText(item)\n\n def run_job(self):\n newdatafile = self.lineEdit_3.text() + self.comboBoxEndo.currentText() + \".txt\"\n newdatafile = str(os.curdir) + newdatafile\n f = open(newdatafile, 'w')\n # Write the organism name and subspecies/strain if applicable to the top of the file\n f.write(self.lineEdit_1.text() + self.lineEdit_2.text() + self.comboBoxEndo.currentText())\n\n def reset(self):\n self.lineEdit_1.clear()\n self.lineEdit_2.clear()\n self.lineEdit_2.clear()\n self.keggsearchresults.clear()\n\n\n\nclass DisplaySubprocessOutput:\n def __init__(self, window, outlabel, passinfo): # location of .exe and infopath of the cfcode file with information\n self.root = window\n self.outlabel = outlabel\n\n # start dummy subprocess to generate some output\n self.process = sub.Popen(passinfo, stdout=sub.PIPE)\n\n # launch thread to read the subprocess output\n # (put the subprocess output into the queue in a background thread,\n # get output from the queue in the GUI thread.\n # Output chain: process.readline -> queue -> label)\n q = Queue(maxsize=1024) # limit output buffering (may stall subprocess)\n t = Thread(target=self.reader_thread, args=[q])\n t.daemon = True # close pipe if GUI process exits\n t.start()\n\n # show subprocess' stdout in GUI\n self.label = tk.Label(self.root, text=\" \", font=(None, 12))\n self.label.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')\n self.clabel = tk.Label(self.root, text=\" \", font=(None, 12))\n self.clabel.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')\n self.update(q) # start update loop\n\n def reader_thread(self, q):\n \"\"\"Read subprocess output and put it into the queue.\"\"\"\n try:\n with self.process.stdout as pipe:\n for line in iter(pipe.readline, b''):\n q.put(line)\n finally:\n q.put(None)\n\n def update(self, q):\n \"\"\"Update GUI with items from the queue.\"\"\"\n for line in iter_except(q.get_nowait, Empty): # display all content\n if line is None:\n self.outlabel['text'] = \"Program Complete.\"\n self.quit()\n return\n else:\n self.label['text'] = line # update GUI\n if \"Chromosome\" in line:\n self.clabel['text'] = line\n if \"Time\" in line:\n tk.Label(self.root, text=line, font=(None, 12)).pack(ipadx=2, fill=\"both\")\n if \"There\" in line:\n tk.Label(self.root, text=line, font=(None, 12)).pack(ipadx=2, fill=\"both\")\n break # display no more than one line per 40 milliseconds\n self.root.after(40, self.update, q) # schedule next update\n\n def quit(self):\n self.process.kill() # exit subprocess if GUI is closed (zombie!)","sub_path":"NewGenome.py","file_name":"NewGenome.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"450034026","text":"import os, glob\nimport numpy as np\nfrom network_analysis.global_network_properties import get_efficiency\nfrom network_analysis.norm_cm_by_atlas_areas import norm_mat\nfrom scipy.stats import skew\nimport matplotlib.pyplot as plt\n\nfrom network_analysis.norm_cm_by_random_mat import make_n_rand_mat\n\nsubj_list = glob.glob(f'G:\\data\\V7\\HCP\\*[0-9]{os.sep}')\nadd_eff=[]\nnum_eff=[]\nfa_eff=[]\n#dist_eff=[]\n\nth = 'HistMatch'\natlas = 'yeo7_200'\nfor sl in subj_list:\n\n add_cm = np.load(f'{sl}cm{os.sep}{atlas}_ADD_{th}_SC_cm_ord.npy')\n add_eff.append(get_efficiency(add_cm))\n\n\n num_cm = np.load(f'{sl}cm{os.sep}{atlas}_Num_{th}_SC_cm_ord.npy')\n num_eff.append(get_efficiency(num_cm))\n\n\n fa_cm = np.load(f'{sl}cm{os.sep}{atlas}_FA_{th}_SC_cm_ord.npy')\n fa_eff.append(get_efficiency(fa_cm))\n\n\n #dist_mat = np.load(f'{sl}cm{os.sep}{atlas}_Dist_{th}_SC_cm_ord.npy')\n #dist_eff.append(get_efficiency(dist_mat))\n\n\nplt.hist(num_eff,15, color=[0.2, 0.7, 0.6], histtype='step',linewidth=3, range=(0, 0.05))\nplt.hist(add_eff,15, color=[0.8, 0.5, 0.3], histtype='step',linewidth=3, range=(0, 0.05))\nplt.hist(fa_eff,15, color=[0.3, 0.3, 0.5], histtype='step',linewidth=3, range=(0, 0.05))\n\nplt.legend([f'Num Eglob \\n Mean: {np.round(np.nanmean(num_eff),3)}, STD: {np.round(np.nanstd(num_eff),3)} \\n Skewness: {np.round(skew(num_eff, nan_policy=\"omit\"),3)}',\n f'ADD Eglob \\n Mean: {np.round(np.nanmean(add_eff),3)}, STD: {np.round(np.nanstd(add_eff),3)} \\n Skewness: {np.round(skew(add_eff, nan_policy=\"omit\"),3)}',\n f'FA Eglob \\n Mean: {np.round(np.nanmean(fa_eff), 3)}, STD: {np.round(np.nanstd(fa_eff), 3)} \\n Skewness: {np.round(skew(fa_eff, nan_policy=\"omit\"), 3)}'])\nplt.show()","sub_path":"HCP_network_analysis/Eglob_ADD_Num_hist.py","file_name":"Eglob_ADD_Num_hist.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"150431939","text":"import re\nimport requests\nimport datetime\nimport random\n\nfrom settings import (bot_token, api_ulr, chat_admin, t_channel, t_site)\nfrom dict_commands import *\nfrom utils import (random_int, get_weather_now, get_update, get_update,\n get_last_update, get_chat_id, get_last_chat_id, send_msg,\n understand, check_to_admin, get_user_name_info,\n )\n\n\nlast_update = None\nnew_offset = 0\nnow = None\nhour = None\n\nsprint = False\nsprint_list = []\n\n# Cycle bot work\nwhile True:\n try:\n\n update = get_update(offset=new_offset)\n if last_update != get_last_update(update) and get_last_update(update):\n ask = True\n now = datetime.datetime.now() + datetime.timedelta(hours=3)\n hour = now.hour\n last_update = get_last_update(update)\n last_update_id = last_update['update_id']\n last_chat_message = last_update.get('message', None)\n\n last_chat_text = None\n last_chat_id = None\n last_chat_name = None\n last_chat_date = None\n\n if last_chat_message:\n last_chat_text = last_chat_message.get('text', None)\n last_chat_id = last_chat_message['chat']['id']\n last_chat_name = last_chat_message['chat']['first_name']\n last_chat_date = (datetime.datetime.fromtimestamp(int(last_chat_message['date'])) + datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')\n\n command = last_chat_text.lower() if last_chat_message else ''\n\n if command == \"sprint start\":\n if check_to_admin(last_chat_id):\n if not sprint:\n sprint = True\n text = \"Акцію запущено...\"\n else:\n text = \"Триває попередня акція!\"\n else:\n text = \"В доступі відмовлено. Лише адміністратор може запустити акцію!\"\n send_msg(id=last_chat_id, text=text)\n\n answer = True\n ask = False\n\n if command == \"sprint stop\":\n if check_to_admin(last_chat_id):\n if sprint:\n sprint = False\n text = \"Акцію зупинено!\"\n else:\n text = \"Не запущена жодна акція!\"\n else:\n text = \"В доступі відмовлено. Лише адміністратор може зупинити акцію!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"tkostopil\":\n if sprint:\n text = \"Ви щойно прийняли участь в акції. \\nЗа результатами слідкуйте в нашому телеграм каналі {}\\n\".format(t_channel)\n user = last_update['message']['from']\n user_id = user[\"id\"]\n text = text + \"Користувач: \" + get_user_name_info(user) + \".\\n\"\n text = text + \"Дата: \" + str(last_chat_date)\n\n user_name_info = get_user_name_info(user)\n user_username_info = '@' + str(user[\"username\"])\n user_date_info = str(last_chat_date)\n\n user_is_unique = True\n\n for one in sprint_list:\n if one['username'] == user_username_info:\n user_is_unique = False\n text = \"В акції можна прийняти участь лише один раз. \\nЗа результатами слідкуйте в нашому телеграм каналі {}\\n\".format(t_channel)\n text = text + \"Користувач: \" + str(one['user']) + \".\\n\"\n text = text + \"Дата: \" + str(one['date'])\n\n if user_is_unique:\n sprint_list.append({\n 'chat_id': last_chat_id,\n 'user': user_name_info,\n 'username': user_username_info,\n 'date': user_date_info,\n })\n\n elif not sprint and sprint_list:\n text = \"Акцію завершено !!! \\n\"\n text = text + \"За результатами слідкуйте в нашому телеграм каналі {}\\n\".format(\n t_channel)\n\n elif not sprint and not sprint_list:\n text = \"Акцію ще не розпочато !!!\"\n\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint status\":\n if check_to_admin(last_chat_id):\n if sprint:\n text = \"Акція триває\"\n\n elif not sprint and sprint_list:\n text = \"Акцію завершено !!! \\n\"\n\n elif not sprint and not sprint_list:\n text = \"Акцію ще не розпочато !!!\"\n\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint list\":\n if check_to_admin(last_chat_id):\n if sprint_list:\n text = \"\"\n i = 1\n for one in sprint_list:\n text = text + str(i) + \". \" + str(one['user']) + \" \" + str(one['username']) + \" \" + str(one['date']) + \"\\n\"\n i = i + 1\n else:\n text = \"Результатів покищо немає.\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint list full\":\n if check_to_admin(last_chat_id):\n if sprint_list:\n text = \"\"\n i = 1\n for one in sprint_list:\n text = text + str(i) + \". \" + str(one['user'])\\\n + \" \" + str(one['username']) + \" #\" + str(one['chat_id']) + \" \" + str(one['date']) + \"\\n\"\n i = i + 1\n else:\n text = \"Результатів покищо немає.\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint list first\":\n if check_to_admin(last_chat_id):\n if sprint_list:\n\n text = \"1. \" + str(sprint_list[0]['user']) + \" \" + str(sprint_list[0]['username']) + \" \" + str(sprint_list[0]['date'])\n\n else:\n text = \"Результатів покищо немає.\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint list random\":\n if check_to_admin(last_chat_id):\n if sprint_list:\n max_users = len(sprint_list)\n if max_users == 1:\n text = \"1. \" + str(sprint_list[0]['user']) + \" \" + str(sprint_list[0]['username']) + \" \" + str(sprint_list[0]['date'])\n elif max_users > 1:\n random_number = random_int(max_users)\n text = str(random_number) + \". \" + str(sprint_list[int(random_number)-1]['user']) + \" \" + str(sprint_list[int(random_number)-1]['username']) + \" \" + str(sprint_list[int(random_number)-1]['date'])\n else:\n text = \"Результатів покищо немає.\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"sprint list clean\":\n if check_to_admin(last_chat_id):\n if sprint_list:\n sprint_list = []\n text = \"Список учасників акції ОЧИЩЕНО!\"\n else:\n text = \"Результатів покищо немає.\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if command == \"help\":\n if check_to_admin(last_chat_id):\n text = \"\"\"\n Короткий опис команд управління акціями:\n \n sprint start - запуск акції\n sprint status - перевірити статус акції\n sprint stop - зупинка акції\n \n tkostopil - прийняти участь в акції (публічна команда)\n \n sprint list - показати список учасників акції\n sprint list full - показати список учасників акції з повною інформаціє про учасника\n sprint list first - показати першого учасника акції\n \n sprint list random - показати рандомний вибір учасників\n \n sprint list clean - очистити список учасників акції\n \"\"\"\n else:\n text = \"В доступі відмовлено!\"\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n for one in hello_commands:\n answer = False\n if re.search(one, command) and not answer and 6 <= hour < 12:\n text = 'Доброго ранку, {}. '.format(last_chat_name)\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n elif re.search(one, command) and not answer and 12 <= hour < 17:\n text = 'Доброго дня, {}. '.format(last_chat_name)\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n elif re.search(one, command) and not answer and 17 <= hour <= 23:\n text = 'Добрий вечір, {}. '.format(last_chat_name)\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n elif re.search(one, command) and not answer and 0 <= hour < 6:\n text = 'Доброї ночі, {}. Засинаю...'.format(last_chat_name)\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n for one in weather_commands:\n answer = False\n if re.search(one, command) and not answer:\n weather_now = get_weather_now()\n plus_temp = ''\n if weather_now['temp'] > 0:\n plus_temp = '+'\n text = 'В Костополі ' + str(plus_temp) + str(weather_now['temp']) + ' C. За вікном ' + str(weather_now['description']) + ', хмарність ' + str(weather_now['clouds']) + '%'\n send_msg(id=last_chat_id, text=text)\n answer = True\n ask = False\n\n if not understand(command, start_commands, last_chat_id, ':) ку...'):\n ask = False\n\n text = 'Інтерактивні новини можна проглянути на нашому каналі в telegram\\n{}\\nта на нашому сайті\\n{}'.format(\n t_channel, t_site)\n if not understand(command, news_commands, last_chat_id, text):\n ask = False\n\n text = 'Для цього чату ваш id: {} '.format(last_chat_id)\n if not understand(command, id_commands, last_chat_id, text):\n ask = False\n\n text = 'Можу запропонувати послухати музику яку слухаю я...\\n\\nhttps://soundcloud.com/ramon-yaskal/sets/trap-for-travel'\n if not understand(command, music_commands, last_chat_id, text):\n ask = False\n\n text = 'Я Бот telegram каналу\\n{}\\nМене звати Бот Типовий Костопіль @tkostopil_bot. Мені 18 років. Живу в місті Костопіль. Моє хоббі - цікавитись новинами міста і не тільки, а й всієї області та навіть всієї країни. Долучайся до мого телеграм каналу щоб інтерактивно отримувати новини. Також не забудь відвідати наш сайт та інтернет магазин\\n{}'.format(\n t_channel, t_site)\n if not understand(command, who_are_you_commands, last_chat_id, text):\n ask = False\n\n text = 'Якщо ти шукаєш роботу... переглянь пропозиції на сайті {}/?q=робота+в+костополі'.format(t_site)\n if not understand(command, find_work_commands, last_chat_id, text):\n ask = False\n\n text = 'Дуже приємно. Красиве імя.'\n if not understand(command, you_name_commands, last_chat_id, text):\n ask = False\n\n text = 'Читаю новини на сайті {}'.format(t_site)\n if not understand(command, what_you_do_commands, last_chat_id, text):\n ask = False\n\n text = 'Так.'\n if not understand(command, truly_commands, last_chat_id, text):\n ask = False\n\n text = 'Як же ш я люблю Костопіль... '\n if not understand(command, kostopil_commands, last_chat_id, text):\n ask = False\n\n if ask:\n send_msg(id=last_chat_id, text='Не можу зрозуміти запитання...')\n send_msg(id=last_chat_id, text='Але ось що мені вдалось знайти за Вашим запитом\\nhttps://www.google.com.ua/search?q={}'.format(command.replace(' ', '+')))\n new_offset = last_update_id + 1\n\n except:\n print(\"BOT GLOBAL ERROR\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":15715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"29158587","text":"#!/bin/env python3\n\nimport sys\nfrom knights_tour_graph import knightGraph, pprint\n\ndef knightTour(n,path,u,limit):\n \"\"\"\n @u - start \n @limit - end\n @path - traversed[]\n @n - level/depth (query whether all nodes covered)\n \"\"\"\n u.setColor('gray')\n path.append(u)\n if n < limit:\n nbrList = list(u.getConnections())\n i = 0\n done = False\n while i < len(nbrList) and not done:\n #import pdb; pdb.set_trace()\n cv = G.getVertex(nbrList[i])\n # print(u._id, u.getColor(), nbrList, cv._id, cv.getColor(), limit, path)\n if cv.getColor() == 'white':\n done = knightTour(n+1, path, cv, limit)\n i += 1\n if not done: # prepare to backtrack\n # print(\"backtracking \", u._id, u.getColor())\n path.pop()\n u.setColor('white')\n else:\n print(n, len(path), u._id, u.getColor(), limit) \n done = True\n return done\n\n\nif __name__ == '__main__':\n\n try:\n board_size = int(sys.argv[1])\n except:\n board_size = 5\n \n G = knightGraph(board_size)\n u = G.getVertex(0)\n print(knightTour(0, [], u, board_size**2 - 1))\n","sub_path":"algorithms_DS/COURSES/pythonds/chapter_7_graphs/knights_tour_dfs_undirected_colored.py","file_name":"knights_tour_dfs_undirected_colored.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"264366048","text":"#! python\r\n# coding: utf-8\r\n\r\ndoor = input('Дай мені розміри дверей (Висота Ширина) \\r\\n').split()\r\n\r\nif (len(door) < 2) | (len(door) >= 3):\r\n\tprint('Нєєєє братіш. Мене не обдуриш. Давай ще раз.\\r\\n')\r\n\texit()\r\n\r\nif int(door[0]) > int(door[1]):\r\n\th = int(door[0])\r\n\tw = int(door[1])\r\nelse:\r\n\th = int(door[1])\r\n\tw = int(door[0])\r\n\t\r\nbox = input('Дай мені розміри коробки (Всі три)\\r\\n').split();\r\n\t\r\nif len(box) < 3:\r\n\tprint('Нєєєє братіш. Мене не обдуриш. Давай ще раз.\\r\\n')\r\n\texit()\r\n\t\r\na = int(box[0])\r\nb = int(box[1])\r\nc = int(box[2])\r\n\r\nif (a <= h) & (b <= w):\r\n\tprint('IT FITS. YAY.')\r\nelif(b <= h) & (a <= w):\r\n\tprint('IT FITS. YAY.')\r\nelif(c <= h) & (b <= w):\r\n\tprint('IT FITS. YAY.')\r\nelif(a <= h) & (c <= w):\r\n\tprint('IT FITS. YAY.')\r\nelif(b <= h) & (c <= w):\r\n\tprint('IT FITS. YAY.')\r\nelif(c <= h) & (a <= w):\r\n\tprint('IT FITS. YAY.')\r\nelse:\r\n\tprint('Your box is too fat!')","sub_path":"lab5_2.py","file_name":"lab5_2.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"18368203","text":"# -*- coding: utf-8 -*-\n\nimport re\n\n#过滤掉除了中文以外的字符\nstr = \"hello,world!!%[545]你好234世界。。。\"\nstr = re.sub(\"[A-Za-z0-9\\!\\%\\[\\]\\,\\。]\", \"\", str)\nprint(str)\n \n#提取字符串里的中文,返回数组\npattern=\"[\\u4e00-\\u9fa5]+\"\nregex = re.compile(pattern)\nresults = regex.findall(\"adf中文adf发京东方23带手\")\nprint(results)\n","sub_path":"justChinese.py","file_name":"justChinese.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"566300346","text":"from __future__ import division, print_function, absolute_import\n\nimport os\nimport utils.cuda_util_ti4\nfrom random import shuffle\n\nimport numpy as np\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.applications.resnet50 import preprocess_input\nfrom keras.callbacks import TensorBoard\nfrom keras.layers import Dense, Flatten, Dropout, BatchNormalization, Activation\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras.optimizers import Adam, SGD\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\n\nfrom utils.file_helper import safe_rmdir\n\n\ndef load_data(LIST, TRAIN, camera_cnt, class_cnt):\n images_in_cameras, labels_in_cameras = [[] for _ in range(camera_cnt)], [[] for _ in range(camera_cnt)]\n last_labels, label_cnts = [-1 for _ in range(camera_cnt)], [-1 for _ in range(camera_cnt)]\n with open(LIST, 'r') as f:\n for line in f:\n line = line.strip()\n img = line\n lbl = line.split('_')[0]\n camera = int(line.split('_')[1][1]) - 1\n if last_labels[camera] != lbl:\n label_cnts[camera] += 1\n last_labels[camera] = lbl\n img = image.load_img(os.path.join(TRAIN, img), target_size=[224, 224])\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = preprocess_input(img)\n\n images_in_cameras[camera].append(img[0])\n labels_in_cameras[camera].append(label_cnts[camera])\n print(label_cnts)\n for i in range(camera_cnt):\n img_cnt = len(labels_in_cameras[i])\n shuffle_idxes = range(img_cnt)\n shuffle(shuffle_idxes)\n shuffle_imgs = list()\n shuffle_labels = list()\n for idx in shuffle_idxes:\n shuffle_imgs.append(images_in_cameras[i][idx])\n shuffle_labels.append(labels_in_cameras[i][idx])\n images_in_cameras[i] = np.array(shuffle_imgs)\n labels_in_cameras[i] = to_categorical(shuffle_labels, label_cnts[i] + 1)\n return images_in_cameras, labels_in_cameras, label_cnts\n\n\ndef multi_generator(images_in_cameras, labels_in_cameras, batch_size, train=True):\n camera_cnt = len(images_in_cameras)\n if train:\n img_aug = ImageDataGenerator(\n rotation_range=30, brightness_range=[0.8, 1.0], zoom_range=0.1,\n shear_range=0.2, width_shift_range=0.2, height_shift_range=0.2,\n horizontal_flip=0.5)\n else:\n img_aug = ImageDataGenerator()\n generators = [img_aug.flow(images_in_cameras[i], labels_in_cameras[i], batch_size=batch_size) for i in\n range(camera_cnt)]\n while True:\n feed_images = []\n feed_labels = []\n for i in range(camera_cnt):\n images, labels = generators[i].next()\n if len(labels) != batch_size:\n images, labels = generators[i].next()\n feed_images.append(images)\n feed_labels.append(labels)\n yield feed_images, feed_labels\n\n\ndef multi_branch_model(label_cnts, camera_cnt):\n # load pre-trained resnet50\n base_model = ResNet50(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))\n for layer in base_model.layers:\n layer.trainable = True\n if isinstance(layer, BatchNormalization):\n layer.trainable = False\n for layer in base_model.layers[: len(base_model.layers) // 3]:\n layer.trainable = False\n img_inputs = []\n softmax_outputs = []\n dropout = Dropout(0.5)\n for i in range(camera_cnt):\n img_inputs.append(Input(shape=(224, 224, 3), name='img_%d' % i))\n x = base_model(img_inputs[i])\n x = dropout(Flatten()(x))\n x = Dense(label_cnts[i] + 1)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n sm_output = Activation('softmax', name='sm_out_%d' % i)(x)\n softmax_outputs.append(sm_output)\n net = Model(inputs=img_inputs, outputs=softmax_outputs)\n # plot_model(net, to_file='multi_branch.png')\n return net\n\n\ndef multi_branch_train(train_list, train_dir, class_count, camera_cnt, target_model_path):\n images_in_cameras, labels_in_cameras, label_cnts = load_data(train_list, train_dir, camera_cnt, class_count)\n train_images = [[] for _ in range(camera_cnt)]\n val_images = [[] for _ in range(camera_cnt)]\n train_labels = [[] for _ in range(camera_cnt)]\n val_labels = [[] for _ in range(camera_cnt)]\n for i in range(camera_cnt):\n data_cnt = len(images_in_cameras[i])\n train_images[i] = images_in_cameras[i][:data_cnt // 10 * 9]\n train_labels[i] = labels_in_cameras[i][:data_cnt // 10 * 9]\n val_images[i] = images_in_cameras[i][data_cnt // 10 * 9:]\n val_labels[i] = labels_in_cameras[i][data_cnt // 10 * 9:]\n train_images_cnt = [len(train_images[i]) for i in range(camera_cnt)]\n sum_train_images_cnt = sum(train_images_cnt)\n loss_weights = [train_images_cnt[i] / sum_train_images_cnt for i in range(camera_cnt)]\n print('loss weights')\n print(loss_weights)\n max_train_images_cnt = max(train_images_cnt)\n max_val_images_cnt = max([len(val_images[i]) for i in range(camera_cnt)])\n print('max_train_images_cnt:%d' % max_train_images_cnt)\n print('max_val_images_cnt:%d' % max_val_images_cnt)\n\n loss_dict = {}\n loss_weights_dict = {}\n for i in range(camera_cnt):\n loss_dict['sm_out_%d' % i] = 'categorical_crossentropy'\n loss_weights_dict['sm_out_%d' % i] = 0.15 # loss_weights[i]\n net = multi_branch_model(label_cnts, camera_cnt)\n for i in range(10):\n batch_size = 16\n net.get_layer('resnet50').trainable = False\n for layer in net.layers:\n if isinstance(layer, BatchNormalization):\n layer.trainable = True\n if isinstance(layer, Dense):\n layer.trainable = True\n net.compile(optimizer=Adam(lr=0.002), loss=loss_dict,\n metrics=['accuracy'], loss_weights=loss_weights_dict)\n net.fit_generator(multi_generator(train_images, train_labels, batch_size),\n steps_per_epoch=max_train_images_cnt / batch_size + 1,\n epochs=5,\n validation_data=multi_generator(val_images, val_labels, batch_size, train=False),\n validation_steps=max_val_images_cnt / batch_size + 1,\n verbose=2\n )\n\n batch_size = 14\n net.get_layer('resnet50').trainable = True\n\n for layer in net.layers:\n if isinstance(layer, BatchNormalization):\n layer.trainable = False\n if isinstance(layer, Dense):\n layer.trainable = False\n if i >= 3:\n for layer in net.get_layer('resnet50').layers:\n layer.trainable = True\n batch_size = 10\n if i > 5:\n cnn_lr = 2e-3 / i\n else:\n cnn_lr = 2e-3\n net.compile(optimizer=SGD(lr=cnn_lr, momentum=0.9, decay=0.01), loss=loss_dict,\n metrics=['accuracy'], loss_weights=loss_weights_dict)\n log_path = target_model_path.replace('.h5', '_logs')\n safe_rmdir(log_path)\n tb = TensorBoard(log_dir=log_path, histogram_freq=1, write_graph=False)\n net.fit_generator(multi_generator(train_images, train_labels, batch_size),\n steps_per_epoch=max_train_images_cnt / batch_size + 1,\n epochs=5,\n validation_data=next(multi_generator(val_images, val_labels, 90, train=False)),\n # validation_data=multi_generator(val_images, val_labels, 90, train=False),\n validation_steps=max_val_images_cnt / 90 + 1,\n verbose=2,\n callbacks=[tb]\n )\n net.save(target_model_path.replace('.h5', '_%d.h5' % i))\n net.save(target_model_path)\n\n\ndef multi_softmax_pretrain_on_dataset(source, project_path='/home/cwh/coding/rank-reid',\n dataset_parent='/home/cwh/coding'):\n camera_cnt = 6\n if source == 'market':\n train_list = project_path + '/dataset/market_train.list'\n train_dir = dataset_parent + '/Market-1501/train'\n class_count = 751\n elif source == 'grid':\n train_list = project_path + '/dataset/grid_train.list'\n train_dir = dataset_parent + '/grid_label'\n class_count = 250\n elif source == 'cuhk':\n train_list = project_path + '/dataset/cuhk_train.list'\n train_dir = dataset_parent + '/cuhk01'\n class_count = 971\n elif source == 'viper':\n train_list = project_path + '/dataset/viper_train.list'\n train_dir = dataset_parent + '/viper'\n class_count = 630\n elif source == 'duke':\n train_list = project_path + '/dataset/duke_train.list'\n train_dir = dataset_parent + '/DukeMTMC-reID/train'\n class_count = 702\n camera_cnt = 8\n elif 'grid-cv' in source:\n cv_idx = int(source.split('-')[-1])\n train_list = project_path + '/dataset/grid-cv/%d.list' % cv_idx\n train_dir = dataset_parent + '/underground_reid/cross%d/train' % cv_idx\n class_count = 125\n elif 'mix' in source:\n train_list = project_path + '/dataset/mix.list'\n train_dir = dataset_parent + '/cuhk_grid_viper_mix'\n class_count = 250 + 971 + 630\n else:\n train_list = 'unknown'\n train_dir = 'unknown'\n class_count = -1\n multi_branch_train(train_list, train_dir, class_count, camera_cnt, '../pretrain/' + source + '_multi_sl_pretrain.h5')\n\n\nif __name__ == '__main__':\n # sources = ['market', 'grid', 'cuhk', 'viper']\n sources = ['market']\n for source in sources:\n multi_softmax_pretrain_on_dataset(source)\n","sub_path":"pretrain/multi_branch_train_ti4_small_label.py","file_name":"multi_branch_train_ti4_small_label.py","file_ext":"py","file_size_in_byte":9939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"632197346","text":"from flask import Flask, render_template, request, redirect, url_for\nimport wikipedia\nimport urllib.request\nfrom gtts import gTTS\nlang=\"en\"\nsumith=\" \"\n\n\n\napp = Flask(__name__)\n@app.route('/')\ndef home():\n return render_template(\"home1.html\")\n@app.route('/button', methods=[\"POST\"])\ndef gettingText():\n text=request.form['movie']\n processed_text = text.upper()\n sumith = result(processed_text)\n myObj = gTTS(text=str(sumith), lang=lang, slow=False)\n myObj.save(\"static/sample.mp3\")\n return render_template(\"contact1.html\", sumith=sumith,sumith_title=processed_text)\n\n\ndef search(movie):\n AlResult=(wikipedia.search(movie))\n for i in range(0,len(AlResult)):\n print(str(i+1)+\"-> \"+AlResult[i])\n UserSQ=int(input())\n print(\"_\".join((AlResult[UserSQ-1]).split()))\n result(\"_\".join((AlResult[UserSQ-1]).split()))\n\n\ndef result(movie):\n page = (wikipedia.page(movie))\n content = ((page.content)).split()\n # print(page.content)\n # print(\"Hai\")\n plot = \"Plot\"\n cast = \"Cast\"\n pIndex = 0\n cIndex = 0\n cOccur = 0\n i = 0\n # checking where the plot and cast starting with the == or not\n for i in range(0, len(content)):\n if content[i] == plot and content[i - 1] == \"==\":\n pIndex = i + 2\n if content[i] == cast and content[i - 1] == \"==\":\n cIndex = i - 1\n cOccur = 1\n # print(\" \".join(content[pIndex:cIndex]))\n if (\" \".join(content[pIndex:cIndex])) == \"\":\n search(page)\n else:\n print(\"\\n\\n\")\n musick = ((\" \".join(content[pIndex:cIndex])))\n\n cOccur = 0\n st1=\" \".join(content[pIndex:cIndex])\n len1=len(st1)\n return (st1)\n\n\n@app.route('/getFileName')\ndef getFileName():\n return 'static/sample.mp3'\n\n\ndef contact():\n if \"Return\" in request.form:\n pass\n return render_template('home1.html')\n\n\nif __name__ == '__main__':\n #app.secret_key='secret123'\n app.run(debug=True)\n","sub_path":"myflaskapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"492766292","text":"\"\"\"Convert a binary list to a positive integer list. Works with more than one row input.\"\"\"\ndef b2d(inp):\n\tif isinstance(inp[0], int): #1 dimension\n\t\treturn _b2d(inp)\n\t\n\tresult=[] #2 dimensions\n\tfor item in inp:\n\t\tresult.append(_b2d(item))\n\treturn result\n\ndef _b2d(inp):\n\tresult=0\n\tinp=inp[::-1]\n\tfor col in range(len(inp)):\n\t\tif inp[col]==1:\n\t\t\tresult=result+2**col\n\treturn(result)\n","sub_path":"lib/b2d.py","file_name":"b2d.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"98853414","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\nclass LinkedList:\n def __init__(self):\n self.head=None\n\n def push(self, new_data):\n new_node = Node(new_data)\n new_node.next = self.head\n self.head = new_node\n\n\n def partition(self, head, pivot):\n dummy_tail = Node(0)\n tail = dummy_tail\n current = head\n dummy_front = Node(0)\n front = dummy_front\n\n while current:\n if current.data < pivot:\n front.next= Node(current.data)\n front=front.next\n\n else:\n tail.next=Node(current.data)\n tail=tail.next\n\n current = current.next\n\n front.next = dummy_tail.next\n\n temp = dummy_front.next\n print(\"partioned List is \")\n while (temp):\n print(temp.data);\n temp = temp.next\n\n def printList(self):\n temp = self.head\n while (temp):\n print (temp.data);\n temp = temp.next\n\n\nfirst = LinkedList()\n\n# Create first list\nfirst.push(1)\nfirst.push(2)\nfirst.push(10)\nfirst.push(5)\nfirst.push(8)\nfirst.push(5)\nfirst.push(3)\nprint (\"First List is \", first.printList())\nres = LinkedList()\nres.partition(first.head, 5)\n\n\n\n\n\n\n","sub_path":"Linked List/Partition of linked list.py","file_name":"Partition of linked list.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"1957348","text":"\"\"\"\nNOT CURRENTLY WORKING\n\"\"\"\n\nimport pickle\nimport argparse\nimport os\nimport cv2\nimport numpy as np\nimport glob\nfrom natsort import natsorted\n\n# assumes the program is run from scripts directory\nimport sys\nsys.path.insert(0, os.path.realpath('..'))\nif __name__ == '__main__':\n from utils.progress_bar import progress\n\n\ndef display_pickles(result_path):\n # Get the files\n filepaths = os.path.join(result_path, \"*.pkl\")\n files = natsorted(glob.glob(filepaths))\n\n # Parse files\n for ind, fi in enumerate(files):\n progress(ind, len(files), fraction=True)\n f = open(fi, 'rb')\n pkl = pickle.load(f)\n images = pkl[:-1]\n data = pkl[-1]\n text = f'A: {data[0]}, D: {data[1]}, W: {data[2]}, S: {data[3]}'\n\n # text properties\n font = cv2.FONT_HERSHEY_SIMPLEX\n org = (50, 50)\n fontScale = 1\n color = (0, 0, 255)\n thickness = 2\n\n # truncated file name\n fname = os.path.split(fi)[-1]\n\n for im in images:\n image = cv2.putText(im, text, org, font, fontScale,\n color, thickness, cv2.LINE_AA, False)\n cv2.imshow(fname, image)\n key = cv2.waitKey(0)\n\n if key == ord('q'):\n print()\n f.close()\n exit()\n\n cv2.destroyWindow(fname)\n f.close()\n\n\nif __name__ == '__main__':\n # Get arguments\n parser = argparse.ArgumentParser(\n description='Checks the results'\n )\n parser.add_argument('result_path', action='store',\n help='should be GTAV_program/results_resized or \\\n GTAV_program/results_cropped')\n args = parser.parse_args()\n\n if not os.path.isdir(args.result_path):\n print('the specified result folder does not exist')\n print('please generate the results first')\n exit(1)\n\n print(\"press 'q' to quit\")\n display_pickles(args.result_path)\n","sub_path":"scripts/test_results.py","file_name":"test_results.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"195535108","text":"# -------------------------神经网络训练模型---------------------------\nimport numpy as np # 数据处理常用库\nimport pandas as pd # 数据处理常用库\nimport matplotlib.pyplot as plt\nimport os\n\nNUM = 89\n\n\ndef city_D(dir):\n # 设置模型\n # 学习率\n learning_rate = 0.01 # 类似于每次梯度下降移动步长\n\n data_dir = 'D:/python/venv/2020year/2020 IKCEST/train_data_all'\n files = ['city_A', 'city_B', 'city_C', 'city_D', 'city_E', 'city_F', 'city_G',\n 'city_H', 'city_I', 'city_J', 'city_K']\n names = ['density.csv', 'grid_attr.csv', 'infection.csv', 'migration.csv', 'transfer.csv', 'weather.csv']\n\n Index = [\n ['data', 'hour', 'grid_x', 'grid_y', 'Population_flow_index'],\n ['grid_x', 'grid_y', 'region_id'],\n ['city', 'region_id', 'data', 'num_new_persons'],\n ['data', 'departure_city', 'arrival_city', 'migration_scale_index'],\n ['hour', 'start_grid_x', 'start_grid_y', 'end_grid_x', 'end_grid_y', 'transfer_intensity'],\n ['data', 'hour', 'temperature', 'humidity', 'wind_direction', 'wind_speed', 'wind_force', 'weather']\n ]\n\n # days_ = np.append(np.array(range(21200615, 21200631)), np.array(range(21200701, 21200715)))\n # days_ = days_.astype('int')\n # print(days_)\n\n for file in files[3:4]:\n i = 2\n name = names[i]\n dir_ = data_dir + '/' + file + '/' + name\n print('目前文件为{}'.format(name))\n data = pd.read_csv(dir_, header=0, names=Index[i])\n data_2 = pd.read_csv('D:/python/venv/2020year/2020 IKCEST/result/{}/submission.csv'.format(dir), header=None, names=Index[i])\n city = file.split('_')[-1]\n data_2 = data_2[data_2['city'] == city]\n\n print(data[:5])\n\n days = data['data'].unique()\n # print(days)\n region_id = data['region_id'].unique()\n\n # 创建存储路径\n save_path = r'D:\\python\\venv\\2020year\\2020 IKCEST\\result visualization\\{}\\{}'.format(dir, city)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n for id in region_id:\n data_ = data[data['region_id'] == id]\n data_2_ = data_2[data_2['region_id'] == id]\n x = np.array(range(data_.shape[0])).astype('float32')\n y_ = list(data_['num_new_persons'])\n y = []\n for i in range(len(y_)):\n y.append(sum(y_[:i+1]))\n\n # print(y)\n y = np.array(y).astype('float32')\n max_y = y.max()\n y = y.reshape((len(y), 1))\n x = x.reshape((len(x), 1))\n\n st = NUM - data_2_.shape[0]\n x_2 = np.array(range(st, NUM))\n y_2 = []\n y_0 = np.array(data_2_['num_new_persons'])\n for i in range(len(y_0)):\n y_2.append(sum(y_0[:i+1]) + max_y)\n\n plt.cla()\n plt.plot(x, y, color='blue')\n plt.plot(x_2, y_2, color='red')\n name_ = \"city {},id{}\".format(city, id)\n plt.title(name_)\n\n plt.savefig(\n r'D:\\python\\venv\\2020year\\2020 IKCEST\\result visualization\\{}\\{}\\{}'.format(dir, city, id))\n","sub_path":"result visualization/A_main/result_vis_d.py","file_name":"result_vis_d.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"626718257","text":"import numpy as np\nfrom shapely import geometry\n\nfrom ... import h5table\nfrom ...utilities import pool\n\n\n\ndef group_polygons(data,minarea=0.1):\n nnew=ndata=len(data)\n\n while nnew!=0:\n groups=[]\n\n while len(data)!=0:\n thisid,thispoly=data.pop(0)\n \n for i,(testid,testpoly) in enumerate(data):\n inter=thispoly.intersection(testpoly)\n \n r1=inter.area/testpoly.area\n r2=inter.area/thispoly.area\n if r1 > minarea and r2 > minarea: \n data.pop(i)\n\n thispoly=thispoly.union(testpoly)\n thisid.extend(testid)\n groups.append((thisid,thispoly))\n\n N=len(data)\n data=groups\n nnew=ndata-N\n ndata=N\n\n return groups\n\ndef group_ids(data):\n print(\"[info]Grouping the IDs\")\n \n # group those IDs\n nnew=ndata=len(data)\n while nnew!=0:\n new=[]\n while len(data)!=0:\n this=data.pop(0)\n for i,test in enumerate(data):\n if this.intersection(test):\n this=this.union(test)\n data.pop(i)\n new.append(this)\n data=new\n n=len(data)\n nnew=ndata-n\n ndata=n\n return data\n \n\n \ndef group_grism(grism,sources,beams,path):\n \n\n # open the file for a given grism\n with h5table.H5Table(grism.dataset,path=path,mode='r') as h5tab:\n groups=[]\n for device in grism:\n\n\n # first convert each source to a polygon\n polys=[]\n ids=[]\n for source in sources:\n\n # make a Multipolygon for each source\n poly=[]\n for beam in beams:\n\n # open the files\n h5tab.open_table(device.name,beam,'pdt')\n\n # read the data\n odt=h5tab.load_from_file(source,beam,'odt')\n ovt=odt.compute_vertices()\n this_poly=ovt.as_polygon()\n \n ## read the data \n #ovt=h5tab.load_from_file(source.name,'ovt',beam)\n #\n ## get the polygon representation\n #this_poly=ovt.as_polygon()\n\n\n # record it in the list\n poly.append(this_poly)\n\n\n # make a multipolygon over beams\n poly=geometry.MultiPolygon(poly)\n\n # make a multipolgon\n polys.append(poly) #geometry.MultiPolygon(poly))\n ids.append([source.segid])\n \n data=list(zip(ids,polys))\n\n # now group these polygons for a given device\n grouped=group_polygons(data)\n\n # update the groups\n groups.append(grouped)\n\n\n # get a list of the segids as a list of lists\n segids=list(list(zip(*groups[0]))[0])\n\n #groups=list(zip(*groups))[0]\n #segids=list(zip(*groups))[0]\n\n #print(segids)\n\n \n #ids=[set(group) for group in groups]\n ids=[set(i) for i in segids]\n\n \n # now group these IDs for the different devices\n ids=group_ids(ids)\n \n # return the SEGIDs that collide\n return ids\n\n\ndef make_groups(grisms,sources,beams,path):\n print('[info]Starting the group algorithm')\n \n\n # use the pool to group the FLTs\n p=pool.Pool(group_grism,desc='Grouping grisms',ncpu=1)\n #ids=p(grisms.values(),sources,beams,path)\n ids=[group_grism(f,sources,beams,path) for f in grisms]\n \n # make the list of lists a list of sets\n sets=[]\n for i in ids:\n sets.extend(i)\n del ids\n \n # group those IDs\n data=group_ids(sets)\n ndata=len(data)\n\n # now sort them in reverse order\n if ndata!=0:\n data.sort(key=len)\n data.reverse()\n \n # print something for something's sake\n print(\"[info]Done grouping. Found {} groups.\\n\".format(ndata))\n \n return data\n","sub_path":"pylinear/modules/extract/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"210845143","text":"import os\nimport sys\nimport timeit\nclass Proxy_Handle():\n def __init__(self, dir_name, file_name):\n self.dir_name = dir_name\n self.file_name = file_name\n self.amount = 0\n self.counter = 0\n self.err = 0\n \n def set_amount(self, amount):\n self.amount = amount\n \n def proxy_receiver_only(self, time, amount):\n self.set_amount(amount)\n record = open(os.path.join(self.dir_name, self.file_name), 'a')\n record.write(\"time: {} |\".format(str(time)[0:6])+ \" \" + \"received data: {}\".format(self.amount) + \" \\n\")\n record.close()\n \n def proxy_transmitter_only(self, time, amount):\n self.set_amount(amount)\n record = open(os.path.join(self.dir_name, self.file_name), 'a')\n record.write(\"time: {} |\".format(str(time)[0:6])+ \" \" + \"transmitted data: {}\".format(self.amount) + \" \\n\")\n record.close()\n \n def get_total(self):\n record = open(os.path.join(self.dir_name, self.file_name), 'r')\n self.counter = self.counter + 1 \n total_data = record.read()\n total_data = total_data.split()\n record.close()\n name = self.dir_name + \"/\" + self.file_name\t\t\n try:\n total_data = int(total_data[0])\n except IndexError:\n pass\n return total_data\n \n def update_total(self, amount):\n self.set_amount(amount)\n updated_data = self.get_total() + self.amount\n record = open(os.path.join(self.dir_name, self.file_name), 'w')\n record.write('{}'.format(updated_data) + \" \\n\")\n record.close()\n \n \n \n \n \n \n \n \n \n \n","sub_path":"proxy_pc/proxy_handle.py","file_name":"proxy_handle.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"371680020","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 10 01:45:41 2017\n@author: siw\nProject 3 - Binomial & Poisson\n#1. Experimental Bernoulli Trials\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef expBinomial():\n N = 10000\n n = 1000\n X = []\n \n for i in range(0, N):\n success = 0\n for j in range(0, n):\n sumOfThreeDice = sum(np.random.randint(1,7,3))\n if sumOfThreeDice == 18:\n success += 1\n X.append(success)\n \n #PMF plot\n plt.close('all')\n b = range(0,18)\n h1, bin_edges = np.histogram(X, bins = b)\n b1 = bin_edges[0:17]\n p1 = h1/N\n plt.stem(b1, p1)\n plt.title('Probability Mass Function plot - Three sixes in a roll of three fair dice\\nUsing Binomial Simulated Experiment')\n plt.xlabel('Number of Successes - Three sixes in 1000 rolls')\n plt.ylabel('Probability of Successes')\n ","sub_path":"Project 3/ExperimentalBernoulliTrials.py","file_name":"ExperimentalBernoulliTrials.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"479219510","text":"import pymysql\nfrom DBUtils.PooledDB import PooledDB, SharedDBConnection\n\nPOOL = PooledDB(\n creator=pymysql, # 使用链接数据库的模块\n maxconnections=20, # 连接池允许的最大连接数,0和None表示不限制连接数\n mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建\n maxcached=5, # 链接池中最多闲置的链接,0和None不限制\n maxshared=0, # 链接池中最多共享��链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。\n blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错\n maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制\n setsession=[], # 开始会话前执行的命令列表。如:[\"set datestyle to ...\", \"set time zone ...\"]\n ping=0,\n # ping MySQL服务端,检查是否服务可用。\n host='127.0.0.1',\n port=3306,\n user='root',\n password='123456789',\n database='code_count',\n charset='utf8'\n)\n\ndef on_open(cur=pymysql.cursors.DictCursor):\n \"\"\"\n 连接到连接池中,返回的数据格式为dict\n 1.启动时会在内存中维护一个连接池\n 2.当请求需要连接数据库时则去连接池中获取一个连接,如果有空闲的连接就去获取\n 没有则等待或报错\n :param cur:\n :return:\n \"\"\"\n conn=POOL.connection()\n cursor=conn.cursor(cursor=cur)\n return conn,cursor\n\ndef on_close(conn,cursor):\n \"\"\"\n 关闭连接,使用完毕后,需要将连接归还到连接池中\n \"\"\"\n cursor.close()\n conn.close()\ndef fetchone(sql,args,cur=pymysql.cursors.DictCursor):\n \"\"\"\n 查询一条数据\n \"\"\"\n conn,cursor = on_open(cur)\n cursor.execute(sql, args)\n result = cursor.fetchone()\n return result\n\ndef fetchall(sql,args,cur=pymysql.cursors.DictCursor):\n \"\"\"\n 满足条件的全部查询出来\n \"\"\"\n conn, cursor = on_open(cur)\n cursor.execute(sql, args)\n result = cursor.fetchall()\n return result\n\ndef exec_sql(sql,args,cur=pymysql.cursors.DictCursor):\n \"\"\"\n 增,删,改操作\n \"\"\"\n conn, cursor = on_open(cur)\n cursor.execute(sql, args)\n conn.commit()","sub_path":"MySQL/pymysql_pool.py","file_name":"pymysql_pool.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"264682768","text":"from random import randint\nfrom tkinter import *\n\nDIGIT_COUNT_MIN = 2\nDIGIT_COUNT_MAX = 10\n\n\nclass Model:\n def __init__(self):\n self.bull = 0 # Coincides digit, but not a place\n self.cow = 0 # Coincides digit and a place\n self.digit_num = 3\n self.user_number = None\n self.sec_number = None\n self.sec_number_list = []\n self.win = False\n self.round = 1\n self.wrong_answers = []\n\n def generate_digit(self):\n self.sec_number = randint(0, 10**self.digit_num - 1)\n self.sec_number_list = []\n for d in range(1, self.digit_num + 1):\n self.sec_number_list.append(\n self.sec_number % (10 ** d) // 10 ** (d - 1)\n )\n\n def estimate_value(self, user_number):\n self.bull = 0\n self.cow = 0\n sec_number_list = self.sec_number_list[:]\n self.user_number = user_number\n user_number_list = []\n n = len(str(self.user_number))\n for d in range(n):\n user_number_list.append(self.user_number % (10 ** (d + 1)) // 10 ** d)\n index_del = []\n # Counting the matching\n for i in range(n):\n if user_number_list[i] == sec_number_list[i]:\n self.cow += 1\n index_del.append(i)\n # Delete the matching\n sec_number_list = [sec_number_list[i] for i in range(n) if i not in index_del]\n user_number_list = [user_number_list[i] for i in range(n) if i not in index_del]\n # Counting the coincidences\n for i in range(len(user_number_list)):\n if user_number_list[i] in sec_number_list:\n self.bull += 1\n sec_number_list[sec_number_list.index(user_number_list[i])] = None\n\n def is_win(self, user_number):\n self.user_number = user_number\n if str(self.sec_number).zfill(self.digit_num) == \\\n str(self.user_number).zfill(self.digit_num):\n self.win = True\n else:\n self.win = False\n return self.win\n\n def start_game(self, digit_num=3):\n self.win = False\n if digit_num in range(DIGIT_COUNT_MIN, DIGIT_COUNT_MAX + 1):\n self.digit_num = digit_num\n self.generate_digit()\n self.round = 1\n\n\nclass Controller:\n def __init__(self, model):\n self.model = model\n\n def set_view(self, view):\n self.view = view\n\n def start_game(self):\n digit_num = self.view.get_game_settings()\n self.model.start_game(digit_num)\n self.view.start_game()\n\n def input_digit(self, event=None):\n digit = self.view.get_digit()\n if digit:\n self.model.wrong_answers.append(int(digit))\n if not self.model.is_win(digit):\n self.model.estimate_value(digit)\n self.view.log_wrong_answ()\n self.model.round += 1\n else:\n self.view.game_over()\n\n\nclass TkView(Frame):\n font1 = ('Consolas', 14)\n font2 = ('Consolas', 16)\n font3 = ('Consolas', 18, 'bold')\n\n def __init__(self, controller=None, model=None, master=None, **config):\n super().__init__(master)\n self.pack(expand=True, fill='both')\n self.model = model\n self.controller = controller\n self.controller.set_view(self)\n self.create_widgets()\n\n def create_widgets(self):\n # top frame with probably var\n frame_top = Frame(self)\n self.digit_var = StringVar(frame_top)\n self.digit_var.trace('w', lambda name, index, mode, sv=self.digit_var.trace:\n self.input_control(sv))\n self.answer_ent = Entry(frame_top,\n textvariable=self.digit_var,\n state='disabled',\n font= __class__.font3)\n self.answer_ent.bind('', self.controller.input_digit)\n self.answer_but = Button(frame_top,\n text='OK',\n command=self.controller.input_digit,\n bg='#bed6be',\n state='disabled',\n font=__class__.font3)\n # log\n frame_log_parent = Frame(self)\n frame_log_child = Frame(frame_log_parent)\n self.log_txt = Text(frame_log_child,\n wrap='word',\n width=20,\n height=10,\n state='disabled',\n font=__class__.font1)\n scrollbar = Scrollbar(frame_log_child,\n command=self.log_txt.yview)\n self.log_txt.config(yscrollcommand=scrollbar.set)\n self.log_line = 1\n # bottom frame with settings\n frame_bottom_parent = Frame(self, bg='grey')\n frame_bottom_child = Frame(frame_bottom_parent, bg='grey')\n start_but = Button(frame_bottom_child,\n text='START',\n command=self.controller.start_game,\n bg='#ffddaa',\n font=__class__.font3)\n label = Label(frame_bottom_child,\n text='Number of digits:',\n bg='grey',\n font=__class__.font2)\n self.digit_count_var = StringVar()\n self.digit_count_var.set(4)\n spinbox = Spinbox(frame_bottom_child,\n textvariable=self.digit_count_var,\n from_=DIGIT_COUNT_MIN, to=DIGIT_COUNT_MAX,\n width=3,\n font=__class__.font3)\n # packed\n frame_top.pack(side='top', fill='x', pady=5, padx=5)\n self.answer_ent.pack(side='left', expand='yes', fill='both')\n self.answer_but.pack(side='right')\n frame_log_parent.pack(fill='both', expand=True)\n frame_log_child.pack(fill='both', expand=True, padx=5)\n self.log_txt.pack(side='left', expand='yes', fill='both')\n scrollbar.pack(side='right', fill='y')\n frame_bottom_parent.pack(side='bottom', fill='x')\n frame_bottom_child.pack(fill='x', padx=5, pady=5)\n start_but.pack(side='top', fill='x')\n label.pack(side='left', expand='yes', fill='x', pady=5)\n spinbox.pack(side='left', pady=5)\n\n def get_game_settings(self):\n return int(self.digit_count_var.get())\n\n def input_control(self, event):\n if self.digit_var.get():\n st = self.digit_var.get()\n if not st[-1].isdigit():\n st = st[:-1]\n self.digit_var.set(st)\n\n def get_digit(self):\n digit = self.digit_var.get()\n if digit:\n if len(digit) == self.model.digit_num:\n if int(digit) in self.model.wrong_answers:\n self.answer_ent.config(bg='blue')\n self.answer_ent.after(500, lambda: self.answer_ent.config(bg='white'))\n else:\n self.answer_ent.delete(0, 'end')\n return int(digit)\n else:\n self.answer_ent.config(bg='red')\n self.answer_ent.after(500, lambda: self.answer_ent.config(bg='white'))\n\n def add_to_log(self, string):\n self.log_txt.config(state='normal')\n self.log_txt.insert('{}.{}'.format(self.log_line, 0), string)\n self.log_txt.config(state='disabled')\n self.log_txt.see('{0}.{1}'.format(self.log_line, 0))\n self.log_line += 1\n\n def log_wrong_answ(self):\n template = '\\n{}. {}: cows-{} & bulls-{}'\n message = template.format(str(self.model.round).rjust(2),\n self.model.user_number,\n self.model.cow,\n self.model.bull)\n self.add_to_log(message)\n\n def game_over(self):\n self.answer_but.config(state='disabled')\n self.answer_ent.config(state='disabled')\n message = '\\nCorrect! You find the secret number {} with {} try.'. \\\n format(self.model.sec_number, self.model.round)\n self.add_to_log(message)\n\n def start_game(self):\n self.log_line = 1\n self.log_txt.config(state='normal')\n self.log_txt.delete('1.0', 'end')\n self.log_txt.config(state='disabled')\n self.answer_but.config(state='normal')\n self.answer_ent.config(state='normal')\n message = 'Conceive {}-valued secret number, try to guess!'. \\\n format(self.model.digit_num)\n self.add_to_log(message)\n\n\ngame_model = Model()\ngame_controller = Controller(game_model)\nroot = Tk()\nroot.title('Cows & Bulls')\nroot.minsize(width=330, height=385)\ngame_view = TkView(master=root,\n controller=game_controller,\n model=game_model)\ngame_view.mainloop()\n","sub_path":"cows-and-bulls game.py","file_name":"cows-and-bulls game.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"233080084","text":"import random\r\nfrom string import ascii_uppercase\r\nimport Gallow\r\n\r\n\r\ndef welcoming():\r\n print(\"This is HANGMAN GAME!\")\r\n player_name = input(\"Please enter your name to play this game:\\n\").capitalize()\r\n print(f\"Welcome to HANGMAN GAME {player_name}! You have 8 attempts to guess the full word!\")\r\n print(\"There are multiple difficulty settings shown below, please choose one:\")\r\n print(\"For Easy type E\")\r\n print(\"For Medium type M\")\r\n print(\"For Hard type H\")\r\n return player_name\r\n\r\n\r\ndef difficulties(player_name):\r\n diff = input(f\"{player_name}, which difficulty you'd like to play?:\\n\").upper()\r\n diffs = [\"E\", \"M\", \"H\"]\r\n while diff not in diffs:\r\n print(\"You did NOT choose any difficulty, please choose one:\")\r\n diff = input().upper()\r\n if diff == 'E': #len(word) <= 4\r\n print(f\"Well {player_name}, you've chosen Easy difficulty.\")\r\n f = open(\"C:/Users/hisha/PycharmProjects/Hangman game/WordList_easy.txt\", \"r\")\r\n easy_file = f.read().split()\r\n word = random.choice(easy_file)\r\n elif diff == 'M':\r\n print(f\"Well {player_name}, you've chosen Medium difficulty.\")\r\n f = open(\"C:/Users/hisha/PycharmProjects/Hangman game/WordList_medium.txt\", \"r\")\r\n medium_file = f.read().split()\r\n word = random.choice(medium_file)\r\n elif diff == 'H':\r\n print(f\"Well {player_name}, you've chosen Hard difficulty.\")\r\n f = open(\"WordList_hard.txt\")\r\n hard_file = f.read().split()\r\n word = random.choice(hard_file)\r\n return word\r\n\r\n\r\ndef gallow_board(incorrect_letters, secret_word, correct_letters):\r\n print(Gallow.gallow[len(incorrect_letters)])\r\n for letter in secret_word:\r\n if letter in correct_letters:\r\n print(\"\\033[1;34m\", letter, end=' ' + \"\\033[0m\") # correct\r\n else:\r\n print('_', end=' ') # length of the secret word\r\n print('\\n')\r\n print(\"\\033[3;91m*****INCORRECT LETTERS*****\\033[0m\")\r\n for letter in incorrect_letters:\r\n print(\"\\033[1;91m\", letter, end=' ' + \"\\033[0m\")\r\n print('\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~')\r\n\r\n\r\ndef player_guess(incorrect_letters, secret_word, correct_letters): # Handling_errors:\r\n while True:\r\n guess = input(\"Guess a letter:\\n\").upper() # Asking the player for input\r\n if guess in correct_letters or guess in incorrect_letters: # If player already guessed the letter\r\n print(\"You have already guessed this letter\")\r\n elif len(guess) > 1: # If player inputs more than a letter\r\n print(\"Please enter only ONE letter at time\")\r\n elif len(guess) == 0: # If player inputs nothing or pressed Enter\r\n print(\"You entered NOTHING!! Please enter a letter\")\r\n elif guess not in ascii_uppercase: # If user inputs anything else but letters\r\n print(\"NOT VALID!! please enter ONLY letter\") # We can use .isalpha to accept german letters\r\n else:\r\n break\r\n if guess in secret_word: # Check player's guess\r\n correct_letters.append(guess)\r\n else:\r\n incorrect_letters.append(guess)\r\n\r\n\r\ndef check_win(incorrect_letters, secret_word, correct_letters): # If user won or lost:\r\n if len(incorrect_letters) == 8: # attempts = 8\r\n return 'loss'\r\n for i in secret_word:\r\n if i not in correct_letters:\r\n return 'no win'\r\n return 'win'\r\n\r\n\r\ndef play_game(player_name):\r\n secret_word = difficulties(player_name).upper()\r\n correct_letters = []\r\n incorrect_letters = []\r\n print(secret_word)\r\n print('The word contains', len(secret_word), 'letters')\r\n play_turn = True\r\n turn_count = 0\r\n while play_turn: # Looping the entire game till the user wins or looses\r\n gallow_board(incorrect_letters, secret_word, correct_letters)\r\n player_guess(incorrect_letters, secret_word, correct_letters)\r\n attempts = len(incorrect_letters)\r\n score = 1000\r\n points = score - (attempts * 125)\r\n '''result = {}'''\r\n\r\n win_condition = check_win(incorrect_letters, secret_word, correct_letters)\r\n if win_condition == 'loss':\r\n print(Gallow.gallow[-2])\r\n print(f\"GAME OVER {player_name}! The word was {secret_word}\")\r\n return None\r\n elif win_condition == 'win':\r\n print(Gallow.gallow[-1])\r\n print(f\"Great {player_name}, YOU WON! The word was {secret_word}\\nYour score is: {str(points)}\")\r\n turn_count += 1\r\n with open('Scoreboard.txt', 'a') as file:\r\n file.write(player_name + \" \" + str(points) + \"\\n\")\r\n return\r\n\r\n\r\ndef scoreboard():\r\n file_highscore = open('Scoreboard.txt' , 'r')\r\n scores = []\r\n for line in file_highscore.readlines():\r\n score_info = line.split()\r\n scores.append((score_info[0], int(score_info[1])))\r\n\r\n scores.sort(key = lambda x:x[1], reverse = True)\r\n print('The First 5 Highscores are:')\r\n for score, name in scores[:5]:\r\n print(name, score)\r\n\r\n\r\ndef end_game():\r\n while True:\r\n results = play_game(player_name)\r\n play_again = input('Would you like to play again? \\nPlease type Yes(y) or No(n):\\n').lower()\r\n yes_or_no = ['y', 'yes', 'no', 'n']\r\n while play_again not in yes_or_no:\r\n print('\\033[91mPlease type \"yes\" or \"y\" to play again OR\\nIf you want to end this game please type \"no\" or \"n\"\\033[0m')\r\n play_again = input('y/n: ').lower()\r\n print(play_again)\r\n\r\n if play_again == 'no' or play_again == 'n':\r\n print(f\"Thank you for your time!\")\r\n score_board = scoreboard()\r\n break\r\n elif play_again == 'yes' or play_again == 'y':\r\n print(f'Great! Game Restarted')\r\n\r\n# the whole game:\r\nplayer_name = welcoming()\r\nend_game()","sub_path":"Hangman last version.py","file_name":"Hangman last version.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"59051809","text":"#inductorClass.py\nfrom heodb import orderOfMagnitude\nfrom .passivesClass import Passive\nfrom heodb.consts import bomConsts\nfrom .componentBaseClasses import PartTable\nfrom heodb.consts import partNumberConsts as pc\n\nclass InductorTable(PartTable):\n\tdef __init__(self, db):\n\t\tPartTable.__init__(self,db)\n\t\tself.ind_type = self.elementTable.addElement(title = 'Inductor Type', \n\t\t\t\tname = 'ind_type', updatable = False, raiseWarnings = False, \n\t\t\t\toptions = ('TOROID', 'CHOKE', 'RF', 'COUPLED', 'SHIELDED', 'UNSHIELDED'))\n\t\tself.ind_windings = self.elementTable.addElement(title = 'Windings', \n\t\t\t\tname = 'ind_windings', elementType = 'INT',updatable = False, raiseWarnings = False)\n\t\tself.ind_thermal_lim = self.elementTable.addElement(title = 'T_Max', \n\t\t\t\tname = 'ind_thermal_lim', elementType = 'FLOAT', raiseWarnings = False,\n\t\t\t\tnull = True)\n\t\tself.ind_sat_curr = self.elementTable.addElement(title = 'Saturation Current', \n\t\t\t\tname = 'ind_sat_curr', elementType = 'FLOAT', raiseWarnings = False)\n\t\tself.ind_curr_rating = self.elementTable.addElement(title = 'Current Rating', \n\t\t\t\tname = 'ind_curr_rating', elementType = 'FLOAT', raiseWarnings = False)\n\t\tself.ind_tol = self.elementTable.addElement(title = 'Tolerance', \n\t\t\t\tname = 'ind_tol', elementType = 'FLOAT', raiseWarnings = False)\n\t\tself.ind_val_float = self.elementTable.addElement(title = 'Value', \n\t\t\t\tname = 'ind_val_float', elementType = 'FLOAT', raiseWarnings = False, updatable = False)\n\n\t\tself.table = 'compInductor'\n\n\tdef writeBomLine(self, bomLine):\n\t\tbomLine[bomConsts.bom_compSpec1] = self.ind_type.value\n\t\tbomLine[bomConsts.bom_compSpec2] = orderOfMagnitude(self.ind_val_float.value)[0] + 'H'\n\t\tbomLine[bomConsts.bom_compSpec3] = orderOfMagnitude(self.ind_tol.value)[0] + '%'\n\t\tbomLine[bomConsts.bom_compSpec4] = 'I_Max ' + orderOfMagnitude(self.ind_curr_rating.value)[0] + 'A'\n\t\tbomLine[bomConsts.bom_compSpec5] = 'I_Sat ' + orderOfMagnitude(self.ind_sat_curr.value)[0] + 'A'\n\t\tbomLine[bomConsts.bom_compSpec6] = orderOfMagnitude(self.ind_thermal_lim.value)[0] + 'C'\n\t\treturn bomLine\n\n\tdef readBomLine(self, bomLine):\n\t\tself.ind_type.value = bomLine[bomConsts.bom_compSpec1]\n\t\tself.ind_val_float.value = bomLine[bomConsts.bom_compSpec2]\n\t\tself.ind_tol.value = bomLine[bomConsts.bom_compSpec3]\n\t\tself.ind_curr_rating.value = bomLine[bomConsts.bom_compSpec4].split(' ')[-1]\n\t\tself.ind_sat_curr.value = bomLine[bomConsts.bom_compSpec5].split(' ')[-1]\n\t\tself.ind_thermal_lim.value = bomLine[bomConsts.bom_compSpec6]\n\t\tself.formatInput(self.getVals)\n\n\nclass Inductor(Passive):\n\tpart_class = 'L'\n\tcomp_type = 'IND'\n\n\tdef __init__(self, db):\n\t\tPassive.__init__(self, db)\n\t\tself.addComponentTable(InductorTable(db))\n\t\tself.db = db\n\t\tself.posX = '-20'\n\t\tself.posY = '20'\n\n\t@property\n\tdef comp_sub_type(self):\n\t\treturn self.ComponentTable.ind_type.value\n\n\tdef assignPartType(self):\n\t\tindType = self.ComponentTable.ind_type.value.upper()\n\t\tpackage_type = str(self.ManuInfo.package_type.value)\n\n\t\tif(round(float(self.ComponentTable.ind_windings.value)) > 1):\n\t\t\ttypeArg = 'MULTI WINDINGS'\n\t\t\ttypePairs = {typeArg: '61'}\n\n\t\telif( indType in ['SHIELDED', 'UNSHIELDED']):\n\t\t\ttypeArg = package_type\n\t\t\ttypePairs = pc.packages\n\n\t\telif( indType == 'CHOKE' ):\n\t\t\ttypeArg = indType\n\t\t\ttypePairs = {indType: '60'}\n\n\t\telif( indType == 'TOROID'):\n\t\t\ttypePairs = {'SMT': '62', 'THRU': '63', 'AXIAL': '63','RADIAL': '63'}\n\t\t\tif package_type not in typePairs:\n\t\t\t\traise UserWarning('The acceptable packages for a toroid are: {}'.format(list(typePair.keys())))\n\t\t\ttypeArg = package_type\n\n\t\telse:\n\t\t\traise UserWarning('Inductor Messed up with its part type')\n\n\t\ttry:\n\t\t\tself.PartNumber.part_type.value = typePairs[typeArg]\n\t\texcept KeyError:\n\t\t\traise UserWarning('Inductor Messed up with its part type')\n\t\t\n\n\tdef assignExactNum(self):\n\t\tdecNote = (('P',1e-12),('N',1e-9),('U',1e-6),('M',1e-3),('R',1))\n\t\tval = self.ComponentTable.ind_val_float.value\n\t\tself.PartNumber.exact_num.value = self.exactNumByValue(decNote, val)\n\nCompData = {'names': ('IND','INDUCTOR'), 'ComponentClass': Inductor, 'isIC': False }\n","sub_path":"heodb/components/inductorClass.py","file_name":"inductorClass.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"551386948","text":"#Day 1, Part 1, coded by Callum, http://picapi.xyz\n#Set floor to 0\nfloor = 0\n#Get the input from a folder.\ntable = open(\"../Inputs/Day1.txt\").read()\n#Loop through every character in the input.\nfor x in range(len(table)):\n #If it's an (, go up a floor.\n if table[x] == \"(\":\n floor += 1\n #Otherwise, if it's a ), go down a floor.\n elif table[x] == \")\":\n floor -= 1\n#At the end, print the answer!\nprint(floor)\n","sub_path":"Day 1/day1puz1.py","file_name":"day1puz1.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"} +{"seq_id":"88792263","text":"import logging\nimport time\n\n# Log objects consist of four main parts:\n# 1. The actually Logger class (AKA loggers), which exposes the interface to application code.\n# 2. Handlers which determine where to to send the log records (created by loggers)\n# 3. Filters which provide for finer tuning of determining where logs output (we will be ignoring this)\n# 4. Formatters which specify how you want the log record to look: Ex: \n\n# Lets go through each of the steps one by one\n\n# 1. Creating logger objects \n\n# This creates a logger object corresponding to 'example2' and sets its level to DEBUG\nlogger1 = logging.getLogger('example2')\nlogger1.setLevel(logging.DEBUG)\n\n# 2. Create a handler which logs the messages\n\n# This creates a handler that will log to the file example2.log\nfh = logging.FileHandler('example2.log')\nfh.setLevel(logging.DEBUG)\n\n# 3. We are skipping over filters\n\n# 4. Creating a formatter\n\nformatter1 = logging.Formatter('%(asctime)s - %(message)s')\n\n# Now that everything is created there are a few more steps to go through\n# First add the formatter to the handler\n# This means that the handler will now log as we have defined it\n\nfh.setFormatter(formatter1)\n\n# Finally, add the handler to the actual logger object\nlogger1.addHandler(fh)\n\n# Time to test out that it works as intended\n# First, it should log all levels of logs from DEBUG - CRITICAL\n# Second, it should format it